rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
print "Ham distribution for", tag
print "-> <stat> Ham distribution for", tag,
def printhist(tag, ham, spam): print print "Ham distribution for", tag ham.display() print print "Spam distribution for", tag spam.display()
print "Spam distribution for", tag
print "-> <stat> Spam distribution for", tag,
def printhist(tag, ham, spam): print print "Ham distribution for", tag ham.display() print print "Spam distribution for", tag spam.display()
for j in range((expire) // grouping, -1, -1):
for j in range(((expire) // grouping) - 1, -1, -1):
def row(value, spamday, hamday, unsureday): line = "%5d|" % value for j in range((expire) // grouping, -1, -1): spamv = 0 hamv = 0 unsurev = 0 for k in range(j * grouping, (j + 1) * grouping): try: spamv += spamday[k] hamv += hamday[k] unsurev += unsureday[k] except: pass spamv = spamv // grouping hamv = hamv // groupi...
if ssl: self.socket.setblocking(1)
self.socket.setblocking(1)
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...
self.socket.setblocking(0) print self._fileno
self.socket.setblocking(0)
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...
ham = options["Headers", "header_ham_string"] + ',' spam = options["Headers", "header_spam_string"] + ',' unsure = options["Headers", "header_unsure_string"] + ',' if options["Headers", "notate_subject"]: for disp in (ham, spam, unsure): if subject.startswith(disp): self.replace_header("Subject", subject[len(disp):]) ...
if subject: ham = options["Headers", "header_ham_string"] + ',' spam = options["Headers", "header_spam_string"] + ',' unsure = options["Headers", "header_unsure_string"] + ',' if options["Headers", "notate_subject"]: for disp in (ham, spam, unsure): if subject.startswith(disp): self.replace_header("Subject", subject[le...
def delNotations(self): """If present, remove our notation from the subject: and/or to: header of the message.
ham = "%s@spambayes.invalid," % \ (options["Headers", "header_ham_string"],) spam = "%s@spambayes.invalid," % \ (options["Headers", "header_spam_string"],) unsure = "%s@spambayes.invalid," % \ (options["Headers", "header_unsure_string"],) if options["Headers", "notate_to"]: for disp in (ham, spam, unsure): if to.starts...
if to: ham = "%s@spambayes.invalid," % \ (options["Headers", "header_ham_string"],) spam = "%s@spambayes.invalid," % \ (options["Headers", "header_spam_string"],) unsure = "%s@spambayes.invalid," % \ (options["Headers", "header_unsure_string"],) if options["Headers", "notate_to"]: for disp in (ham, spam, unsure): if to...
def delNotations(self): """If present, remove our notation from the subject: and/or to: header of the message.
print 'Listener on port %d is proxying %s:%d' % \ (proxyPort, serverName, serverPort)
print 'Listener on port %s is proxying %s:%d' % \ (_addressPortStr(proxyPort), serverName, serverPort)
def __init__(self, serverName, serverPort, proxyPort): proxyArgs = (serverName, serverPort) Dibbler.Listener.__init__(self, proxyPort, BayesProxy, proxyArgs) print 'Listener on port %d is proxying %s:%d' % \ (proxyPort, serverName, serverPort)
for imageName in IMAGES: exec "from spambayes.resources import %s_gif" % imageName exec "images[imageName] = %s_gif.data" % imageName
for baseName in IMAGES: moduleName = '%s.%s_gif' % ('spambayes.resources', baseName) module = __import__(moduleName, {}, {}, ('spambayes', 'resources')) images[baseName] = module.data
def readUIResources(): """Returns ui.html and a dictionary of Gifs. Used here and by OptionConfig""" # Using `exec` is nasty, but I couldn't figure out a way of making # `getattr` or `__import__` work with ResourcePackage. from spambayes.resources import ui_html images = {} for imageName in IMAGES: exec "from spambay...
self.proxyPorts = map(int, map(string.strip, splitPorts))
self.proxyPorts = map(_addressAndPort, splitPorts)
def __init__(self): """Initialises the State object that holds the state of the app. The default settings are read from Options.py and bayescustomize.ini and are then overridden by the command-line processing code in the __main__ code below.""" # Open the log file. if options.verbose: self.logFile = open('_pop3proxy.lo...
self.proxyPortsString = ', '.join(map(str, self.proxyPorts))
self.proxyPortsString = ', '.join(map(_addressPortStr, self.proxyPorts))
def buildServerStrings(self): """After the server details have been set up, this creates string versions of the details, for display in the Status panel.""" serverStrings = ["%s:%s" % (s, p) for s, p in self.servers] self.serversString = ', '.join(serverStrings) self.proxyPortsString = ', '.join(map(str, self.proxyPort...
state.proxyPorts = [int(arg)]
state.proxyPorts = [_addressAndPort(arg)]
def run(): # Read the arguments. try: opts, args = getopt.getopt(sys.argv[1:], 'htdbzp:l:u:') except getopt.error, msg: print >>sys.stderr, str(msg) + '\n\n' + __doc__ sys.exit() runSelfTest = False for opt, arg in opts: if opt == '-h': print >>sys.stderr, __doc__ sys.exit() elif opt == '-t': state.isTest = True state...
else: raise RuntimeError, "Can't find a default message store"
if store_name is None: raise RuntimeError, "Can't find a default message store"
def FindFolder(self, name): assert name names = [n.lower() for n in name.split("\\")] if names[0]: for store, name, is_default in self.GetMessageStores(): if is_default: store_name = name.lower() break else: raise RuntimeError, "Can't find a default message store" folder_names = names else: store_name = names[1] folder...
return Time2Internaldate(time.mktime(parsed_date)) else: return Time2Internaldate(time.time())
try: return Time2Internaldate(time.mktime(parsed_date)) except OverflowError: pass return Time2Internaldate(time.time())
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 valid date # header we use that. Otherwise, we use the current time. message_date = self["Date"] if message_date is not None: parsed_date = parsedate(message_date) if parsed_date is ...
print sleepTime
def Logout(self, expunge): # sign off if expunge: imap.expunge() imap.logout()
HEADER_NAME = r"[\w\.-\*]+" HEADER_VALUE = r"[\w\.-\*]+"
HEADER_NAME = r"[\w\.\-\*]+" HEADER_VALUE = r"[\w\.\-\*]+"
def bool(val): return not not val
PATH = r"[\w\.-~:\\/\*]+"
PATH = r"[\w\.\-~:\\/\*]+"
def bool(val): return not not val
def _GetPropFromStream(self, prop_id): try: stream = self.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 ""
def _GetPropFromStream(self, prop_id): try: stream = self.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 ""
got_tag, got_val = row if PROP_TYPE(got_tag) == PT_ERROR: ret = "" if got_val == mapi.MAPI_E_NOT_FOUND: pass elif got_val == mapi.MAPI_E_NOT_ENOUGH_MEMORY: ret = self._GetPropFromStream(prop_id) else: tag_name = mapiutil.GetPropTagName(prop_id) err_string = mapiutil.GetScodeString(got_val) print "Warning - failed to g...
return GetPotentiallyLargeStringProp(self.mapi_object, prop_id, row)
def _GetPotentiallyLargeStringProp(self, prop_id, row): got_tag, got_val = row if PROP_TYPE(got_tag) == PT_ERROR: ret = "" if got_val == mapi.MAPI_E_NOT_FOUND: pass # No property for this message. elif got_val == mapi.MAPI_E_NOT_ENOUGH_MEMORY: # Too big for simple properties - get via a stream ret = self._GetPropFromSt...
attach_body = self._GetPotentiallyLargeStringProp( prop_ids[0], data[0])
attach_body = GetPotentiallyLargeStringProp(attach, prop_ids[0], data[0])
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
assert msg.is_multipart() sub = msg.get_payload(0) body = sub.get_payload()
assert msg.is_multipart(), "Should be multi-part: %r" % attach_body def collect_text_parts(msg): collected = '' if msg.is_multipart(): for sub in msg.get_payload(): collected += collect_text_parts(sub) else: if msg.get_content_maintype()=='text': collected += msg.get_payload() else: pass return collected body = col...
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
p, n = map(float, f.readline().split())
p, n = map(float, line.split())
def suck(f): fns = [] fps = [] while 1: line = f.readline() if line.startswith('total'): break if not line.startswith('Training'): # A line with an f-p rate and an f-n rate. p, n = map(float, f.readline().split()) fps.append(p) fns.append(n) # "total false pos 8 0.04" # "total false neg 249 1.81090909091" fptot = int(...
def _sortMessages(self, messages, sort_order):
def _sortMessages(self, messages, sort_order, reverse=False):
def _sortMessages(self, messages, sort_order): """Sorts the message by the appropriate attribute. If this was the previous sort order, then reverse it.""" if sort_order is None or sort_order == "received": # Default sorting, which is in reverse order of appearance. # This is complicated because the 'received' info is ...
else: tmplist = [(getattr(x[1], sort_order), x) for x in messages]
tmplist = [(getattr(x[1], sort_order), x) for x in messages]
def _sortMessages(self, messages, sort_order): """Sorts the message by the appropriate attribute. If this was the previous sort order, then reverse it.""" if sort_order is None or sort_order == "received": # Default sorting, which is in reverse order of appearance. # This is complicated because the 'received' info is ...
if self.previous_sort == sort_order:
if reverse:
def _sortMessages(self, messages, sort_order): """Sorts the message by the appropriate attribute. If this was the previous sort order, then reverse it.""" if sort_order is None or sort_order == "received": # Default sorting, which is in reverse order of appearance. # This is complicated because the 'received' info is ...
self.previous_sort = None else: self.previous_sort = sort_order
def _sortMessages(self, messages, sort_order): """Sorts the message by the appropriate attribute. If this was the previous sort order, then reverse it.""" if sort_order is None or sort_order == "received": # Default sorting, which is in reverse order of appearance. # This is complicated because the 'received' info is ...
def _appendMessages(self, table, keyedMessageInfo, label, sort_order):
def _appendMessages(self, table, keyedMessageInfo, label, sort_order, reverse=False):
def _appendMessages(self, table, keyedMessageInfo, label, sort_order): """Appends the rows of a table of messages to 'table'.""" stripe = 0
keyedMessageInfo = self._sortMessages(keyedMessageInfo, sort_order)
keyedMessageInfo = self._sortMessages(keyedMessageInfo, sort_order, reverse)
def _appendMessages(self, table, keyedMessageInfo, label, sort_order): """Appends the rows of a table of messages to 'table'.""" stripe = 0
score = float(messageInfo.score.rstrip('%'))
score = messageInfo.score
def _appendMessages(self, table, keyedMessageInfo, label, sort_order): """Appends the rows of a table of messages to 'table'.""" stripe = 0
row.score_ = messageInfo.score
if isinstance(messageInfo.score, types.StringTypes): row.score_ = messageInfo.score else: row.score_ = "%.2f%%" % (messageInfo.score,)
def _appendMessages(self, table, keyedMessageInfo, label, sort_order): """Appends the rows of a table of messages to 'table'.""" stripe = 0
params.get('sort'))
sort_order, reverse)
def onReview(self, **params): """Present a list of message for (re)training.""" # Train/discard sumbitted messages. self._writePreamble("Review") id = '' numTrained = 0 numDeferred = 0 if params.get('go') != 'Refresh': for key, value in params.items(): if key.startswith('classify:'): id = key.split(':')[2] if value == ...
score = "%.2f%%" % (float(score)*100,)
score = float(score) * 100
def _makeMessageInfo(self, message): """Given an email.Message, return an object with subjectHeader, bodySummary and other header (as needed) attributes. These objects are passed into appendMessages by onReview - passing email.Message objects directly uses too much memory.""" subjectHeader = message["Subject"] or "(no...
def __init__(self, classifier, debug):
def __init__(self, classifier):
def __init__(self, classifier, debug): self.spam_folder = IMAPFolder(options.imap_spam_folder) self.unsure_folder = IMAPFolder(options.imap_unsure_folder)
imap_filter = IMAPFilter(classifier, imapDebug)
imap_filter = IMAPFilter(classifier)
def Filter(self): if options.verbose: t = time.time() for filter_folder in options.imap_filter_folders.split(): folder = IMAPFolder(filter_folder, False) folder.Filter(self.classifier, self.spam_folder, self.unsure_folder)
print "Bayes database is not dirty - not writing"
self.LogDebug(1, "Bayes database is not dirty - not writing")
def Save(self): # No longer save the config here - do it explicitly when changing it # (prevents lots of extra pickle writes, for no good reason. Other # alternative is a dirty flag for config - this is simpler) if self.classifier_data.dirty: self.classifier_data.Save() else: print "Bayes database is not dirty - not w...
return "You must define folders to watch for new messages"
return "You must define folders to watch for new messages. " \ "Select the 'Filtering' tab to define these folders."
def GetDisabledReason(self): # Gets the reason why the plugin can not be enabled. # If return is None, then it can be enabled (and indeed may be!) # Otherwise return is the string reason config = self.config.filter ok_to_enable = operator.truth(config.watch_folder_ids) if not ok_to_enable: return "You must define folde...
return "You must define the folder to receive your certain spam"
return "You must define the folder to receive your certain spam. " \ "Select the 'Filtering' tab to define this folders."
def GetDisabledReason(self): # Gets the reason why the plugin can not be enabled. # If return is None, then it can be enabled (and indeed may be!) # Otherwise return is the string reason config = self.config.filter ok_to_enable = operator.truth(config.watch_folder_ids) if not ok_to_enable: return "You must define folde...
trustedIPs = trustedIPs.replace('.', '\.').replace('*', '([01]?\d\d?|2[04]\d|25[0-5])')
trustedIPs = trustedIPs.replace('.', '\.').replace('*', '([01]?\d\d?|2[0-4]\d|25[0-5])')
def onIncomingConnection(self, clientSocket): """Checks the security settings.""" # Stolen from UserInterface.py
if not hasattr(self, "MBDName"): self.MDBName, self.useMDB = spambayes.message.database_type() self.mdb = spambayes.message.open_storage(self.MDBName, self.useMDB) spambayes.message.Message.message_info_db = self.mdb
self.mdb = spambayes.message.Message().message_info_db
def createWorkers(self): """Using the options that were initialised in __init__ and then possibly overridden by the driver code, create the Bayes object, the Corpuses, the Trainers and so on.""" print "Loading database...", if self.isTest: self.useDB = "pickle" self.DBName = '_pop3proxy_test.pickle' # This is never s...
win32gui.SendMessage(slider, commctrl.TBM_SETRANGE, 0, MAKELONG(0, 10))
win32gui.SendMessage(slider, commctrl.TBM_SETRANGE, 0, MAKELONG(0, 20))
def InitSlider(self): slider = self.GetControl(self.slider_id) win32gui.SendMessage(slider, commctrl.TBM_SETRANGE, 0, MAKELONG(0, 10)) win32gui.SendMessage(slider, commctrl.TBM_SETLINESIZE, 0, 1) win32gui.SendMessage(slider, commctrl.TBM_SETPAGESIZE, 0, 1) win32gui.SendMessage(slider, commctrl.TBM_SETTICFREQ, 1, 0) sel...
win32gui.SendMessage(slider, commctrl.TBM_SETTICFREQ, 1, 0)
win32gui.SendMessage(slider, commctrl.TBM_SETTICFREQ, 2, 0)
def InitSlider(self): slider = self.GetControl(self.slider_id) win32gui.SendMessage(slider, commctrl.TBM_SETRANGE, 0, MAKELONG(0, 10)) win32gui.SendMessage(slider, commctrl.TBM_SETLINESIZE, 0, 1) win32gui.SendMessage(slider, commctrl.TBM_SETPAGESIZE, 0, 1) win32gui.SendMessage(slider, commctrl.TBM_SETTICFREQ, 1, 0) sel...
slider_pos = int(slider_pos) str_val = str(slider_pos)
slider_pos = float(slider_pos) str_val = str(slider_pos*.5)
def OnMessage(self, msg, wparam, lparam): slider = self.GetControl(self.slider_id) if slider == lparam: slider_pos = win32gui.SendMessage(slider, commctrl.TBM_GETPOS, 0, 0) slider_pos = int(slider_pos) str_val = str(slider_pos) edit = self.GetControl() win32gui.SendMessage(edit, win32con.WM_SETTEXT, 0, str_val)
val = int(float(self.option.get()/1000))
val = int(float(self.option.get())/500.0)
def UpdateSlider_FromEdit(self): slider = self.GetControl(self.slider_id) try: # Get as float so we dont fail should the .0 be there, but # then convert to int as the slider only works with ints val = int(float(self.option.get()/1000)) except ValueError: return win32gui.SendMessage(slider, commctrl.TBM_SETPOS, 1, val)
value = self.option.get()/1000
value = float(self.option.get())/1000.0
def UpdateControl_FromValue(self): value = self.option.get()/1000 win32gui.SendMessage(self.GetControl(), win32con.WM_SETTEXT, 0, str(value)) self.UpdateSlider_FromEdit()
val = int(str_val) if val < 0 or val > 10:
val = float(str_val) if val < 0.0 or val > 10.0:
def UpdateValue_FromControl(self): buf_size = 100 buf = win32gui.PyMakeBuffer(buf_size) nchars = win32gui.SendMessage(self.GetControl(), win32con.WM_GETTEXT, buf_size, buf) str_val = buf[:nchars] val = int(str_val) if val < 0 or val > 10: raise ValueError, "Value must be between 0 and 10" self.SetOptionValue(val*1000)
self.SetOptionValue(val*1000)
self.SetOptionValue(int(val*1000.0))
def UpdateValue_FromControl(self): buf_size = 100 buf = win32gui.PyMakeBuffer(buf_size) nchars = win32gui.SendMessage(self.GetControl(), win32con.WM_GETTEXT, buf_size, buf) str_val = buf[:nchars] val = int(str_val) if val < 0 or val > 10: raise ValueError, "Value must be between 0 and 10" self.SetOptionValue(val*1000)
urs = ["read", "unread"][self.unread]
if self.unread: urs = "read" else: urs = "unread"
def __repr__(self): urs = ["read", "unread"][self.unread] return "<%s, (%s) id=%s>" % (self.__class__.__name__, urs, mapi.HexFromBin(self.id))
folders = item.Folders
folders = item.Parent.Folders
def EnsureOutlookFieldsForFolder(self, folder_id, include_sub=False): # Ensure that our fields exist on the Outlook *folder* # Setting properties via our msgstore (via Ext Mapi) gets the props # on the message OK, but Outlook doesn't see it as a "UserProperty". # Using MAPI to set them directly on the folder also has n...
disposition = options["Hammie", "header_ham_string"]
disposition = options["Headers", "header_ham_string"]
def classifyInbox(v, vmoveto, bayes, ldbname, notesindex): # the notesindex hash ensures that a message is looked at only once if len(notesindex.keys()) == 0: firsttime = 1 else: firsttime = 0 docstomove = [] numham = 0 numspam = 0 numuns = 0 numdocs = 0 doc = v.GetFirstDocument() while doc: nid = doc.NOTEID if fir...
disposition = options["Hammie", "header_spam_string"]
disposition = options["Headers", "header_spam_string"]
def classifyInbox(v, vmoveto, bayes, ldbname, notesindex): # the notesindex hash ensures that a message is looked at only once if len(notesindex.keys()) == 0: firsttime = 1 else: firsttime = 0 docstomove = [] numham = 0 numspam = 0 numuns = 0 numdocs = 0 doc = v.GetFirstDocument() while doc: nid = doc.NOTEID if fir...
disposition = options["Hammie", "header_unsure_string"]
disposition = options["Headers", "header_unsure_string"]
def classifyInbox(v, vmoveto, bayes, ldbname, notesindex): # the notesindex hash ensures that a message is looked at only once if len(notesindex.keys()) == 0: firsttime = 1 else: firsttime = 0 docstomove = [] numham = 0 numspam = 0 numuns = 0 numdocs = 0 doc = v.GetFirstDocument() while doc: nid = doc.NOTEID if fir...
str = options["Hammie", "header_spam_string"] else: str = options["Hammie", "header_ham_string"]
str = options["Headers", "header_spam_string"] else: str = options["Headers", "header_ham_string"]
def processAndTrain(v, vmoveto, bayes, is_spam, notesindex): if is_spam: str = options["Hammie", "header_spam_string"] else: str = options["Hammie", "header_ham_string"] print "Training %s" % (str) docstomove = [] doc = v.GetFirstDocument() while doc: try: subj = doc.GetItemValue('Subject')[0] except: subj = 'No Sub...
if trainedas == options["Hammie", "header_spam_string"] and \
if trainedas == options["Headers", "header_spam_string"] and \
def processAndTrain(v, vmoveto, bayes, is_spam, notesindex): if is_spam: str = options["Hammie", "header_spam_string"] else: str = options["Hammie", "header_ham_string"] print "Training %s" % (str) docstomove = [] doc = v.GetFirstDocument() while doc: try: subj = doc.GetItemValue('Subject')[0] except: subj = 'No Sub...
elif trainedas == options["Hammie", "header_ham_string"] and \
elif trainedas == options["Headers", "header_ham_string"] and \
def processAndTrain(v, vmoveto, bayes, is_spam, notesindex): if is_spam: str = options["Hammie", "header_spam_string"] else: str = options["Hammie", "header_ham_string"] print "Training %s" % (str) docstomove = [] doc = v.GetFirstDocument() while doc: try: subj = doc.GetItemValue('Subject')[0] except: subj = 'No Sub...
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 trainnew and os.path.isdir(os.path.join(path, "new")): maildir_train(h, os.path.join(path, "new"), is_spam, force) elif os.path.i...
try:
if hasattr(obs, "onAddMessage"):
def addMessage(self, message): '''Add a Message to this corpus'''
except AttributeError: pass
def addMessage(self, message): '''Add a Message to this corpus'''
try:
if hasattr(obs, "onRemoveMessage"):
def removeMessage(self, message): '''Remove a Message from this corpus'''
except AttributeError: pass
def removeMessage(self, message): '''Remove a Message from this corpus'''
return len(self.db)
return len(self.keys())
def __len__(self): return len(self.db)
def keys(self): return self.classifier.keys()
def keys(self): return self.classifier.keys()
def __init__(self, folder_id, name):
def __init__(self, folder_id, name, ignore_eids = None):
def __init__(self, folder_id, name): self.folder_id = folder_id self.name = name self.children = []
def _BuildFoldersMAPI(manager, folder_id):
def _BuildFoldersMAPI(manager, folder_spec):
def _BuildFoldersMAPI(manager, folder_id): # This is called dynamically as folders are expanded. win32ui.DoWaitCursor(1) folder = manager.message_store.GetFolder(folder_id).OpenEntry() # Get the hierarchy table for it. table = folder.GetHierarchyTable(0) children = [] order = (((PR_DISPLAY_NAME_A, mapi.TABLE_SORT_ASCEN...
folder = manager.message_store.GetFolder(folder_id).OpenEntry()
folder = manager.message_store.GetFolder(folder_spec.folder_id).OpenEntry()
def _BuildFoldersMAPI(manager, folder_id): # This is called dynamically as folders are expanded. win32ui.DoWaitCursor(1) folder = manager.message_store.GetFolder(folder_id).OpenEntry() # Get the hierarchy table for it. table = folder.GetHierarchyTable(0) children = [] order = (((PR_DISPLAY_NAME_A, mapi.TABLE_SORT_ASCEN...
spec = FolderSpec(child_folder.GetID(), name)
spec = FolderSpec(child_folder.GetID(), name, folder_spec.ignore_eids)
def _BuildFoldersMAPI(manager, folder_id): # This is called dynamically as folders are expanded. win32ui.DoWaitCursor(1) folder = manager.message_store.GetFolder(folder_id).OpenEntry() # Get the hierarchy table for it. table = folder.GetHierarchyTable(0) children = [] order = (((PR_DISPLAY_NAME_A, mapi.TABLE_SORT_ASCEN...
def BuildFolderTreeMAPI(session):
def BuildFolderTreeMAPI(session, ignore_ids):
def BuildFolderTreeMAPI(session): root = FolderSpec(None, "root") tab = session.GetMsgStoresTable(0) prop_tags = PR_ENTRYID, PR_DISPLAY_NAME_A rows = mapi.HrQueryAllRows(tab, prop_tags, None, None, 0) for row in rows: (eid_tag, eid), (name_tag, name) = row hex_eid = mapi.HexFromBin(eid) try: msgstore = session.OpenMsgS...
hr, data = msgstore.GetProps((PR_IPM_SUBTREE_ENTRYID,), 0)
hr, data = msgstore.GetProps((PR_IPM_SUBTREE_ENTRYID,)+ignore_ids, 0)
def BuildFolderTreeMAPI(session): root = FolderSpec(None, "root") tab = session.GetMsgStoresTable(0) prop_tags = PR_ENTRYID, PR_DISPLAY_NAME_A rows = mapi.HrQueryAllRows(tab, prop_tags, None, None, 0) for row in rows: (eid_tag, eid), (name_tag, name) = row hex_eid = mapi.HexFromBin(eid) try: msgstore = session.OpenMsgS...
folder = msgstore.OpenEntry(subtree_eid, None, mapi.MAPI_DEFERRED_ERRORS)
ignore_eids = [item[1] for item in data[1:] if PROP_TYPE(item[0])==PT_BINARY]
def BuildFolderTreeMAPI(session): root = FolderSpec(None, "root") tab = session.GetMsgStoresTable(0) prop_tags = PR_ENTRYID, PR_DISPLAY_NAME_A rows = mapi.HrQueryAllRows(tab, prop_tags, None, None, 0) for row in rows: (eid_tag, eid), (name_tag, name) = row hex_eid = mapi.HexFromBin(eid) try: msgstore = session.OpenMsgS...
spec = FolderSpec(folder_id, name)
spec = FolderSpec(folder_id, name, ignore_eids)
def BuildFolderTreeMAPI(session): root = FolderSpec(None, "root") tab = session.GetMsgStoresTable(0) prop_tags = PR_ENTRYID, PR_DISPLAY_NAME_A rows = mapi.HrQueryAllRows(tab, prop_tags, None, None, 0) for row in rows: (eid_tag, eid), (name_tag, name) = row hex_eid = mapi.HexFromBin(eid) try: msgstore = session.OpenMsgS...
desc_noun_suffix="ed"):
desc_noun_suffix="ed", exclude_prop_ids=(PR_IPM_WASTEBASKET_ENTRYID, PR_IPM_SENTMAIL_ENTRYID, PR_IPM_OUTBOX_ENTRYID) ):
def __init__ (self, manager, selected_ids=None, single_select=False, checkbox_state=False, checkbox_text=None, desc_noun="Select", desc_noun_suffix="ed"): assert not single_select or selected_ids is None or len(selected_ids)<=1 dialog.Dialog.__init__ (self, self.dt) self.single_select = single_select self.next_item_id ...
tree = BuildFolderTreeMAPI(self.manager.message_store.session)
tree = BuildFolderTreeMAPI(self.manager.message_store.session, self.exclude_prop_ids)
def OnInitDialog (self): caption = "%s folder" % (self.select_desc_noun,) if not self.single_select: caption += "(s)" self.SetWindowText(caption) self.SetDlgItemText(IDC_BUTTON_SEARCHSUB, self.checkbox_text) if self.checkbox_state is None: self.GetDlgItem(IDC_BUTTON_SEARCHSUB).ShowWindow(win32con.SW_HIDE) else: self.Ge...
folderSpec.children = _BuildFoldersMAPI(self.manager, folderSpec.folder_id)
folderSpec.children = _BuildFoldersMAPI(self.manager, folderSpec)
def OnTreeItemExpanding(self,(hwndFrom, idFrom, code), extra): if idFrom != IDC_LIST_FOLDERS: return None action, itemOld, itemNew, pt = extra if action == 1: return 0 # contracting, not expanding
import sys
import sys, types
def bool(val): return not not val
if data_source_name.find('::') != -1:
if (isinstance(data_source_name, types.StringTypes) and data_source_name.find('::') != -1):
def open_storage(data_source_name, useDB=True): """Return a storage object appropriate to the given parameters. By centralizing this code here, all the applications will behave the same given the same options. If useDB is false, a pickle will be used, otherwise if the data source name includes "::", whatever is befor...
except email.Errors.MessageParseError, e:
except:
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) try: response = imap.uid("FE...
spamtxt = "spam"
spamtxt = options["Headers", "header_spam_string"]
def msg_train(h, msg, is_spam, force): """Train bayes with a single message.""" # XXX: big hack -- why is email.Message unable to represent # multipart/alternative? try: msg.as_string() except TypeError: # We'll be unable to represent this as text :( return False if is_spam: spamtxt = "spam" else: spamtxt = "ham" old...
spamtxt = "ham"
spamtxt = options["Headers", "header_ham_string"]
def msg_train(h, msg, is_spam, force): """Train bayes with a single message.""" # XXX: big hack -- why is email.Message unable to represent # multipart/alternative? try: msg.as_string() except TypeError: # We'll be unable to represent this as text :( return False if is_spam: spamtxt = "spam" else: spamtxt = "ham" old...
def maildir_train(h, path, is_spam, force):
def maildir_train(h, path, is_spam, force, removetrained):
def maildir_train(h, path, is_spam, force): """Train bayes with all messages from a maildir.""" if loud: print " Reading as Maildir" import time import socket pid = os.getpid() host = socket.gethostname() counter = 0 trained = 0 for fn in os.listdir(path): counter += 1 cfn = os.path.join(path, fn) tfn = os.path.no...
if loud: print " Reading as Maildir"
if loud: print " Reading %s as Maildir" % (path,)
def maildir_train(h, path, is_spam, force): """Train bayes with all messages from a maildir.""" if loud: print " Reading as Maildir" import time import socket pid = os.getpid() host = socket.gethostname() counter = 0 trained = 0 for fn in os.listdir(path): counter += 1 cfn = os.path.join(path, fn) tfn = os.path.no...
counter += 1
def maildir_train(h, path, is_spam, force): """Train bayes with all messages from a maildir.""" if loud: print " Reading as Maildir" import time import socket pid = os.getpid() host = socket.gethostname() counter = 0 trained = 0 for fn in os.listdir(path): counter += 1 cfn = os.path.join(path, fn) tfn = os.path.no...
def train(h, path, is_spam, force, trainnew):
def train(h, path, is_spam, force, trainnew, removetrained):
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) if trainnew: maildir_train(...
maildir_train(h, os.path.join(path, "cur"), is_spam, force)
maildir_train(h, os.path.join(path, "cur"), is_spam, force, removetrained)
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) if trainnew: maildir_train(...
maildir_train(h, os.path.join(path, "new"), is_spam, force)
maildir_train(h, os.path.join(path, "new"), is_spam, force, removetrained)
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) if trainnew: maildir_train(...
opts, args = getopt.getopt(sys.argv[1:], 'hfqnd:D:g:s:')
opts, args = getopt.getopt(sys.argv[1:], 'hfqnrd:D:g:s:')
def main(): """Main program; parse options and go.""" global loud try: opts, args = getopt.getopt(sys.argv[1:], 'hfqnd:D:g:s:') except getopt.error, msg: usage(2, msg) if not opts: usage(2, "No options given") pck = None usedb = None force = False trainnew = False good = [] spam = [] for opt, arg in opts: if opt ==...
train(h, g, False, force, trainnew)
train(h, g, False, force, trainnew, removetrained)
def main(): """Main program; parse options and go.""" global loud try: opts, args = getopt.getopt(sys.argv[1:], 'hfqnd:D:g:s:') except getopt.error, msg: usage(2, msg) if not opts: usage(2, "No options given") pck = None usedb = None force = False trainnew = False good = [] spam = [] for opt, arg in opts: if opt ==...
train(h, s, True, force, trainnew)
train(h, s, True, force, trainnew, removetrained)
def main(): """Main program; parse options and go.""" global loud try: opts, args = getopt.getopt(sys.argv[1:], 'hfqnd:D:g:s:') except getopt.error, msg: usage(2, msg) if not opts: usage(2, "No options given") pck = None usedb = None force = False trainnew = False good = [] spam = [] for opt, arg in opts: if opt ==...
opts, args = getopt.getopt(argv, "hns:p:r:o:",
opts, args = getopt.getopt(argv, "hns:p:r:t:o:",
def main(argv): null = False server = "localhost" port = options["html_ui", "port"] prob = 1.0 try: opts, args = getopt.getopt(argv, "hns:p:r:o:", ["help", "null", "server=", "port=", "prob=", "option="]) except getopt.error: usage(globals(), locals()) sys.exit(1) for opt, arg in opts: if opt in ("-h", "--help"): usa...
"prob=", "option="])
"prob=", "train=", "option="])
def main(argv): null = False server = "localhost" port = options["html_ui", "port"] prob = 1.0 try: opts, args = getopt.getopt(argv, "hns:p:r:o:", ["help", "null", "server=", "port=", "prob=", "option="]) except getopt.error: usage(globals(), locals()) sys.exit(1) for opt, arg in opts: if opt in ("-h", "--help"): usa...
post_multipart("%s:%d"%(server,port), "/upload", [], [('file', 'message.dat', data)])
if train_as is not None: which_text = "Train as %s" % (train_as,) post_multipart("%s:%d" % (server, port), "/train", [("which", which_text), ("text", "")], [("file", "message.dat", data)]) else: post_multipart("%s:%d" % (server,port), "/upload", [], [('file', 'message.dat', data)])
def main(argv): null = False server = "localhost" port = options["html_ui", "port"] prob = 1.0 try: opts, args = getopt.getopt(argv, "hns:p:r:o:", ["help", "null", "server=", "port=", "prob=", "option="]) except getopt.error: usage(globals(), locals()) sys.exit(1) for opt, arg in opts: if opt in ("-h", "--help"): usa...
if opt in notate_opt and \
if (notate_opt is not None) and (opt in notate_opt) and \
def takeMessage(self, key, fromcorpus, fromCache=False): '''Move a Message from another corpus to this corpus''' msg = fromcorpus[key] msg.load() # ensure that the substance has been loaded
print >>sys.stderr, "Can't connect to %s:%d: %s" % \ (serverName, serverPort, e)
error = "Can't connect to %s:%d: %s" % (serverName, serverPort, e) print >>sys.stderr, error self.lineCallback('-ERR %s\r\n' % error) 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) try: self.connect((serverName, serverPort)) except socket.error, e: print >>sys.stderr, "Can't ...
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) try: self.connect((serverName, serverPort)) except socket.error, e: print >>sys.stderr, "Can't ...
return len(args) == 0
return len(self.args) == 0
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']...
<td class='reviewheaders'><b>
<td class='reviewheaders' nowrap><b>
def __init__(self, uiPort, socketMap=asyncore.socket_map): Listener.__init__(self, uiPort, UserInterface, (), socketMap=socketMap)
win32api.MoveFileEx(src, dest, win32con.MOVEFILE_COPY_ALLOWED) else: shutil.copyfile(src, dest)
os.remove(src)
def _MigrateFile(self, filename, do_move = True): src = os.path.join(self.application_directory, filename) dest = os.path.join(self.data_directory, filename) if os.path.isfile(src) and not os.path.isfile(dest): if do_move: # shutil in 2.2 and earlier does not contain 'move' win32api.MoveFileEx(src, dest, win32con.MOVEF...
def Update(self):
def MoveTo(self, dest): if self.previous_folder is not None: self.previous_folder = self.folder_name self.folder_name = dest def Save(self):
def Update(self): # we can't actually update the message with IMAP # so what we do is create a new message and delete the old one response = imap.append(self.folder_name, None, self.extractTime(), self.get_payload()) response = imap.select(self.folder_name, False) response = imap.uid("STORE", self.getId(), "+FLAGS.SILE...
response = imap.select(self.folder_name, False) response = imap.uid("STORE", self.getId(), "+FLAGS.SILENT", "(\\Deleted)")
def Update(self): # we can't actually update the message with IMAP # so what we do is create a new message and delete the old one response = imap.append(self.folder_name, None, self.extractTime(), self.get_payload()) response = imap.select(self.folder_name, False) response = imap.uid("STORE", self.getId(), "+FLAGS.SILE...
self.changeId(response[1][0]) def Delete(self): self._selectFolder(self.folder_name, False) response = imap.uid("STORE", self.getId(), "+FLAGS.SILENT", "(\\Deleted)") self._check(response, "uid store") self.notTrained() self.notClassified() def Append(self): response = imap.append(self.folder_name, None, self.getId...
old_id = self.id self.id = response[1][0] if self.previous_folder is not None: response = imap.select(self.previous_folder, False) self.previous_folder = None
def Update(self): # we can't actually update the message with IMAP # so what we do is create a new message and delete the old one response = imap.append(self.folder_name, None, self.extractTime(), self.get_payload()) response = imap.select(self.folder_name, False) response = imap.uid("STORE", self.getId(), "+FLAGS.SILE...
self.spam_folder = IMAPFolder(options.imap_spam_folder) self.unsure_folder = IMAPFolder(options.imap_unsure_folder)
def __init__(self): global imap imap = imaplib.IMAP4(options.imap_server, options.imap_port) self.spam_folder = IMAPFolder(options.imap_spam_folder) self.unsure_folder = IMAPFolder(options.imap_unsure_folder) if options.verbose: print "Loading database...", filename = options.pop3proxy_persistent_storage_file filenam...
def _check(self, response, command): if response[0] != "OK": print "Invalid response to %s:\n%s" % (command, response) sys.exit(-1) def _selectFolder(self, name, read_only): folder = imap.select(name, read_only) self._check(folder, 'select') return folder
def _check(self, response, command): if response[0] != "OK": print "Invalid response to %s:\n%s" % (command, response) sys.exit(-1)