rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
bsddb_error = bsddb.DBNotFoundError | bsddb_error = bsddb.db.DBNotFoundError | def DBExtractor(bayes): # We use bsddb3 now if we can try: import bsddb3 as bsddb bsddb_error = bsddb.DBNotFoundError except ImportError: import bsddb bsddb_error = bsddb.error key = bayes.dbm.first()[0] if key not in ["saved state"]: yield key, bayes._wordinfoget(key) while True: try: key = bayes.dbm.next()[0] except ... |
out.write(self.unconvert(sectname, optname)) | newval = self.unconvert(sectname, optname) out.write(newval.replace("\n", "\n\t")) | def update_file(self, filename): '''Update the specified configuration file.''' sectname = None optname = None out = TemporaryFile() if os.path.exists(filename): f = file(filename, "r") else: # doesn't exist, so create it - all the changed options will # be added to it if self.verbose: print "Creating new configuration... |
out.write(self.unconvert(sect, opt)) | newval = self.unconvert(sect, opt) out.write(newval.replace("\n", "\n\t")) | def _add_missing(self, out, written, sect, vi, label=True): # add any missing ones, where the value does not equal the default for opt in self.options_in_section(sect): if not (sect, opt) in written and \ self.get(sect, opt) != self.default(sect, opt): if label: out.write('[') out.write(sect) out.write("]\n") label = F... |
prop_restriction = (mapi.RES_PROPERTY, (mapi.RELOP_EQ, PR_CONTENT_UNREAD, (PR_CONTENT_UNREAD, True)) ) | prop_restriction = (mapi.RES_BITMASK, (mapi.BMR_EQZ, PR_MESSAGE_FLAGS, MSGFLAG_READ)) | def GetNewUnscoredMessageGenerator(self, scoreFieldName): folder = self.msgstore._OpenEntry(self.id) table = folder.GetContentsTable(0) # Resolve the field name resolve_props = ( (mapi.PS_PUBLIC_STRINGS, "Spam"), ) resolve_ids = folder.GetIDsFromNames(resolve_props, 0) field_id = PROP_TAG( PT_I4, PROP_ID(resolve_ids[0]... |
restriction = (mapi.RES_AND, (prop_restriction, not_exist_restriction)) | class_restriction = (mapi.RES_PROPERTY, (mapi.RELOP_GE, PR_MESSAGE_CLASS_A, (PR_MESSAGE_CLASS_A, "IPM.Note"))) restriction = (mapi.RES_AND, (prop_restriction, not_exist_restriction, class_restriction)) | def GetNewUnscoredMessageGenerator(self, scoreFieldName): folder = self.msgstore._OpenEntry(self.id) table = folder.GetContentsTable(0) # Resolve the field name resolve_props = ( (mapi.PS_PUBLIC_STRINGS, "Spam"), ) resolve_ids = folder.GetIDsFromNames(resolve_props, 0) field_id = PROP_TAG( PT_I4, PROP_ID(resolve_ids[0]... |
if not html and not body: print "Couldn't find any useful body for message '%s'" \ % (self.GetField(PR_SUBJECT_A),) | def _GetMessageText(self): # This is finally reliable. The only messages this now fails for # are for "forwarded" messages, where the forwards are actually # in an attachment. Later. # Note we *dont* look in plain text attachments, which we arguably # should. import mboxutils | |
IP_LIST = r"\*|localhost|((\*|[01]?\d\d?|2[04]\d|25[0-5])\.(\*|[01]?\d" \ r"\d?|2[04]\d|25[0-5])\.(\*|[01]?\d\d?|2[04]\d|25[0-5])\.(\*" \ r"|[01]?\d\d?|2[04]\d|25[0-5]),?)+" | IP_LIST = r"\*|localhost|((\*|[01]?\d\d?|2[0-4]\d|25[0-5])\.(\*|[01]?\d" \ r"\d?|2[0-4]\d|25[0-5])\.(\*|[01]?\d\d?|2[0-4]\d|25[0-5])\.(\*" \ r"|[01]?\d\d?|2[0-4]\d|25[0-5]),?)+" | def output_for_docs(self, section=None, option=None): '''Return output suitable for inserting into documentation for the available options.''' return self._display_nice(section, option, 'as_documentation_string') |
self.fn += 1 | self.fp += 1 | def CalculateStats(self): self.Reset() for msg in msginfoDB.db: self.total += 1 m = self.__empty_msg() m.id = msg msginfoDB._getState(m) if m.c == 's': self.cls_spam += 1 if m.t == 0: self.fn += 1 elif m.c == 'h': self.cls_ham += 1 if m.t == 1: self.fp += 1 elif m.c == 'u': self.cls_unsure += 1 if m.t == 0: self.trn_un... |
self.fp += 1 | self.fn += 1 | def CalculateStats(self): self.Reset() for msg in msginfoDB.db: self.total += 1 m = self.__empty_msg() m.id = msg msginfoDB._getState(m) if m.c == 's': self.cls_spam += 1 if m.t == 0: self.fn += 1 elif m.c == 'h': self.cls_ham += 1 if m.t == 1: self.fp += 1 elif m.c == 'u': self.cls_unsure += 1 if m.t == 0: self.trn_un... |
push("SpamBayes has processed %(num_seen)d messages - " \ | for num, key in [(self.total, "sp1"), (self.trn_ham, "sp2"), (self.trn_spam, "sp3"), (self.trn_unsure_ham, "sp4"), (self.fp, "sp5"), (self.fn, "sp6")]: if num == 1: format_dict[key] = '' else: format_dict[key] = 's' for num, key in [(self.fp, "wp1"), (self.fn, "wp2")]: if num == 1: format_dict[key] = 'was a' else: form... | def GetStats(self): if self.total == 0: return ["SpamBayes has processed zero messages"] chunks = [] push = chunks.append perc_ham = 100.0 * self.cls_ham / self.total perc_spam = 100.0 * self.cls_spam / self.total perc_unsure = 100.0 * self.cls_unsure / self.total format_dict = { 'perc_spam': perc_spam, 'perc_ham': per... |
push("%(trn_ham)d message(s) were manually " \ "classified as good (with %(fp)d " \ "being false positives)." % format_dict) push("%(trn_spam)d message(s) were manually " \ "classified as spam (with %(fn)d " \ "being false negatives)." % format_dict) push("%(trn_unsure_ham)d unsure message(s) were manually " \ | push("%(trn_ham)d message%(sp2)s were manually " \ "classified as good (%(fp)d %(wp1)s false positive%(sp5)s)." \ % format_dict) push("%(trn_spam)d message%(sp3)s were manually " \ "classified as spam (%(fn)d %(wp2)s false negative%(sp6)s)." \ % format_dict) push("%(trn_unsure_ham)d unsure message%(sp4)s were manually ... | def GetStats(self): if self.total == 0: return ["SpamBayes has processed zero messages"] chunks = [] push = chunks.append perc_ham = 100.0 * self.cls_ham / self.total perc_spam = 100.0 * self.cls_spam / self.total perc_unsure = 100.0 * self.cls_unsure / self.total format_dict = { 'perc_spam': perc_spam, 'perc_ham': per... |
if not self.manager.config.training.train_manual_spam: return | assert(not self.manager.config.training.train_manual_spam, "The folder shouldn't be hooked if this is False") | def OnItemAdd(self, item): # Not sure what the best heuristics are here - for # now, we assume that if the calculated spam prob # was *not* certain-spam, or it is in the ham corpa, # then it should be trained as such. self.manager.LogDebug(2, "OnItemAdd event for SPAM folder", self, "with item", item.Subject.encode("mb... |
if config.spam_folder_id: | if config.spam_folder_id and \ self.manager.config.training.train_manual_spam: | def UpdateFolderHooks(self): config = self.manager.config.filter new_hooks = {} new_hooks.update( self._HookFolderEvents(config.watch_folder_ids, config.watch_include_sub, HamFolderItemsEvent, "filtering") ) # For spam manually moved if config.spam_folder_id: new_hooks.update( self._HookFolderEvents([config.spam_folder... |
signal.signal(signal.SIGALRM, lambda s: sys.exit(1)) | signal.signal(signal.SIGALRM, lambda s, f: sys.exit(1)) | def filter_message(hamdir, spamdir): signal.signal(signal.SIGALRM, lambda s: sys.exit(1)) signal.alarm(24 * 60 * 60) # write message to temporary file (must be on same partition) tmpfile, pathname, filename = maketmp(hamdir) try: tmpfile.write(os.environ.get("DTLINE", "")) # delivered-to line bytes = 0 blocks = [] whi... |
if self.gzipCache: | if options["Storage", "cache_use_gzip"]: | def onTrain(self, file, text, which): """Train on an uploaded or pasted message.""" self._writePreamble(_("Train")) |
code += 0x4f0000 | code += commctrl.PY_0U | def OnNotify(self, msg, hwnd, wparam, lparam): FolderSelector_Parent.OnNotify(self, hwnd, msg, wparam, lparam) format = "iii" buf = win32gui.PyMakeBuffer(struct.calcsize(format), lparam) hwndFrom, id, code = struct.unpack(format, buf) code += 0x4f0000 # hrm - wtf - commctrl uses this, and it works with mfc. *sigh* id_... |
def run(): | def run(force_UI=False): | def run(): try: opts, args = getopt.getopt(sys.argv[1:], 'hbPtcvl:e:i:d:p:o:') except getopt.error, msg: print >>sys.stderr, str(msg) + '\n\n' + __doc__ sys.exit() doTrain = False doClassify = False doExpunge = options["imap", "expunge"] imapDebug = 0 sleepTime = 0 promptForPass = False launchUI = False server = "" us... |
if not launchUI: | if not launchUI and not force_UI: | def run(): try: opts, args = getopt.getopt(sys.argv[1:], 'hbPtcvl:e:i:d:p:o:') except getopt.error, msg: print >>sys.stderr, str(msg) + '\n\n' + __doc__ sys.exit() doTrain = False doClassify = False doExpunge = options["imap", "expunge"] imapDebug = 0 sleepTime = 0 promptForPass = False launchUI = False server = "" us... |
stats = Stats(options, message_db) | stats = Stats.Stats(options, message_db) | def run(): try: opts, args = getopt.getopt(sys.argv[1:], 'hbPtcvl:e:i:d:p:o:') except getopt.error, msg: print >>sys.stderr, str(msg) + '\n\n' + __doc__ sys.exit() doTrain = False doClassify = False doExpunge = options["imap", "expunge"] imapDebug = 0 sleepTime = 0 promptForPass = False launchUI = False server = "" us... |
for x in msg.get_charsets(None): if x is not None: yield 'charset:' + x.lower() | try: for x in msg.get_charsets(None): if x is not None: yield 'charset:' + x.lower() except UnicodeEncodeError: yield 'charset:invalid_unicode' | def crack_content_xyz(msg): yield 'content-type:' + msg.get_content_type() x = msg.get_param('type') if x is not None: yield 'content-type/type:' + x.lower() for x in msg.get_charsets(None): if x is not None: yield 'charset:' + x.lower() x = msg.get('content-disposition') if x is not None: yield 'content-disposition... |
self.__dict__ = new_me.__dict__ | self.__dict__.update(new_me.__dict__) | def setPayload(self, payload): """DEPRECATED. |
self.__dict__ = new_me.__dict__ | self.__dict__.update(new_me.__dict__) | def setPayload(self, payload): """DEPRECATED. """ warnings.warn("setPayload is deprecated. Use " \ "email.message_from_string(payload, _class=" \ "SBHeaderMessage) instead.", DeprecationWarning, 2) new_me = email.message_from_string(payload, _class=SBHeaderMessage) self.__dict__ = new_me.__dict__ |
def Init(self, manager, explorer): ButtonDeleteAsEventBase.Init(self, manager, explorer) image = "delete_as_spam.bmp" self.Caption = "Delete As Spam" self.TooltipText = \ "Move the selected message to the Spam folder,\n" \ "and train the system that this is Spam." SetButtonImage(self, image, manager) | def Init(self, manager, explorer): ButtonDeleteAsEventBase.Init(self, manager, explorer) image = "delete_as_spam.bmp" self.Caption = "Delete As Spam" self.TooltipText = \ "Move the selected message to the Spam folder,\n" \ "and train the system that this is Spam." SetButtonImage(self, image, manager) | |
def Init(self, manager, explorer): ButtonDeleteAsEventBase.Init(self, manager, explorer) image = "recover_ham.bmp" self.Caption = "Recover from Spam" self.TooltipText = \ "Recovers the selected item back to the folder\n" \ "it was filtered from (or to the Inbox if this\n" \ "folder is not known), and trains the system ... | def Init(self, manager, explorer): ButtonDeleteAsEventBase.Init(self, manager, explorer) image = "recover_ham.bmp" self.Caption = "Recover from Spam" self.TooltipText = \ "Recovers the selected item back to the folder\n" \ "it was filtered from (or to the Inbox if this\n" \ "folder is not known), and trains the system ... | |
tt_text = "Move the selected message to the Spam folder,\n" \ "and train the system that this is Spam." | def SetupUI(self): manager = self.manager activeExplorer = self assert self.toolbar is None, "Should not yet have a toolbar" # Add our "Delete as ..." and "Recover as" buttons self.but_delete_as = self._AddControl( None, constants.msoControlButton, ButtonDeleteAsSpamEvent, (self.manager, self), BeginGroup = False, Tag ... | |
Tag = "SpamBayesCommand.DeleteAsSpam") | Tag = "SpamBayesCommand.DeleteAsSpam", image = "delete_as_spam.bmp") tt_text = \ "Recovers the selected item back to the folder\n" \ "it was filtered from (or to the Inbox if this\n" \ "folder is not known), and trains the system that\n" \ "this is a good message\n" | def SetupUI(self): manager = self.manager activeExplorer = self assert self.toolbar is None, "Should not yet have a toolbar" # Add our "Delete as ..." and "Recover as" buttons self.but_delete_as = self._AddControl( None, constants.msoControlButton, ButtonDeleteAsSpamEvent, (self.manager, self), BeginGroup = False, Tag ... |
Tag = "SpamBayesCommand.RecoverFromSpam") | Caption="Recover from Spam", TooltipText = tt_text, Tag = "SpamBayesCommand.RecoverFromSpam", image = "recover_ham.bmp") | def SetupUI(self): manager = self.manager activeExplorer = self assert self.toolbar is None, "Should not yet have a toolbar" # Add our "Delete as ..." and "Recover as" buttons self.but_delete_as = self._AddControl( None, constants.msoControlButton, ButtonDeleteAsSpamEvent, (self.manager, self), BeginGroup = False, Tag ... |
for attr, val in item_attrs.items(): setattr(item, attr, val) | def _AddControl(self, parent, # who the control is added to control_type, # type of control to add. events_class, events_init_args, # class/Init() args **item_attrs): # extra control attributes. # Outlook Toolbars suck :) # We have tried a number of options: temp/perm in the standard toolbar, # Always creating our own ... | |
assert response.find(options["Hammie", "header_name"]) >= 0 | assert response.find(options["Headers", "classification_header_name"]) >= 0 | def runUIAndProxy(): httpServer = UserInterfaceServer(8881) proxyUI = ProxyUserInterface(state, _recreateState) httpServer.register(proxyUI) BayesProxyListener('localhost', 8110, ('', 8111)) state.bayes.learn(tokenizer.tokenize(spam1), True) state.bayes.learn(tokenizer.tokenize(good1), False) proxyReady.set() Dibbler.r... |
from spambayes.Options import options | from spambayes.Options import options, get_pathname_option | def bool(val): return not not val |
(msg.c, msg.t) = self.db[msg.getId()] | attributes = self.db[msg.getId()] | def _getState(self, msg): if self.db is not None: try: (msg.c, msg.t) = self.db[msg.getId()] except KeyError: pass |
self.db[msg.getId()] = (msg.c, msg.t) | attributes = [] for att in msg.stored_attributes: attributes.append((att, getattr(msg, att))) self.db[msg.getId()] = attributes | def _setState(self, msg): if self.db is not None: self.db[msg.getId()] = (msg.c, msg.t) self.store() |
message_info_db_name = options["Storage", "messageinfo_storage_file"] message_info_db_name = os.path.expanduser(message_info_db_name) | message_info_db_name = get_pathname_option("Storage", "messageinfo_storage_file") | def store(self): if self.db is not None: self.db.sync() |
username = options["imap", "username"][0] if username == "": | username = options["imap", "username"] if isinstance(username, types.TupleType): username = username[0] if not username: | def _login_to_imap(self): if self.imap_logged_in: return if self.imap is None and len(options["imap", "server"]) > 0: server = options["imap", "server"][0] if server.find(':') > -1: server, port = server.split(':', 1) port = int(port) else: if options["imap", "use_ssl"]: port = 993 else: port = 143 self.imap = self.ima... |
elif trainnew and os.path.isdir(os.path.join(path, "new")): maildir_train(h, os.path.join(path, "new"), is_spam, force) | def train(h, path, is_spam, force, trainnew): if not os.path.exists(path): raise ValueError("Nonexistent path: %s" % path) elif os.path.isfile(path): mbox_train(h, path, is_spam, force) elif os.path.isdir(os.path.join(path, "cur")): maildir_train(h, os.path.join(path, "cur"), is_spam, force) elif trainnew and os.path.i... | |
elif self.command in ['RETR', 'TOP']: | elif self.command in ['RETR', 'TOP', 'CAPA']: | def isMultiline(self): """Returns True if the request should get a multiline response (assuming the response is positive). """ if self.command in ['USER', 'PASS', 'APOP', 'QUIT', 'STAT', 'DELE', 'NOOP', 'RSET', 'KILL']: return False elif self.command in ['RETR', 'TOP']: return True elif self.command in ['LIST', 'UIDL']... |
self.handlers = {'STAT': self.onStat, | self.handlers = {'CAPA': self.onCapa, 'STAT': self.onStat, | def __init__(self, clientSocket, socketMap): # Grumble: asynchat.__init__ doesn't take a 'map' argument, # hence the two-stage construction. Dibbler.BrighterAsyncChat.__init__(self) Dibbler.BrighterAsyncChat.set_socket(self, clientSocket, socketMap) self.maildrop = [spam1, good1] self.set_terminator('\r\n') self.okComm... |
pop3Server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) pop3Server.connect(('localhost', 8110)) | def runUIAndProxy(): httpServer = UserInterfaceServer(8881) proxyUI = UserInterface() httpServer.register(proxyUI, OptionsConfigurator(proxyUI)) BayesProxyListener('localhost', 8110, ('', 8111)) state.bayes.learn(tokenizer.tokenize(spam1), True) state.bayes.learn(tokenizer.tokenize(good1), False) proxyReady.set() Dibbl... | |
if type == socket.error and v[0] == 9: pass elif type == SystemExit: | if type == SystemExit: | def handle_error(self): """Let SystemExit cause an exit.""" type, v, t = sys.exc_info() if type == socket.error and v[0] == 9: # Why? Who knows... pass elif type == SystemExit: raise else: asynchat.async_chat.handle_error(self) |
while self.producer_fifo or self.ac_out_buffer: | while (self.producer_fifo or self.ac_out_buffer) and not self._closed: | def flush(self): """Flush everything in the output buffer.""" while self.producer_fifo or self.ac_out_buffer: self.initiate_send() |
fn.extend(eval(line[16:])) | unsures.extend(eval(line[16:])) | def main(): try: opts, args = getopt.getopt(sys.argv[1:], 'hiuo:', []) except getopt.error, msg: usage(1, msg) interactive = False do_unsures = False for opt, arg in opts: if opt == '-h': usage(0) elif opt == '-i': interactive = True elif opt == '-u': do_unsures = True elif opt in ('-o', '--option'): # Do the import h... |
disp = ("%."+str(options["Headers", "header_score_digits"])+"f") % prob | disp = "%.*f" % (options["Headers", "header_score_digits"], prob) | def addSBHeaders(self, prob, clues): """Add hammie header, and remember message's classification. Also, add optional headers if needed.""" |
if (header.lower() in names and not negate) or names == (): | if (header.upper() in names and not negate) or \ (header.upper() not in names and negate) or names == (): | def getHeaders(self, negate, *names): """Retrieve a group of message headers.""" headers = {} for header, value in self.items(): if (header.lower() in names and not negate) or names == (): headers[header.lower()] = value return headers |
assert(self.date is not None, "Must set date to use IMAPMessage instance.") | assert self.date is not None, \ "Must set date to use IMAPMessage instance." | def getInternalDate(self): """Retrieve the date internally associated with this message.""" assert(self.date is not None, "Must set date to use IMAPMessage instance.") return self.date |
all_flags = [] if self.deleted: all_flags.append("\\DELETED") if self.answered: all_flags.append("\\ANSWERED") if self.flagged: all_flags.append("\\FLAGGED") if self.seen: all_flags.append("\\SEEN") if self.draft: all_flags.append("\\DRAFT") if self.draft: all_flags.append("\\RECENT") return all_flags | return list(self._flags_iter()) | def flags(self): """Return the message flags.""" all_flags = [] if self.deleted: all_flags.append("\\DELETED") if self.answered: all_flags.append("\\ANSWERED") if self.flagged: all_flags.append("\\FLAGGED") if self.seen: all_flags.append("\\SEEN") if self.draft: all_flags.append("\\DRAFT") if self.draft: all_flags.appe... |
self.set_payload(self.func(body=True, headers=True)) | self.set_payload(self.func(body=True)) for headerstr in self.func(headers=True).split('\r\n'): header, value = headerstr.split(':') self[header] = value.strip() | def load(self): self.set_payload(self.func(body=True, headers=True)) |
def __init__(self, file_name, directory): | def __init__(self, file_name=None, directory=None): | def __init__(self, file_name, directory): """Constructor(message file name, corpus directory name).""" date = imaplib.Time2Internaldate(time.time())[1:-1] IMAPMessage.__init__(self, date) FileCorpus.FileMessage.__init__(self, file_name, directory) self.id = file_name self.directory = directory |
self.directory = directory | def __init__(self, file_name, directory): """Constructor(message file name, corpus directory name).""" date = imaplib.Time2Internaldate(time.time())[1:-1] IMAPMessage.__init__(self, date) FileCorpus.FileMessage.__init__(self, file_name, directory) self.id = file_name self.directory = directory | |
def create(self, key, directory): | def create(self, key, directory, content=None): | def create(self, key, directory): '''Create a message object from a filename in a directory''' return IMAPFileMessage(key, directory) |
return IMAPFileMessage(key, directory) | if content is None: return IMAPFileMessage(key, directory) msg = email.message_from_string(content, _class=IMAPFileMessage, strict=False) msg.id = key msg.file_name = key msg.directory = directory return msg | def create(self, key, directory): '''Create a message object from a filename in a directory''' return IMAPFileMessage(key, directory) |
msg.append("Subject:SpamBayes Status") msg.append('From:"SpamBayes" <no-reply@localhost>') | msg.append("Subject: SpamBayes Status") msg.append('From: "SpamBayes" <no-reply@spambayes.invalid>') | def buildStatusMessage(self, body=False, headers=False): """Build a message containing the current status message. |
msg.append(state.warning or "SpamBayes operating correctly.") | msg.append("POP3 proxy running on %s, proxying to %s." % \ (state.proxyPortsString, state.serversString)) msg.append("Active POP3 conversations: %s." % \ (state.activeSessions,)) msg.append("POP3 conversations this session: %s." % \ (state.totalSessions,)) msg.append("IMAP server running on %s." % \ (state.serverPortSt... | def buildStatusMessage(self, body=False, headers=False): """Build a message containing the current status message. |
about = 'Subject: About SpamBayes\r\n' \ 'From: "SpamBayes" <no-reply@localhost>\r\n\r\n' \ 'See <http://spambayes.org>.\r\n' | state.buildServerStrings() about = 'Subject: About SpamBayes / POP3DND\r\n' \ 'From: "SpamBayes" <no-reply@spambayes.invalid>\r\n\r\n' \ '%s\r\nSee <http://spambayes.org>.\r\n' % (__doc__,) | def createMessages(self): """Create the special messages that live in this mailbox.""" state.buildStatusStrings() # This about message could have a bit more content! about = 'Subject: About SpamBayes\r\n' \ 'From: "SpamBayes" <no-reply@localhost>\r\n\r\n' \ 'See <http://spambayes.org>.\r\n' date = imaplib.Time2Internal... |
def __init__(self, id, ham, spam, unsure, inbox): | def __init__(self, id, ham, spam, unsure, train_spam, inbox): | def __init__(self, id, ham, spam, unsure, inbox): MemoryAccount.__init__(self, id) self.mailboxes = {"SPAM" : spam, "UNSURE" : unsure, "TRAIN_AS_HAM" : ham, "INBOX" : inbox} |
class MyBayesProxy(POP3ProxyBase): | class RedirectingBayesProxy(POP3ProxyBase): | def buildProtocol(self, addr): """Create an instance of a subclass of Protocol, passing a single parameter.""" if self.parameter is not None: p = self.protocol(self.parameter) else: p = self.protocol() p.factory = self return p |
intercept_message = 'From: "Spambayes" <no-reply@localhost>\r\n' \ | intercept_message = 'From: "Spambayes" <no-reply@spambayes.invalid>\r\n' \ | def buildProtocol(self, addr): """Create an instance of a subclass of Protocol, passing a single parameter.""" if self.parameter is not None: p = self.protocol(self.parameter) else: p = self.protocol() p.factory = self return p |
stream = cStringIO.StringIO() traceback.print_exc(None, stream) details = stream.getvalue() detailLines = details.strip().split('\n') dottedDetails = '\n.'.join(detailLines) headerName = 'X-Spambayes-Exception' header = Header(dottedDetails, header_name=headerName) headers, body = re.split(r'\n\r?\n', messageText, 1) h... | messageText, details = \ message.insert_exception_header(messageText) | def onRetr(self, command, args, response): """Classifies the message. If the result is ham, then simply pass it through. If the result is an unsure or spam, move it to the appropriate IMAP folder.""" # XXX This is all almost from sb_server! We could just # XXX extract that out into a function and call it here. |
class MyBayesProxyListener(Dibbler.Listener): | class RedirectingBayesProxyListener(Dibbler.Listener): | def onUnknown(self, command, args, response): """Default handler; returns the server's response verbatim.""" return response |
MyBayesProxy objects to serve them. | RedirectingBayesProxy objects to serve them. | def onUnknown(self, command, args, response): """Default handler; returns the server's response verbatim.""" return response |
Dibbler.Listener.__init__(self, proxyPort, MyBayesProxy, proxyArgs) | Dibbler.Listener.__init__(self, proxyPort, RedirectingBayesProxy, proxyArgs) | def __init__(self, serverName, serverPort, proxyPort, spam, unsure): proxyArgs = (serverName, serverPort, spam, unsure) Dibbler.Listener.__init__(self, proxyPort, MyBayesProxy, proxyArgs) print 'Listener on port %s is proxying %s:%d' % \ (_addressPortStr(proxyPort), serverName, serverPort) |
state.imap_port = options["imapserver", "port"] | def setup(): # Setup state, app, boxes, trainers and account state.createWorkers() proxyListeners = [] app = Application("SpambayesIMAPServer") spam_box = SpambayesMailbox("Spam", 0, options["Storage", "spam_cache"]) unsure_box = SpambayesMailbox("Unsure", 1, options["Storage", "unknown_cache"]) ham_train_box = Spamba... | |
app = Application("SpambayesIMAPServer") spam_box = SpambayesMailbox("Spam", 0, options["Storage", "spam_cache"]) unsure_box = SpambayesMailbox("Unsure", 1, options["Storage", "unknown_cache"]) | spam_box = SpambayesMailbox("Spam", 0, options["Storage", "spam_cache"]) unsure_box = SpambayesMailbox("Unsure", 1, options["Storage", "unknown_cache"]) | def setup(): # Setup state, app, boxes, trainers and account state.createWorkers() proxyListeners = [] app = Application("SpambayesIMAPServer") spam_box = SpambayesMailbox("Spam", 0, options["Storage", "spam_cache"]) unsure_box = SpambayesMailbox("Unsure", 1, options["Storage", "unknown_cache"]) ham_train_box = Spamba... |
inbox = SpambayesInbox(3) spam_trainer = Trainer(spam_box, True) | spam_train_cache = os.path.join(options["Storage", "ham_cache"], "..", "spam_to_train") spam_train_box = SpambayesMailbox("TrainAsSpam", 3, spam_train_cache) inbox = SpambayesInbox(4) spam_trainer = Trainer(spam_train_box, True) | def setup(): # Setup state, app, boxes, trainers and account state.createWorkers() proxyListeners = [] app = Application("SpambayesIMAPServer") spam_box = SpambayesMailbox("Spam", 0, options["Storage", "spam_cache"]) unsure_box = SpambayesMailbox("Unsure", 1, options["Storage", "unknown_cache"]) ham_train_box = Spamba... |
spam_box.addListener(spam_trainer) | spam_train_box.addListener(spam_trainer) | def setup(): # Setup state, app, boxes, trainers and account state.createWorkers() proxyListeners = [] app = Application("SpambayesIMAPServer") spam_box = SpambayesMailbox("Spam", 0, options["Storage", "spam_cache"]) unsure_box = SpambayesMailbox("Unsure", 1, options["Storage", "unknown_cache"]) ham_train_box = Spamba... |
inbox) | spam_train_box, inbox) | def setup(): # Setup state, app, boxes, trainers and account state.createWorkers() proxyListeners = [] app = Application("SpambayesIMAPServer") spam_box = SpambayesMailbox("Spam", 0, options["Storage", "spam_cache"]) unsure_box = SpambayesMailbox("Unsure", 1, options["Storage", "unknown_cache"]) ham_train_box = Spamba... |
state.imap_port = options["imapserver", "port"] app.listenTCP(state.imap_port, f) | reactor.listenTCP(state.imap_port, f) | def setup(): # Setup state, app, boxes, trainers and account state.createWorkers() proxyListeners = [] app = Application("SpambayesIMAPServer") spam_box = SpambayesMailbox("Spam", 0, options["Storage", "spam_cache"]) unsure_box = SpambayesMailbox("Unsure", 1, options["Storage", "unknown_cache"]) ham_train_box = Spamba... |
listener = MyBayesProxyListener(server, serverPort, proxyPort, spam_box, unsure_box) | listener = RedirectingBayesProxyListener(server, serverPort, proxyPort, spam_box, unsure_box) | def setup(): # Setup state, app, boxes, trainers and account state.createWorkers() proxyListeners = [] app = Application("SpambayesIMAPServer") spam_box = SpambayesMailbox("Spam", 0, options["Storage", "spam_cache"]) unsure_box = SpambayesMailbox("Unsure", 1, options["Storage", "unknown_cache"]) ham_train_box = Spamba... |
httpServer = UserInterfaceServer(state.uiPort) serverUI = ServerUserInterface(state, _recreateState) httpServer.register(serverUI) return app | def setup(): # Setup state, app, boxes, trainers and account state.createWorkers() proxyListeners = [] app = Application("SpambayesIMAPServer") spam_box = SpambayesMailbox("Spam", 0, options["Storage", "spam_cache"]) unsure_box = SpambayesMailbox("Unsure", 1, options["Storage", "unknown_cache"]) ham_train_box = Spamba... | |
opts, args = getopt.getopt(sys.argv[1:], 'hbd:D:u:o:') | opts, args = getopt.getopt(sys.argv[1:], 'ho:') | def run(): # Read the arguments. try: opts, args = getopt.getopt(sys.argv[1:], 'hbd:D:u:o:') except getopt.error, msg: print >>sys.stderr, str(msg) + '\n\n' + __doc__ sys.exit() launchUI = False for opt, arg in opts: if opt == '-h': print >>sys.stderr, __doc__ sys.exit() elif opt == '-b': launchUI = True elif opt == '... |
launchUI = False | def run(): # Read the arguments. try: opts, args = getopt.getopt(sys.argv[1:], 'hbd:D:u:o:') except getopt.error, msg: print >>sys.stderr, str(msg) + '\n\n' + __doc__ sys.exit() launchUI = False for opt, arg in opts: if opt == '-h': print >>sys.stderr, __doc__ sys.exit() elif opt == '-b': launchUI = True elif opt == '... | |
elif opt == '-b': launchUI = True | def run(): # Read the arguments. try: opts, args = getopt.getopt(sys.argv[1:], 'hbd:D:u:o:') except getopt.error, msg: print >>sys.stderr, str(msg) + '\n\n' + __doc__ sys.exit() launchUI = False for opt, arg in opts: if opt == '-h': print >>sys.stderr, __doc__ sys.exit() elif opt == '-b': launchUI = True elif opt == '... | |
print "and engine %s," % (get_version_string(),) | print get_version_string() | def run(): # Read the arguments. try: opts, args = getopt.getopt(sys.argv[1:], 'hbd:D:u:o:') except getopt.error, msg: print >>sys.stderr, str(msg) + '\n\n' + __doc__ sys.exit() launchUI = False for opt, arg in opts: if opt == '-h': print >>sys.stderr, __doc__ sys.exit() elif opt == '-b': launchUI = True elif opt == '... |
print "with twisted version %s.\n" % (twisted_version,) app = setup() thread.start_new_thread(Dibbler.run, (launchUI,)) app.run(save=False) | print "Twisted version %s.\n" % (twisted_version,) setup() thread.start_new_thread(Dibbler.run, ()) reactor.run() | def run(): # Read the arguments. try: opts, args = getopt.getopt(sys.argv[1:], 'hbd:D:u:o:') except getopt.error, msg: print >>sys.stderr, str(msg) + '\n\n' + __doc__ sys.exit() launchUI = False for opt, arg in opts: if opt == '-h': print >>sys.stderr, __doc__ sys.exit() elif opt == '-b': launchUI = True elif opt == '... |
self.rfc822_command = "RFC822.PEEK" | self.rfc822_command = "BODY.PEEK[]" | def __init__(self): message.Message.__init__(self) self.folder = None self.previous_folder = None self.rfc822_command = "RFC822.PEEK" self.got_substance = False |
print 'Skipping unparseable message: %s' % e return self._headers = new_msg._headers self._unixfrom = new_msg._unixfrom self._payload = new_msg._payload self._charset = new_msg._charset self.preamble = new_msg.preamble self.epilogue = new_msg.epilogue self._default_type = new_msg._default_type if not self.has_key(optio... | self.invalid = True stream = StringIO.StringIO() traceback.print_exc(None, stream) details = stream.getvalue() detailLines = details.strip().split('\n') dottedDetails = '\n.'.join(detailLines) headerName = 'X-Spambayes-Exception' header = Header(dottedDetails, header_name=headerName) headers, body = re.split(... | def get_substance(self): '''Retrieve the RFC822 message from the IMAP server and set as the substance of this message.''' if self.got_substance: return if not self.uid or not self.id: print "Cannot get substance of message without an id and an UID" return imap.SelectFolder(self.folder.name) # We really want to use RFC8... |
print "Training took %s seconds, %s messages were trained" \ | print "Training took %.4f seconds, %s messages were trained" \ | def Train(self): if options["globals", "verbose"]: t = time.time() |
print "Classifying took", time.time() - t, "seconds." | print "Classifying took %.4f seconds." % (time.time() - t,) | def Filter(self): if options["globals", "verbose"]: t = time.time() count = {} count["ham"] = 0 count["spam"] = 0 count["unsure"] = 0 |
return self["Date"] | return imaplib.Time2Internaldate(time.mktime(parsedate(self["Date"]))) | def extractTime(self): # When we create a new copy of a message, we need to specify # a timestamp for the message. Ideally, this would be the # timestamp from the message itself, but for the moment, we # just use the current time. try: return self["Date"] except KeyError: return imaplib.Time2Internaldate(time.time()) |
new_id = "" | def Save(self): # we can't actually update the message with IMAP # so what we do is create a new message and delete the old one time_stamp = self.extractTime() response = imap.append(self.folder.name, None, time_stamp, self.as_string()) self._check(response, 'append') # we need to update the uid, as it will have change... | |
while 1: | while True: | def Logout(self, expunge): # sign off if expunge: imap.expunge() imap.logout() |
self.serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.serverSocket.connect((serverName, serverPort)) self.serverIn = self.serverSocket.makefile('r') self.push(self.serverIn.readline()) | self.command = '' self.args = '' self.isClosing = False self.seenAllHeaders = False self.startTime = 0 self.serverSocket = ServerLineReader(serverName, serverPort, self.onServerLine) | def __init__(self, clientSocket, serverName, serverPort): BrighterAsyncChat.__init__(self, clientSocket) self.request = '' self.set_terminator('\r\n') self.serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.serverSocket.connect((serverName, serverPort)) self.serverIn = self.serverSocket.makefile('r')... |
def isMultiline(self, command, args): """Returns True if the given request should get a multiline | def onServerLine(self, line): """A line of response has been received from the POP3 server.""" isFirstLine = not self.response self.response = self.response + line self.seenAllHeaders = self.seenAllHeaders or line in ['\r\n', '\n'] if not line: self.isClosing = True if not self.command: self.push(self.response) s... | def isMultiline(self, command, args): """Returns True if the given request should get a multiline response (assuming the response is positive). """ if command in ['USER', 'PASS', 'APOP', 'QUIT', 'STAT', 'DELE', 'NOOP', 'RSET', 'KILL']: return False elif command in ['RETR', 'TOP']: return True elif command in ['LIST', '... |
if command in ['USER', 'PASS', 'APOP', 'QUIT', 'STAT', 'DELE', 'NOOP', 'RSET', 'KILL']: | if self.command in ['USER', 'PASS', 'APOP', 'QUIT', 'STAT', 'DELE', 'NOOP', 'RSET', 'KILL']: | def isMultiline(self, command, args): """Returns True if the given request should get a multiline response (assuming the response is positive). """ if command in ['USER', 'PASS', 'APOP', 'QUIT', 'STAT', 'DELE', 'NOOP', 'RSET', 'KILL']: return False elif command in ['RETR', 'TOP']: return True elif command in ['LIST', '... |
elif command in ['RETR', 'TOP']: | elif self.command in ['RETR', 'TOP']: | def isMultiline(self, command, args): """Returns True if the given request should get a multiline response (assuming the response is positive). """ if command in ['USER', 'PASS', 'APOP', 'QUIT', 'STAT', 'DELE', 'NOOP', 'RSET', 'KILL']: return False elif command in ['RETR', 'TOP']: return True elif command in ['LIST', '... |
elif command in ['LIST', 'UIDL']: | elif self.command in ['LIST', 'UIDL']: | def isMultiline(self, command, args): """Returns True if the given request should get a multiline response (assuming the response is positive). """ if command in ['USER', 'PASS', 'APOP', 'QUIT', 'STAT', 'DELE', 'NOOP', 'RSET', 'KILL']: return False elif command in ['RETR', 'TOP']: return True elif command in ['LIST', '... |
def readResponse(self, command, args): """Reads the POP3 server's response and returns a tuple of (response, isClosing, timedOut). isClosing is True if the server closes the socket, which tells found_terminator() to close when the response has been sent. timedOut is set if a TOP or RETR request was still arriving aft... | def readResponse(self, command, args): """Reads the POP3 server's response and returns a tuple of (response, isClosing, timedOut). isClosing is True if the server closes the socket, which tells found_terminator() to close when the response has been sent. timedOut is set if a TOP or RETR request was still arriving aft... | |
self.serverSocket.sendall(self.request + '\r\n') | self.serverSocket.push(self.request + '\r\n') | def found_terminator(self): """Asynchat override.""" # Send the request to the server and read the reply. if self.request.strip().upper() == 'KILL': self.serverSocket.sendall('QUIT\r\n') self.send("+OK, dying.\r\n") self.shutdown(2) self.close() raise SystemExit self.serverSocket.sendall(self.request + '\r\n') if self.... |
command, args = ('', '') else: | self.command = self.args = '' else: | def found_terminator(self): """Asynchat override.""" # Send the request to the server and read the reply. if self.request.strip().upper() == 'KILL': self.serverSocket.sendall('QUIT\r\n') self.send("+OK, dying.\r\n") self.shutdown(2) self.close() raise SystemExit self.serverSocket.sendall(self.request + '\r\n') if self.... |
command = splitCommand[0].upper() args = splitCommand[1:] rawResponse, isClosing, timedOut = self.readResponse(command, args) | self.command = splitCommand[0].upper() self.args = splitCommand[1:] self.startTime = time.time() self.request = '' def onResponse(self): | def found_terminator(self): """Asynchat override.""" # Send the request to the server and read the reply. if self.request.strip().upper() == 'KILL': self.serverSocket.sendall('QUIT\r\n') self.send("+OK, dying.\r\n") self.shutdown(2) self.close() raise SystemExit self.serverSocket.sendall(self.request + '\r\n') if self.... |
cookedResponse = self.onTransaction(command, args, rawResponse) self.push(cookedResponse) self.request = '' if timedOut: while True: line = self.serverIn.readline() if not line: isClosing = True break elif line == '.\r\n': self.push(line) break else: self.push(line) if isClosing: | cooked = self.onTransaction(self.command, self.args, self.response) self.push(cooked) if self.isClosing: | def found_terminator(self): """Asynchat override.""" # Send the request to the server and read the reply. if self.request.strip().upper() == 'KILL': self.serverSocket.sendall('QUIT\r\n') self.send("+OK, dying.\r\n") self.shutdown(2) self.close() raise SystemExit self.serverSocket.sendall(self.request + '\r\n') if self.... |
.banner { background: | .banner { background: border-top: 1px solid black; border-bottom: 1px solid black } | def __init__(self, uiPort, bayes): uiArgs = (bayes,) Listener.__init__(self, uiPort, UserInterface, uiArgs) |
<span class='header'>Spambayes proxy: %s</span></div> | <span class='header'> Spambayes proxy: %s</span></div> | def __init__(self, uiPort, bayes): uiArgs = (bayes,) Listener.__init__(self, uiPort, UserInterface, uiArgs) |
<input type='submit' value='Shutdown now'> | %s | def __init__(self, uiPort, bayes): uiArgs = (bayes,) Listener.__init__(self, uiPort, UserInterface, uiArgs) |
requestLine, headers = self.request.split('\r\n', 1) | requestLine, headers = (self.request+'\r\n').split('\r\n', 1) | def found_terminator(self): """Asynchat override. Read and parse the HTTP request and call an on<Command> handler.""" requestLine, headers = self.request.split('\r\n', 1) try: method, url, version = requestLine.strip().split() except ValueError: self.pushError(400, "Malformed request: '%s'" % requestLine) # XXX: 400??... |
self.pushOKHeaders('image/gif') | inOneHour = time.gmtime(time.time() + 3600) expiryDate = time.strftime('%a, %d %b %Y %H:%M:%S GMT', inOneHour) extraHeaders = {'Expires': expiryDate} self.pushOKHeaders('image/gif', extraHeaders) | def onRequest(self, path, params): """Handles a decoded HTTP request.""" if path == '/': path = '/Home' if path == '/helmet.gif': self.pushOKHeaders('image/gif') self.push(self.helmet) else: try: name = path[1:].capitalize() handler = getattr(self, 'on' + name) except AttributeError: self.pushError(404, "Not found: '%... |
self.pushError(404, "Not found: '%s'" % url) | self.pushError(404, "Not found: '%s'" % path) | def onRequest(self, path, params): """Handles a decoded HTTP request.""" if path == '/': path = '/Home' if path == '/helmet.gif': self.pushOKHeaders('image/gif') self.push(self.helmet) else: try: name = path[1:].capitalize() handler = getattr(self, 'on' + name) except AttributeError: self.pushError(404, "Not found: '%... |
self.push(self.footer % timeString) def pushOKHeaders(self, contentType): self.push("HTTP/1.0 200 OK\r\n") | if status.useDB: self.push(self.footer % (timeString, self.shutdownDB)) else: self.push(self.footer % (timeString, self.shutdownPickle)) def pushOKHeaders(self, contentType, extraHeaders={}): timeNow = time.gmtime(time.time()) httpNow = time.strftime('%a, %d %b %Y %H:%M:%S GMT', timeNow) self.push("HTTP/1.1 200 OK\r\n... | def onRequest(self, path, params): """Handles a decoded HTTP request.""" if path == '/': path = '/Home' if path == '/helmet.gif': self.pushOKHeaders('image/gif') self.push(self.helmet) else: try: name = path[1:].capitalize() handler = getattr(self, 'on' + name) except AttributeError: self.pushError(404, "Not found: '%... |
summary = """POP3 proxy running on port <b>%(proxyPort)d</b>, proxying to <b>%(serverName)s:%(serverPort)d</b>.<br> Active POP3 conversations: <b>%(activeSessions)d</b>.<br> POP3 conversations this session: <b>%(totalSessions)d</b>.<br> Emails classified this session: <b>%(numSpams)d</b> spam, <b>%(numHams)d</b> ham, <... | body = (self.pageSection % ('Status', self.summary % status.__dict__)+ self.pageSection % ('Word query', self.wordQuery)+ self.pageSection % ('Train', self.train)) | def onHome(self, params): summary = """POP3 proxy running on port <b>%(proxyPort)d</b>, proxying to <b>%(serverName)s:%(serverPort)d</b>.<br> Active POP3 conversations: <b>%(activeSessions)d</b>.<br> POP3 conversations this session: <b>%(totalSessions)d</b>.<br> Emails classified this session: <b>%(numSpams)d</b> spam,... |
self.push("<p><b>Shutdown.</b> Goodbye.</p>") self.push(' ') | if params['how'].lower().find('save') >= 0: if not status.useDB and status.pickleName: self.push("<b>Saving...</b>") self.push(' ') fp = open(status.pickleName, 'wb') cPickle.dump(self.bayes, fp, 1) fp.close() self.push("<b>Shutdown</b>. Goodbye.") self.push(' ') | def onShutdown(self, params): self.push("<p><b>Shutdown.</b> Goodbye.</p>") self.push(' ') # Acts as a flush for small buffers. self.shutdown(2) self.close() raise SystemExit |
f.write("From ???@???\n") | f.write("From pop3proxy@spambayes.org Sat Jan 31 00:00:00 2000\n") | def onUpload(self, params): message = params.get('file') or params.get('text') isSpam = (params['which'] == 'spam') # Append the message to a file, to make it easier to rebuild # the database later. message = message.replace('\r\n', '\n').replace('\r', '\n') if isSpam: f = open("_pop3proxyspam.mbox", "a") else: f = ope... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.