rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
mgr.stats.RecordClassification(prob) | def filter_message(msg, mgr, all_actions=True): config = mgr.config.filter prob = mgr.score(msg) mgr.stats.RecordClassification(prob) prob_perc = prob * 100 if prob_perc >= config.spam_threshold: disposition = "Yes" attr_prefix = "spam" elif prob_perc >= config.unsure_threshold: disposition = "Unsure" attr_prefix = "un... | |
msg.SetField(mgr.config.general.field_score_name, prob) if all_actions: msg.RememberMessageCurrentFolder() msg.Save() | for i in range(3): try: msg.SetField(mgr.config.general.field_score_name, prob) if all_actions: msg.RememberMessageCurrentFolder() msg.Save() break except ms.ObjectChangedException: mgr.LogDebug(1, "Got ObjectChanged changed - " \ "trying again...") msg.dirty = False msg.mapi_object = None else: mgr.LogDebug(0... | def filter_message(msg, mgr, all_actions=True): config = mgr.config.filter prob = mgr.score(msg) mgr.stats.RecordClassification(prob) prob_perc = prob * 100 if prob_perc >= config.spam_threshold: disposition = "Yes" attr_prefix = "spam" elif prob_perc >= config.unsure_threshold: disposition = "Unsure" attr_prefix = "un... |
self.connect((serverName, serverPort)) | try: self.connect((serverName, serverPort)) except socket.error, e: print >>sys.stderr, "Can't connect to %s:%d: %s" % \ (serverName, serverPort, e) self.close() self.lineCallback('') | def __init__(self, serverName, serverPort, lineCallback): BrighterAsyncChat.__init__(self) self.lineCallback = lineCallback self.request = '' self.set_terminator('\r\n') self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.connect((serverName, serverPort)) |
if self.request.strip().upper() == 'KILL': self.serverSocket.sendall('QUIT\r\n') self.send("+OK, dying.\r\n") self.serverSocket.shutdown(2) self.serverSocket.close() | verb = self.request.strip().upper() if verb == 'KILL': | def found_terminator(self): """Asynchat override.""" if self.request.strip().upper() == 'KILL': self.serverSocket.sendall('QUIT\r\n') self.send("+OK, dying.\r\n") self.serverSocket.shutdown(2) self.serverSocket.close() self.shutdown(2) self.close() raise SystemExit |
cooked = self.onTransaction(self.command, self.args, self.response) self.push(cooked) | if self.response: cooked = self.onTransaction(self.command, self.args, self.response) self.push(cooked) | def onResponse(self): # Pass the request and the raw response to the subclass and # send back the cooked response. cooked = self.onTransaction(self.command, self.args, self.response) self.push(cooked) |
return POP3ProxyBase.send(self, data) | try: return POP3ProxyBase.send(self, data) except socket.error: self.close() | def send(self, data): """Logs the data to the log file.""" self.logFile.write(data) self.logFile.flush() return POP3ProxyBase.send(self, data) |
status.activeSessions -= 1 POP3ProxyBase.close(self) | if not self.isClosed: self.isClosed = True status.activeSessions -= 1 POP3ProxyBase.close(self) | def close(self): status.activeSessions -= 1 POP3ProxyBase.close(self) |
def __init__(self, uiPort, bayes): | def __init__(self, uiPort, bayes, socketMap=asyncore.socket_map): | def __init__(self, uiPort, bayes): uiArgs = (bayes,) Listener.__init__(self, uiPort, UserInterface, uiArgs) |
Listener.__init__(self, uiPort, UserInterface, uiArgs) | Listener.__init__(self, uiPort, UserInterface, uiArgs, socketMap=socketMap) | def __init__(self, uiPort, bayes): uiArgs = (bayes,) Listener.__init__(self, uiPort, UserInterface, uiArgs) |
body { font: 90%% arial, swiss, helvetica } | body { font: 90%% arial, swiss, helvetica; margin: 0 } | def __init__(self, uiPort, bayes): uiArgs = (bayes,) Listener.__init__(self, uiPort, UserInterface, uiArgs) |
bodyStart = """<body style='margin: 0'> | bodyStart = """<body> | def __init__(self, uiPort, bayes): uiArgs = (bayes,) Listener.__init__(self, uiPort, UserInterface, uiArgs) |
<form action='/shutdown'> | <form action='/shutdown' method='POST'> | def __init__(self, uiPort, bayes): uiArgs = (bayes,) Listener.__init__(self, uiPort, UserInterface, uiArgs) |
<tr><td class='banner'> Spambayes Proxy, %s. | <tr><td class='banner'> <a href='/'>Spambayes Proxy</a>, %s. | def __init__(self, uiPort, bayes): uiArgs = (bayes,) Listener.__init__(self, uiPort, UserInterface, uiArgs) |
</td></tr></table></form>\n""" | </td></tr></table></form> </body></html>\n""" | def __init__(self, uiPort, bayes): uiArgs = (bayes,) Listener.__init__(self, uiPort, UserInterface, uiArgs) |
<input name='word' type='text' size='30'> | <input name='word' value='' type='text' size='30'> | def __init__(self, uiPort, bayes): uiArgs = (bayes,) Listener.__init__(self, uiPort, UserInterface, uiArgs) |
train = """<form action='/upload' method='POST' | upload = """<form action='/%s' method='POST' | def __init__(self, uiPort, bayes): uiArgs = (bayes,) Listener.__init__(self, uiPort, UserInterface, uiArgs) |
Either upload a message file: <input type='file' name='file'><br> Or paste the whole message (incuding headers) here:<br> <textarea name='text' rows='3' cols='60'></textarea><br> Is this message <input type='radio' name='which' value='ham'>Ham</input> or <input type='radio' name='which' value='spam' checked>Spam</input... | Either upload a message file: <input type='file' name='file' value=''><br> Or paste the whole message (incuding headers) here:<br> <textarea name='text' rows='3' cols='60'></textarea><br> %s </form>""" uploadSumbit = """<input type='submit' name='which' value='%s'>""" train = upload % ('train', (uploadSumbit % "Train... | def __init__(self, uiPort, bayes): uiArgs = (bayes,) Listener.__init__(self, uiPort, UserInterface, uiArgs) |
self.pageSection % ('Word query', self.wordQuery)+ self.pageSection % ('Train', self.train)) | self.pageSection % ('Train', self.train)+ self.pageSection % ('Classify a message', self.classify)+ self.pageSection % ('Word query', self.wordQuery)) | def onHome(self, params): """Serve up the homepage.""" body = (self.pageSection % ('Status', self.summary % status.__dict__)+ self.pageSection % ('Word query', self.wordQuery)+ self.pageSection % ('Train', self.train)) self.push(body) |
def onUpload(self, params): | def onTrain(self, params): | def onUpload(self, params): """Train on an uploaded or pasted message.""" # Upload or paste? Spam or ham? message = params.get('file') or params.get('text') isSpam = (params['which'] == 'spam') |
isSpam = (params['which'] == 'spam') | isSpam = (params['which'] == 'Train as Spam') | def onUpload(self, params): """Train on an uploaded or pasted message.""" # Upload or paste? Spam or ham? message = params.get('file') or params.get('text') isSpam = (params['which'] == 'spam') |
self.bayes.learn(tokenizer.tokenize(message), isSpam, True) | tokens = tokenizer.tokenize(message) self.bayes.learn(tokens, isSpam, True) | def onUpload(self, params): """Train on an uploaded or pasted message.""" # Upload or paste? Spam or ham? message = params.get('file') or params.get('text') isSpam = (params['which'] == 'spam') |
info = "'%s' does not appear in the database." % word body = (self.pageSection % ("Statistics for '%s'" % word, info) + self.pageSection % ('Word query', self.wordQuery)) | info = "%r does not appear in the database." % word query = self.setFieldValue(self.wordQuery, 'word', params['word']) body = (self.pageSection % ("Statistics for %r" % word, info) + self.pageSection % ('Word query', query)) | def onWordquery(self, params): word = params['word'] word = word.lower() try: # Must be a better way to get __dict__ for a new-style class... wi = self.bayes.wordinfo[word] members = dict(map(lambda n: (n, getattr(wi, n)), wi.__slots__)) members['atime'] = time.asctime(time.localtime(members['atime'])) info = """Number... |
return "-ERR Unknown command: '%s'\r\n" % command | return "-ERR Unknown command: %s\r\n" % repr(command) | def onUnknown(self, command, args): """Unknown POP3 command.""" return "-ERR Unknown command: '%s'\r\n" % command |
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.connect(('localhost', 8110)) server.sendall("kill\r\n") | proxy.recv(100) pop3Server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) pop3Server.connect(('localhost', 8110)) pop3Server.sendall("kill\r\n") pop3Server.recv(100) | def runProxy(): # Name the database in case it ever gets auto-flushed to disk. bayes = hammie.createbayes('_pop3proxy.db') BayesProxyListener('localhost', 8110, 8111, bayes) bayes.learn(tokenizer.tokenize(spam1), True) bayes.learn(tokenizer.tokenize(good1), False) proxyReady.set() asyncore.loop() |
opts, args = getopt.getopt(sys.argv[1:], 'htdbp:l:u:') | opts, args = getopt.getopt(sys.argv[1:], 'htdbzp:l:u:') | def runProxy(): # Name the database in case it ever gets auto-flushed to disk. bayes = hammie.createbayes('_pop3proxy.db') BayesProxyListener('localhost', 8110, 8111, bayes) bayes.learn(tokenizer.tokenize(spam1), True) bayes.learn(tokenizer.tokenize(good1), False) proxyReady.set() asyncore.loop() |
status.pickleName = hammie.DEFAULTDB status.proxyPort = 110 status.uiPort = 8880 status.serverPort = 110 status.useDB = False status.runTestServer = False status.launchUI = False status.totalSessions = 0 status.activeSessions = 0 status.numEmails = 0 status.numSpams = 0 status.numHams = 0 status.numUnsure = 0 | initStatus() runSelfTest = False | def runProxy(): # Name the database in case it ever gets auto-flushed to disk. bayes = hammie.createbayes('_pop3proxy.db') BayesProxyListener('localhost', 8110, 8111, bayes) bayes.learn(tokenizer.tokenize(spam1), True) bayes.learn(tokenizer.tokenize(good1), False) proxyReady.set() asyncore.loop() |
if not opts and not args: print "Running a self-test (use 'pop3proxy -h' for help)" | if runSelfTest: print "\nRunning self-test...\n" | def runProxy(): # Name the database in case it ever gets auto-flushed to disk. bayes = hammie.createbayes('_pop3proxy.db') BayesProxyListener('localhost', 8110, 8111, bayes) bayes.learn(tokenizer.tokenize(spam1), True) bayes.learn(tokenizer.tokenize(good1), False) proxyReady.set() asyncore.loop() |
elif 1 <= len(args) <= 2: status.serverName = args[0] if len(args) == 2: | elif 0 <= len(args) <= 2: if len(args) >= 1: status.serverName = args[0] if len(args) >= 2: | def runProxy(): # Name the database in case it ever gets auto-flushed to disk. bayes = hammie.createbayes('_pop3proxy.db') BayesProxyListener('localhost', 8110, 8111, bayes) bayes.learn(tokenizer.tokenize(spam1), True) bayes.learn(tokenizer.tokenize(good1), False) proxyReady.set() asyncore.loop() |
main(status.serverName, status.serverPort, status.proxyPort, status.uiPort, status.launchUI, status.pickleName, status.useDB) | if not status.serverName: print >>sys.stderr, \ ("Error: You must give a POP3 server name, either in\n" "bayescustomize.ini as pop3proxy_server_name or on the\n" "command line. pop3server.py -h prints a usage message.") else: main(status.serverName, status.serverPort, status.proxyPort, status.uiPort, status.launchUI, ... | def runProxy(): # Name the database in case it ever gets auto-flushed to disk. bayes = hammie.createbayes('_pop3proxy.db') BayesProxyListener('localhost', 8110, 8111, bayes) bayes.learn(tokenizer.tokenize(spam1), True) bayes.learn(tokenizer.tokenize(good1), False) proxyReady.set() asyncore.loop() |
try: | message_date = self["Date"] if message_date is not None: | def extractTime(self): # When we create a new copy of a message, we need to specify # a timestamp for the message. If the message has a date header # we use that. Otherwise, we use the current time. try: return imaplib.Time2Internaldate(\ time.mktime(parsedate(self["Date"]))) except KeyError: return imaplib.Time2Inte... |
time.mktime(parsedate(self["Date"]))) except KeyError: | time.mktime(parsedate(message_date))) else: | def extractTime(self): # When we create a new copy of a message, we need to specify # a timestamp for the message. If the message has a date header # we use that. Otherwise, we use the current time. try: return imaplib.Time2Internaldate(\ time.mktime(parsedate(self["Date"]))) except KeyError: return imaplib.Time2Inte... |
if self.db: | if self.db is not None: | def store(self): if self.db: self.db.sync() |
if self.db: | if self.db is not None: | def _getState(self, msg): if self.db: try: (msg.c, msg.t) = self.db[msg.getId()] except KeyError: pass |
if self.db: | if self.db is not None: | def _setState(self, msg): if self.db: self.db[msg.getId()] = (msg.c, msg.t) |
if self.db: | if self.db is not None: | def _delState(self, msg): if self.db: del self.db[msg.getId()] |
os.startfile(window.manager.windows_data_directory) | os.startfile(window.manager.data_directory) | def ShowDataFolder(window): """Uses Windows Explorer to show where SpamBayes data and configuration files are stored """ import os os.startfile(window.manager.windows_data_directory) |
if response[-3:] == '.\r\n': | terminatingDotPresent = (response[-4:] == '\n.\r\n') if terminatingDotPresent: | def onRetr(self, command, args, response): """Adds the judgement header based on the raw headers and body of the message.""" # Use '\n\r?\n' to detect the end of the headers in case of # broken emails that don't use the proper line separators. if re.search(r'\n\r?\n', response): # Remove the trailing .\r\n before passi... |
messageText = msg.as_string() | headers = [] for name, value in msg.items(): enc = Header(value, header_name=name, continuation_ws='\t') header = "%s: %s" % (name, str(enc)) headers.append(re.sub(r'\r?\n', '\r\n', header)) body = re.split(r'\n\r?\n', messageText, 1)[1] messageText = "\r\n".join(headers) + "\r\n\r\n" + body | def onRetr(self, command, args, response): """Adds the judgement header based on the raw headers and body of the message.""" # Use '\n\r?\n' to detect the end of the headers in case of # broken emails that don't use the proper line separators. if re.search(r'\n\r?\n', response): # Remove the trailing .\r\n before passi... |
fixed = str(header).replace('\r\n', '\n').replace('\n', '\r\n') headers += "\n%s: %s\r\n\r\n" % (headerName, fixed) | header = re.sub(r'\r?\n', '\r\n', str(header)) headers += "\n%s: %s\r\n\r\n" % (headerName, header) | def onRetr(self, command, args, response): """Adds the judgement header based on the raw headers and body of the message.""" # Use '\n\r?\n' to detect the end of the headers in case of # broken emails that don't use the proper line separators. if re.search(r'\n\r?\n', response): # Remove the trailing .\r\n before passi... |
if retval[-2:] == '\r\n': | if terminatingDotPresent: | def onRetr(self, command, args, response): """Adds the judgement header based on the raw headers and body of the message.""" # Use '\n\r?\n' to detect the end of the headers in case of # broken emails that don't use the proper line separators. if re.search(r'\n\r?\n', response): # Remove the trailing .\r\n before passi... |
else: retval += '\r\n.\r\n' | def onRetr(self, command, args, response): """Adds the judgement header based on the raw headers and body of the message.""" # Use '\n\r?\n' to detect the end of the headers in case of # broken emails that don't use the proper line separators. if re.search(r'\n\r?\n', response): # Remove the trailing .\r\n before passi... | |
except error: | except IMAP4.error: | 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 self.uid is None or self.id is None: print "Cannot get substance of message without an id and an UID" return imap.SelectFolder(self.folder.name) # We really want to ... |
pwd = options["imap", "password"][0] | if not promptForPass: pwd = options["imap", "password"][0] | def run(): global imap try: opts, args = getopt.getopt(sys.argv[1:], 'hbtcvpl:e:i:d:D:') except getopt.error, msg: print >>sys.stderr, str(msg) + '\n\n' + __doc__ sys.exit() bdbname = options["pop3proxy", "persistent_storage_file"] useDBM = options["pop3proxy", "persistent_use_database"] doTrain = False doClassify = F... |
self.isClosing = False | def __init__(self, clientSocket, serverName, serverPort): asynchat.async_chat.__init__(self, clientSocket) self.request = '' self.isClosing = False self.set_terminator('\r\n') serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serverSocket.connect((serverName, serverPort)) self.serverFile = serverSocket.m... | |
"""Reads the POP3 server's response. Also sets self.isClosing to True if the server closes the socket, which tells found_terminator() to close when the response has been sent. | """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 the request was still arriving after 30 seconds, and tells found_terminator() to pr... | def readResponse(self, command, args): """Reads the POP3 server's response. Also sets self.isClosing to True if the server closes the socket, which tells found_terminator() to close when the response has been sent. """ isMulti = self.isMultiline(command, args) responseLines = [] isFirstLine = True while True: line = s... |
self.isClosing = True | isClosing = True | def readResponse(self, command, args): """Reads the POP3 server's response. Also sets self.isClosing to True if the server closes the socket, which tells found_terminator() to close when the response has been sent. """ isMulti = self.isMultiline(command, args) responseLines = [] isFirstLine = True while True: line = s... |
return ''.join(responseLines) | return ''.join(responseLines), isClosing, timedOut | def readResponse(self, command, args): """Reads the POP3 server's response. Also sets self.isClosing to True if the server closes the socket, which tells found_terminator() to close when the response has been sent. """ isMulti = self.isMultiline(command, args) responseLines = [] isFirstLine = True while True: line = s... |
rawResponse = self.readResponse(command, args) | rawResponse, isClosing, timedOut = self.readResponse(command, args) | def found_terminator(self): """Asynchat override.""" # Send the request to the server and read the reply. # XXX When the response is huge, the email client can time out. # It should read as much as it can from the server, then if the # response is still coming after say 30 seconds, it should # classify the message base... |
if self.isClosing: | if timedOut: while True: line = self.serverFile.readline() if not line: isClosing = True break elif line == '.\r\n': self.push(line) break else: self.push(line) if isClosing: | def found_terminator(self): """Asynchat override.""" # Send the request to the server and read the reply. # XXX When the response is huge, the email client can time out. # It should read as much as it can from the server, then if the # response is still coming after say 30 seconds, it should # classify the message base... |
bayes = hammie.createbayes() | bayes = hammie.createbayes('_pop3proxy.db') | def runProxy(): bayes = hammie.createbayes() BayesProxyListener('localhost', 8110, 8111, bayes) bayes.learn(tokenizer.tokenize(spam1), True) bayes.learn(tokenizer.tokenize(good1), False) asyncore.loop() |
try: | if self.msgs.get(key, "") is "": return default else: | def get(self, key, default=None): try: return self[key] except KeyError: return default |
except KeyError: return default | def get(self, key, default=None): try: return self[key] except KeyError: return default | |
self.serverSocket.push(cooked + '\r\n') | self.serverSocket.push(cooked) | def found_terminator(self): """Asynchat override.""" verb = self.request.strip().upper() if verb == 'KILL': self.socket.shutdown(2) self.close() raise SystemExit |
print "pulled: '%s'" % self.request print "pushed: '%s'" % cooked | def found_terminator(self): """Asynchat override.""" verb = self.request.strip().upper() if verb == 'KILL': self.socket.shutdown(2) self.close() raise SystemExit | |
self.servers = [] if options["pop3proxy", "remote_servers"]: for server in options["pop3proxy", "remote_servers"]: server = server.strip() if server.find(':') > -1: server, port = server.split(':', 1) else: port = '110' self.servers.append((server, int(port))) | if not hasattr(self, "servers"): self.servers = [] if options["pop3proxy", "remote_servers"]: for server in options["pop3proxy", "remote_servers"]: server = server.strip() if server.find(':') > -1: server, port = server.split(':', 1) else: port = '110' self.servers.append((server, int(port))) | def init(self): assert not self.prepared, "init after prepare, but before close" # Load the environment for translation. self.lang_manager = i18n.LanguageManager() # Set the system user default language. self.lang_manager.set_language(\ self.lang_manager.locale_default_lang()) # Set interface to use the user language i... |
items.append((info.spamcount, word)) | items.append((info.spamcount, word, info)) | def FindTopWords(bayes, num, get_spam): items = [] try: bayes.db # bsddb style extractor = DBExtractor except AttributeError: extractor = DictExtractor for word, info in extractor(bayes): if ":" in word: continue if get_spam: if info.hamcount==0: items.append((info.spamcount, word)) else: if info.spamcount==0: items.a... |
items.append((info.hamcount, word)) | items.append((info.hamcount, word, info)) | def FindTopWords(bayes, num, get_spam): items = [] try: bayes.db # bsddb style extractor = DBExtractor except AttributeError: extractor = DictExtractor for word, info in extractor(bayes): if ":" in word: continue if get_spam: if info.hamcount==0: items.append((info.spamcount, word)) else: if info.spamcount==0: items.a... |
return [item[1] for item in items] | if len(items) < num: TestFailed("Error: could not find %d words with Spam=%s - only found %d" % (num, get_spam, len(items))) ret = {} for n, word, info in items[:num]: ret[word]=copy.copy(info) return ret | def FindTopWords(bayes, num, get_spam): items = [] try: bayes.db # bsddb style extractor = DBExtractor except AttributeError: extractor = DictExtractor for word, info in extractor(bayes): if ":" in word: continue if get_spam: if info.hamcount==0: items.append((info.spamcount, word)) else: if info.spamcount==0: items.a... |
msg = self.CreateTestMessage(spam_status) | msg, words = self.CreateTestMessage(spam_status) | def CreateTestMessageInFolder(self, spam_status, folder): msg = self.CreateTestMessage(spam_status) msg.Save() # Put into "Drafts". assert self.FindTestMessage(self.folder_drafts) is not None # Move it to the specified folder msg.Move(folder) # And now find it in the specified folder return self.FindTestMessage(folder) |
return self.FindTestMessage(folder) | return self.FindTestMessage(folder), words | def CreateTestMessageInFolder(self, spam_status, folder): msg = self.CreateTestMessage(spam_status) msg.Save() # Put into "Drafts". assert self.FindTestMessage(self.folder_drafts) is not None # Move it to the specified folder msg.Move(folder) # And now find it in the specified folder return self.FindTestMessage(folder) |
words = [] | words = {} | def CreateTestMessage(self, spam_status): words = [] if spam_status != SPAM: words.extend(FindTopWords(self.manager.bayes, 50, False)) if spam_status != HAM: words.extend(FindTopWords(self.manager.bayes, 50, True)) # Create a new blank message with our words msg = self.manager.outlook.CreateItem(0) msg.Body = "\n".join... |
words.extend(FindTopWords(self.manager.bayes, 50, False)) | words.update(FindTopWords(self.manager.bayes, 50, False)) | def CreateTestMessage(self, spam_status): words = [] if spam_status != SPAM: words.extend(FindTopWords(self.manager.bayes, 50, False)) if spam_status != HAM: words.extend(FindTopWords(self.manager.bayes, 50, True)) # Create a new blank message with our words msg = self.manager.outlook.CreateItem(0) msg.Body = "\n".join... |
words.extend(FindTopWords(self.manager.bayes, 50, True)) | words.update(FindTopWords(self.manager.bayes, 50, True)) | def CreateTestMessage(self, spam_status): words = [] if spam_status != SPAM: words.extend(FindTopWords(self.manager.bayes, 50, False)) if spam_status != HAM: words.extend(FindTopWords(self.manager.bayes, 50, True)) # Create a new blank message with our words msg = self.manager.outlook.CreateItem(0) msg.Body = "\n".join... |
msg.Body = "\n".join(words) | msg.Body = "\n".join(words.keys()) | def CreateTestMessage(self, spam_status): words = [] if spam_status != SPAM: words.extend(FindTopWords(self.manager.bayes, 50, False)) if spam_status != HAM: words.extend(FindTopWords(self.manager.bayes, 50, True)) # Create a new blank message with our words msg = self.manager.outlook.CreateItem(0) msg.Body = "\n".join... |
return msg | return msg, words def check_words(words, bayes, spam_offset, ham_offset): for word, existing_info in words.items(): new_info = bayes._wordinfoget(word) if existing_info.spamcount+spam_offset != new_info.spamcount or \ existing_info.hamcount+ham_offset != new_info.hamcount: TestFailed("Word check for '%s failed. " "old... | def CreateTestMessage(self, spam_status): words = [] if spam_status != SPAM: words.extend(FindTopWords(self.manager.bayes, 50, False)) if spam_status != HAM: words.extend(FindTopWords(self.manager.bayes, 50, True)) # Create a new blank message with our words msg = self.manager.outlook.CreateItem(0) msg.Body = "\n".join... |
import copy | def TestSpamFilter(driver): nspam = driver.manager.bayes.nspam nham = driver.manager.bayes.nham import copy original_bayes = copy.copy(driver.manager.bayes) # Create a spam message in the Inbox - it should get immediately filtered msg = driver.CreateTestMessageInFolder(SPAM, driver.folder_watch) # sleep to ensure filte... | |
msg = driver.CreateTestMessageInFolder(SPAM, driver.folder_watch) | msg, words = driver.CreateTestMessageInFolder(SPAM, driver.folder_watch) | def TestSpamFilter(driver): nspam = driver.manager.bayes.nspam nham = driver.manager.bayes.nham import copy original_bayes = copy.copy(driver.manager.bayes) # Create a spam message in the Inbox - it should get immediately filtered msg = driver.CreateTestMessageInFolder(SPAM, driver.folder_watch) # sleep to ensure filte... |
msg = driver.CreateTestMessageInFolder(HAM, driver.folder_watch) | msg, words = driver.CreateTestMessageInFolder(HAM, driver.folder_watch) | def TestHamFilter(driver): # Create a spam message in the Inbox - it should get immediately filtered msg = driver.CreateTestMessageInFolder(HAM, driver.folder_watch) # sleep to ensure filtering. WaitForFilters() # It should still be in the Inbox. if driver.FindTestMessage(driver.folder_watch) is None: TestFailed("The t... |
msg = driver.CreateTestMessageInFolder(UNSURE, driver.folder_watch) | msg, words = driver.CreateTestMessageInFolder(UNSURE, driver.folder_watch) | def TestUnsureFilter(driver): # Create a spam message in the Inbox - it should get immediately filtered msg = driver.CreateTestMessageInFolder(UNSURE, driver.folder_watch) # sleep to ensure filtering. WaitForFilters() # It should no longer be in the Inbox. if driver.FindTestMessage(driver.folder_watch) is not None: Tes... |
{0 : ("", " as ham"), 1 : ("", " as spam"), None : ("not ", "")} | {'0' : ("", " as ham"), '1' : ("", " as spam"), None : ("not ", "")} | def ShowClues(mgr, explorer): from cgi import escape app = explorer.Application msgstore_message = explorer.GetSelectedMessages(False) if msgstore_message is None: return item = msgstore_message.GetOutlookItem() score, clues = mgr.score(msgstore_message, evidence=True) new_msg = app.CreateItem(0) # NOTE: Silly Outloo... |
DEFAULTDB = "~/.hammiedb" | DEFAULTDB = os.path.expanduser(os.path.join("~", ".hammiedb")) | def bool(val): return not not val |
os.startfile(window.manager.data_directory) | import sys filesystem_encoding = sys.getfilesystemencoding() os.startfile(window.manager.data_directory.encode(filesystem_encoding)) | def ShowDataFolder(window): """Uses Windows Explorer to show where SpamBayes data and configuration files are stored """ import os os.startfile(window.manager.data_directory) |
if not msg_train(h, msg, is_spam, force): continue trained += 1 | if msg_train(h, msg, is_spam, force): trained += 1 | def mbox_train(h, path, is_spam, force): """Train bayes with a Unix mbox""" if loud: print " Reading as Unix mbox" import mailbox import fcntl import tempfile # Open and lock the mailbox. Some systems require it be opened for # writes in order to assert an exclusive lock. f = file(path, "r+b") fcntl.flock(f, fcntl... |
if isinstance(x, tuple): assert len(x) == 3 x = x[2] | 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: if isinstance(x, tuple): assert len(x) == 3 x = x[2] yield 'charset:' + x.lower() x = msg.get('content-dispo... | |
alternate = os.getenv('BAYESCUSTOMIZE') | alternate = None if hasattr(os, 'getenv'): alternate = os.getenv('BAYESCUSTOMIZE') | def display(self): output = StringIO.StringIO() self._config.write(output) return output.getvalue() |
print >> sys.stderr, ("Invalid option %s in" " section %s in file %s" % (opt, sect, filename)) | if option.startswith('x-'): option = option[2:] if self._options.has_key((section, option)): self.convert_and_set(section, option, value) else: option = 'x-'+option if self._options.has_key((section, option)): self.convert_and_set(section, option, value) print >> sys.stderr, ( "warning: option %s in" " section %s ... | def merge_file(self, filename): import ConfigParser c = ConfigParser.ConfigParser() c.read(filename) for sect in c.sections(): for opt in c.options(sect): value = c.get(sect, opt) section = sect option = opt if not self._options.has_key((section, option)): print >> sys.stderr, ("Invalid option %s in" " section %s in fi... |
if self.multiple_values_allowed(section, option): value = self.convert(section, option, value) value = self.convert(section, option, value) self.set(section, option, value) | self.convert_and_set(section, option, value) | def merge_file(self, filename): import ConfigParser c = ConfigParser.ConfigParser() c.read(filename) for sect in c.sections(): for opt in c.options(sect): value = c.get(sect, opt) section = sect option = opt if not self._options.has_key((section, option)): print >> sys.stderr, ("Invalid option %s in" " section %s in fi... |
'''Return a alphabetical list of all the options, optionally | '''Return an alphabetical list of all the options, optionally | def options(self, prepend_section_name=False): '''Return a alphabetical list of all the options, optionally prefixed with [section_name]''' all = [] for sect, opt in self._options.keys(): if prepend_section_name: all.append('[' + sect + ']' + opt) else: all.append(opt) all.sort() return all |
HEADER_VALUE = r"[\w\.\-\*]+" | HEADER_VALUE = r".+" | def display_full(self, section=None, option=None): '''Display options including all information.''' # Given that the Options class is no longer as nice looking # as it once was, this returns all the information, i.e. # the doc, default values, and so on output = StringIO.StringIO() |
imap = self.imap_session_class(server, port) | self.imap = self.imap_session_class(server, port) | 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 imap = self.imap_ses... |
if "UNDELETED" in args: | if args.find("UNDELETED") != -1: | def onSearch(self, id, command, args, uid=False): args = args.upper() results = () if "UNDELETED" in args: for msg_id in UNDELETED_IDS: if uid: results += (IMAP_UIDS[msg_id],) else: results += (msg_id,) if uid: command_string = "UID " + command else: command_string = command return "%s\r\n%s OK %s completed\r\n" % \ ("... |
if "UID" in msg_parts: | if msg_parts.find("UID") != -1: | def onFetch(self, id, command, args, uid=False): msg_nums, msg_parts = args.split(None, 1) msg_nums = msg_nums.split() response = {} for msg in msg_nums: response[msg] = [] if "UID" in msg_parts: if uid: for msg in msg_nums: response[msg].append("FETCH (UID %s)" % (msg,)) else: for msg in msg_nums: response[msg].append... |
if "BODY.PEEK[]" in msg_parts: | if msg_parts.find("BODY.PEEK[]") != -1: | def onFetch(self, id, command, args, uid=False): msg_nums, msg_parts = args.split(None, 1) msg_nums = msg_nums.split() response = {} for msg in msg_nums: response[msg] = [] if "UID" in msg_parts: if uid: for msg in msg_nums: response[msg].append("FETCH (UID %s)" % (msg,)) else: for msg in msg_nums: response[msg].append... |
if "RFC822.HEADER" in msg_parts: | if msg_parts.find("RFC822.HEADER") != -1: | def onFetch(self, id, command, args, uid=False): msg_nums, msg_parts = args.split(None, 1) msg_nums = msg_nums.split() response = {} for msg in msg_nums: response[msg] = [] if "UID" in msg_parts: if uid: for msg in msg_nums: response[msg].append("FETCH (UID %s)" % (msg,)) else: for msg in msg_nums: response[msg].append... |
if "FLAGS INTERNALDATE" in msg_parts: | if msg_parts.find("FLAGS INTERNALDATE") != -1: | def onFetch(self, id, command, args, uid=False): msg_nums, msg_parts = args.split(None, 1) msg_nums = msg_nums.split() response = {} for msg in msg_nums: response[msg] = [] if "UID" in msg_parts: if uid: for msg in msg_nums: response[msg].append("FETCH (UID %s)" % (msg,)) else: for msg in msg_nums: response[msg].append... |
has_header = "X-Spambayes-Exception: " in new_msg.as_string() | has_header = new_msg.as_string().find("X-Spambayes-Exception: ") != -1 | def test_get_bad_message(self): self.msg.id = "unittest" self.msg.imap_server.login(IMAP_USERNAME, IMAP_PASSWORD) self.msg.imap_server.select() self.msg.uid = 103 # id of malformed message in dummy server self.msg.folder = IMAPFolder("Inbox", self.msg.imap_server) print "\nWith email package versions less than 3.0, you... |
ok, statusRemainder = statusLine.split(None, 1) | statusData = statusLine.split() ok = statusData[0] | def onRetr(self, command, args, response): """Adds the judgement header based on the raw headers and body of the message.""" # Previously, we used '\n\r?\n' to detect the end of the headers in # case of broken emails that don't use the proper line separators, # and if we couldn't find it, then we assumed that the respo... |
webbrowser.open_new("http://localhost:%d/" % context._HTTPPort) | try: url = "http://localhost:%d/" % context._HTTPPort webbrowser.open_new(url) except webbrowser.Error, e: print "\n%s.\nPlease point your web browser at %s." % (e, url) | def run(launchBrowser=False, context=_defaultContext): """Runs a `Dibbler` application. Servers listen for incoming connections and route requests through to plugins until a plugin calls `sys.exit()` or raises a `SystemExit` exception.""" if launchBrowser: webbrowser.open_new("http://localhost:%d/" % context._HTTPPor... |
print >>sys.stderr, error | now = time.time() then = time.time() - 3600 if error not in state.reported_errors or \ options["globals", "verbose"] or \ state.reported_errors[error] < then: print >>sys.stderr, error state.reported_errors[error] = now | def __init__(self, serverName, serverPort, lineCallback, ssl=False): Dibbler.BrighterAsyncChat.__init__(self) self.lineCallback = lineCallback self.request = '' self.set_terminator('\r\n') self.create_socket(socket.AF_INET, socket.SOCK_STREAM) # create_socket creates a non-blocking socket. This is fine for # regular s... |
def ensureDir(dirname): try: os.mkdir(dirname) except OSError, e: if e.errno != errno.EEXIST: raise | def ensureDir(dirname): try: os.mkdir(dirname) except OSError, e: if e.errno != errno.EEXIST: raise | |
map(ensureDir, [sc, hc, uc]) | map(storage.ensureDir, [sc, hc, uc]) | def ensureDir(dirname): try: os.mkdir(dirname) except OSError, e: if e.errno != errno.EEXIST: raise |
print "Error getting property from stream", d | print "Error getting property", mapiutil.GetPropTagName(prop_id), \ "from stream:", d | def GetPropFromStream(mapi_object, prop_id): try: stream = mapi_object.OpenProperty(prop_id, pythoncom.IID_IStream, 0, 0) chunks = [] while 1: chunk = stream.Read(4096) if not chunk: break chunks.append(chunk) return "".join(chunks) except pythoncom.com_error, d: print "Error getting property from stream", d return "" |
if PROP_TYPE(headers_tag)==PT_STRING8: self.headers = headers has_headers = True else: has_headers = PROP_TYPE(headers_tag)==PT_ERROR and \ headers==mapi.MAPI_E_NOT_ENOUGH_MEMORY self.headers = None | has_headers = PROP_TYPE(headers_tag)==PT_STRING8 | def __init__(self, msgstore, prop_row): self.msgstore = msgstore self.mapi_object = None |
if self.headers is None: prop_ids = (PR_TRANSPORT_MESSAGE_HEADERS_A,) hr, data = self.mapi_object.GetProps(prop_ids,0) self.headers = self._GetPotentiallyLargeStringProp(prop_ids[0], data[0]) headers = self.headers | 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. from spambayes import mboxutils | |
PR_HASATTACH) | PR_HASATTACH, PR_TRANSPORT_MESSAGE_HEADERS_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. from spambayes import mboxutils |
word = urllib.quote(word) | word = uquote(word) | def runExport(dbFN, useDBM, outFN): if useDBM: bayes = spambayes.storage.DBDictClassifier(dbFN) words = bayes.db.keys() words.remove(bayes.statekey) else: bayes = spambayes.storage.PickledClassifier(dbFN) words = bayes.wordinfo.keys() try: fp = open(outFN, 'w') except IOError, e: if e.errno != errno.ENOENT: raise nh... |
word = urllib.unquote(word) | word = uunquote(word) | def runImport(dbFN, useDBM, newDBM, inFN): if newDBM: try: os.unlink(dbFN) except OSError, e: if e.errno != 2: # errno.<WHAT> raise try: os.unlink(dbFN+".dat") except OSError, e: if e.errno != 2: # errno.<WHAT> raise try: os.unlink(dbFN+".dir") except OSError, e: if e.errno != 2: # errno.<WHAT> raise if... |
msgstr = re.sub('([^\r])\n', r'\1\r\n', self.as_string()) | msgstr = self.as_string() | 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() msgstr = re.sub('([^\r])\n', r'\1\r\n', self.as_string()) response = imap.append(self.folder.name, None, time_stamp, msgstr) self._check(response, 'append') |
response = imap.append(self.folder.name, flags, msg_time, self.as_string()) if response[0] == "NO": response = imap.append(self.folder.name, None, msg_time, | for flgs, tme in [(flags, msg_time), (None, msg_time), (flags, Time2Internaldate(time.time())), (None, Time2Internaldate(time.time()))]: response = imap.append(self.folder.name, flgs, tme, | def Save(self): '''Save message to imap server.''' # we can't actually update the message with IMAP # so what we do is create a new message and delete the old one if self.folder is None: raise RuntimeError, """Can't save a message that doesn't have a folder.""" if not self.id: raise RuntimeError, """Can't save a messag... |
print "WARNING: Could not append flags: %s" % (flags,) | break | def Save(self): '''Save message to imap server.''' # we can't actually update the message with IMAP # so what we do is create a new message and delete the old one if self.folder is None: raise RuntimeError, """Can't save a message that doesn't have a folder.""" if not self.id: raise RuntimeError, """Can't save a messag... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.