rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
imap = IMAPSession(server, port, imapDebug, doExpunge)
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...
print "Service not availible. Using thread."
print "Service not available. Using thread."
def __init__(self): # The ordering here is important - it is the order that they will # appear in the menu. As dicts don't have an order, this means # that the order is controlled by the id. Any items where the # function is None will appear as separators. self.control_functions = {START_STOP_ID : ("Stop SpamBayes", ...
out = TemporaryFile("w")
out = TemporaryFile()
def update_file(self, filename): '''Update the specified configuration file.''' sectname = None optname = None out = TemporaryFile("w") 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 options["globals", "verbose"]: print "Creati...
f = file(filename)
f = file(filename, "w") out.seek(0)
def update_file(self, filename): '''Update the specified configuration file.''' sectname = None optname = None out = TemporaryFile("w") 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 options["globals", "verbose"]: print "Creati...
Q = 1.0 - P**n * 2.0**(Qexp * n)
Q = 1.0 - Q**n * 2.0**(Qexp * n)
def robinson_spamprob(self, wordstream, evidence=False): """Return best-guess probability that wordstream is spam.
n = hamcount + spamratio
n = hamcount + spamcount
def robinson_update_probabilities(self): """Update the word probabilities in the spam database.
mgr.bayes.unlearn(tokenize(stream), was_spam, False)
mgr.bayes.unlearn(tokenize(stream), was_spam)
def train_message(msg, is_spam, mgr, rescore=False): # Train an individual message. # Returns True if newly added (message will be correctly # untrained if it was in the wrong category), False if already # in the correct category. Catch your own damn exceptions. # If re-classified AND rescore = True, then a new score ...
mgr.bayes.learn(tokenize(stream), is_spam, False)
mgr.bayes.learn(tokenize(stream), is_spam)
def train_message(msg, is_spam, mgr, rescore=False): # Train an individual message. # Returns True if newly added (message will be correctly # untrained if it was in the wrong category), False if already # in the correct category. Catch your own damn exceptions. # If re-classified AND rescore = True, then a new score ...
mgr.bayes.update_probabilities()
def train_message(msg, is_spam, mgr, rescore=False): # Train an individual message. # Returns True if newly added (message will be correctly # untrained if it was in the wrong category), False if already # in the correct category. Catch your own damn exceptions. # If re-classified AND rescore = True, then a new score ...
subject = msgstore_message.GetSubject()
def ProcessMessage(msgstore_message, manager): manager.LogDebug(2, "ProcessMessage starting for message '%s'" \ % msgstore_message.subject) if not msgstore_message.IsFilterCandidate(): manager.LogDebug(1, "Skipping message '%s' - we don't filter ones like that!" \ % msgstore_message.subject) return if HaveSeenMessage(...
print "Training on message '%s' - " % subject, if train.train_message(msgstore_message, False, manager, rescore = True): print "trained as good"
if train.been_trained_as_spam(msgstore_message, manager): need_train = True
def ProcessMessage(msgstore_message, manager): manager.LogDebug(2, "ProcessMessage starting for message '%s'" \ % msgstore_message.subject) if not msgstore_message.IsFilterCandidate(): manager.LogDebug(1, "Skipping message '%s' - we don't filter ones like that!" \ % msgstore_message.subject) return if HaveSeenMessage(...
print "already was trained as good" assert train.been_trained_as_ham(msgstore_message, manager) manager.SaveBayesPostIncrementalTrain()
prop = msgstore_message.GetField(manager.config.general.field_score_name) if prop is None: prop = manager.score(msgstore_message) need_train = manager.config.filter.unsure_threshold < prop * 100 subject = msgstore_message.subject if need_train: print "Training on message '%s' - " % subject, if train.train_message...
def ProcessMessage(msgstore_message, manager): manager.LogDebug(2, "ProcessMessage starting for message '%s'" \ % msgstore_message.subject) if not msgstore_message.IsFilterCandidate(): manager.LogDebug(1, "Skipping message '%s' - we don't filter ones like that!" \ % msgstore_message.subject) return if HaveSeenMessage(...
print "Please delete any test messages from your Spam, Unsure or Inbox folders first."
print "Please delete any test messages from your Spam, Unsure or Inbox/Watch folders first."
def Tester(manager): import tester # This is only used in source-code versions - so we may as well reload # the test suite to save shutting down Outlook each time we tweak it. reload(tester) try: print "Executing automated tests..." tester.test(manager) print "Tests worked." except: traceback.print_exc() print "Tests F...
imap.close()
self.imap_server.close()
def SelectFolder(self, folder): """A method to point ensuing IMAP operations at a target folder.
if isinstance(fol, ()): r = re.compile(r"{\d+}") m = r.search(fol[0])
if isinstance(fol, types.TupleType): m = re.search(r"{\d+}", fol[0])
def folder_list(self): """Return a alphabetical list of all folders available on the server.""" response = self.list() try: all_folders = self.check_response("list", response) except BadIMAPResponse: # We want to keep going, so just print out a warning, and # return an empty list. print "Could not retrieve folder list....
except BadIMAPResponse:
except BadIMAPResponseError:
def get_full_message(self): """Retrieve the RFC822 message from the IMAP server and return a new IMAPMessage object that has the same details as this message, but also has the substance.""" if self.got_substance: return self
text, details = message.insert_exception_header(data["RFC822"])
text, details = message.insert_exception_header( data[self.rfc822_key], self.id)
def get_full_message(self): """Retrieve the RFC822 message from the IMAP server and return a new IMAPMessage object that has the same details as this message, but also has the substance.""" if self.got_substance: return self
except BadIMAPResponse:
except BadIMAPResponseError:
def Save(self): """Save message to IMAP server.
except BadIMAPResponse:
except BadIMAPResponseError:
def Filter(self): assert self.imap_server, "Cannot do anything without IMAP server." if not self.spam_folder: self.spam_folder = IMAPFolder(options["imap", "spam_folder"], self.imap_server) if not self.unsure_folder: self.unsure_folder = IMAPFolder(options["imap", "unsure_folder"], self.imap_server)
BayesProxyListener('localhost', 8110, 8111)
BayesProxyListener('localhost', 8110, ('', 8111))
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() Dibbler.run...
print test_tuple, v0, v1
def unconvert(self): '''Convert value from the appropriate type to a string.''' if type(self.value) in types.StringTypes: # nothing to do return self.value if self.is_boolean(): # A wee bit extra for Python 2.2 if self.value == True: return "True" else: return "False" if type(self.value) == types.TupleType: if len(self...
value = tuple(value.split(' '))
value = tuple(value.split())
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) # backward compatibility guff if opt[:len(sect) + 1].lower() == sect.lower() + '_': opt = opt[len(sect)+1:] # end of backward compatibility ...
PR_MESSAGE_CLASS_A)
PR_MESSAGE_CLASS_A, PR_MESSAGE_FLAGS, )
def GetNewUnscoredMessageGenerator(self, scoreFieldName): folder = self.msgstore._OpenEntry(self.id) table = folder.GetContentsTable(0) # Resolve the field name resolve_props = ( (mapi.PS_PUBLIC_STRINGS, scoreFieldName), ) resolve_ids = folder.GetIDsFromNames(resolve_props, 0) field_id = PROP_TAG( PT_DOUBLE, PROP_ID(re...
return self.msgclass.lower().startswith("ipm.note")
return self.msgclass.lower().startswith("ipm.note") and \ not self.is_unsent
def IsFilterCandidate(self): # We don't attempt to filter: # * Non-mail items # Later we would like to add: # * Messages that have never been sent (ie, user-composed) return self.msgclass.lower().startswith("ipm.note")
return self.parse_line(self.fp.next())
return self.parse_line(self.fp.readline())
def next(self): return self.parse_line(self.fp.next())
line = line + self.fp.next()
line = line + self.fp.readline()
def parse_line(self, line): """parse the line.
line = line[len(field)+len(match.group(2))]
line = line[len(field)+len(match.group(2)):]
def parse_line(self, line): """parse the line.
import SpamBayes.Version
import spambayes.Version
def fix_sys_path(): # XXX - MarkH had the bright idea *after* writing this that we should # ensure the CVS version of SpamBayes is *not* used to resolve SB imports. # This would allow us to effectively test the distutils setup script, so # any modules or files missing from the installed version raise errors. """Fix sys...
parent = distutils.command.sdist.sdist class sdist(parent):
sdist_parent = distutils.command.sdist.sdist class sdist(sdist_parent):
def run(self): err = False for s in self.old_scripts: s = os.path.join(self.install_dir, s) for e in (".py", ".pyc", ".pyo"): if os.path.exists(s+e): print >> sys.stderr, "Error: old script", s+e, print >> sys.stderr, "still exists." err = True if err: print >>sys.stderr, "Do you want to delete these scripts? (y/n)" an...
retval = parent.run(self)
retval = sdist_parent.run(self)
def run(self): import md5 retval = parent.run(self) for archive in self.get_archive_files(): data = file(archive, "rb").read() print '\n', archive, "\n\tMD5:", md5.md5(data).hexdigest() print "\tLength:", len(data) return retval
perc_spam_incorrect_or_unsure = 100.0
perc_spam_correct_or_unsure = 100.0
def GetStats(self, session_only=False, decimal_points=1): """Return a description of the statistics.
push((_("Ham incorrectly identified:\t%(perc_ham_incorrect_s)s (+ %(perc_ham_unsure_s)s unsure)") \
push((_("Good incorrectly identified:\t%(perc_ham_incorrect_s)s (+ %(perc_ham_unsure_s)s unsure)") \
def GetStats(self, session_only=False, decimal_points=1): """Return a description of the statistics.
print rows
def _FindItemsWithValue(folder, prop_tag, prop_val): tab = folder.GetContentsTable(0) # Restriction for the table: get rows where our prop values match restriction = (mapi.RES_CONTENT, # a property restriction (mapi.FL_SUBSTRING | mapi.FL_IGNORECASE | mapi.FL_LOOSE, # fuzz level prop_tag, # of the given prop (prop...
self.proxyPorts = []
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...
if options["pop3proxy", "listen_ports"]: splitPorts = options["pop3proxy", "listen_ports"] self.proxyPorts = map(_addressAndPort, splitPorts)
if not hasattr(self, "proxyPorts"): self.proxyPorts = [] if options["pop3proxy", "listen_ports"]: splitPorts = options["pop3proxy", "listen_ports"] self.proxyPorts = map(_addressAndPort, splitPorts)
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...
state.proxyPorts = [_addressAndPort(arg)]
state.proxyPorts = [_addressAndPort(a) for a in arg.split(',')]
def run(): global state # Read the arguments. try: opts, args = getopt.getopt(sys.argv[1:], 'hbd:p:l:u:o:') 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 == '-b': state.launc...
self.event_stop = threading.Event()
self.event_stopped = threading.Event() self.event_stopping = threading.Event()
def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.event_stop = threading.Event() self.thread = None
pop3proxy.stop(pop3proxy.state)
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) self.event_stopping.set() pop3proxy.stop(pop3proxy.state)
def SvcStop(self): pop3proxy.stop(pop3proxy.state)
self.event_stop.wait()
self.event_stopping.wait() for i in range(20): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) self.event_stopped.wait(1) if self.event_stopped.isSet(): break print "The service is still shutting down..." else: print "The worker failed to stop - aborting it anyway"
def SvcDoRun(self): # Setup our state etc pop3proxy.prepare(state=pop3proxy.state) assert not pop3proxy.state.launchUI, "Service can't launch a UI"
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) self.event_stop.set()
self.event_stopping.set() self.event_stopped.set()
def ServerThread(self): try: try: pop3proxy.start(pop3proxy.state) except SystemExit: # user requested shutdown print "pop3proxy service shutting down due to user request" except: # Otherwise an error we should log. ob = cStringIO.StringIO() traceback.print_exc(file=ob)
Debug = debug
def __init__(self, server, port, debug=0, do_expunge=False): Debug = debug # this is a global in the imaplib module try: BaseIMAP.__init__(self, server, port) except: # A more specific except would be good here, but I get # (in Python 2.2) a generic 'error' and a 'gaierror' # if I pass a valid domain that isn't an IMA...
if options["globals", "verbose"]: sys.stdout.write(".")
def __getitem__(self, key): '''Return message (no substance) matching the given *uid*.''' # We don't retrieve the substances of the message here - you need # to call msg.get_substance() to do that. imap.SelectFolder(self.name) # Using RFC822.HEADER.LINES would be better here, but it seems # that not all servers accept ...
pass
count["ham"] += 1
def Filter(self, classifier, spamfolder, unsurefolder): for msg in self: if msg.GetClassification() is None: msg.get_substance() (prob, clues) = classifier.spamprob(msg.asTokens(), evidence=True) # add headers and remember classification msg.addSBHeaders(prob, clues)
count["unsure"] += 1
def Filter(self, classifier, spamfolder, unsurefolder): for msg in self: if msg.GetClassification() is None: msg.get_substance() (prob, clues) = classifier.spamprob(msg.asTokens(), evidence=True) # add headers and remember classification msg.addSBHeaders(prob, clues)
return count
def Filter(self, classifier, spamfolder, unsurefolder): for msg in self: if msg.GetClassification() is None: msg.get_substance() (prob, clues) = classifier.spamprob(msg.asTokens(), evidence=True) # add headers and remember classification msg.addSBHeaders(prob, clues)
folder.Filter(self.classifier, self.spam_folder,
count = folder.Filter(self.classifier, self.spam_folder,
def Filter(self): if options["globals", "verbose"]: t = time.time()
print "Filtering took", time.time() - t, "seconds."
if count is not None: print "\nClassified %s ham, %s spam, and %s unsure." % \ (count["ham"], count["spam"], count["unsure"]) print "Classifying took", time.time() - t, "seconds."
def Filter(self): if options["globals", "verbose"]: t = time.time()
good = spam = unknown = None
good = [] spam = [] unknown = []
def main(): """Main program; parse options and go.""" try: opts, args = getopt.getopt(sys.argv[1:], 'hdfg:s:p:u:') except getopt.error, msg: usage(2, msg) if not opts: usage(2, "No options given") pck = DEFAULTDB good = spam = unknown = None do_filter = usedb = False for opt, arg in opts: if opt == '-h': usage(0) eli...
good = arg
good.append(arg)
def main(): """Main program; parse options and go.""" try: opts, args = getopt.getopt(sys.argv[1:], 'hdfg:s:p:u:') except getopt.error, msg: usage(2, msg) if not opts: usage(2, "No options given") pck = DEFAULTDB good = spam = unknown = None do_filter = usedb = False for opt, arg in opts: if opt == '-h': usage(0) eli...
spam = arg
spam.append(arg)
def main(): """Main program; parse options and go.""" try: opts, args = getopt.getopt(sys.argv[1:], 'hdfg:s:p:u:') except getopt.error, msg: usage(2, msg) if not opts: usage(2, "No options given") pck = DEFAULTDB good = spam = unknown = None do_filter = usedb = False for opt, arg in opts: if opt == '-h': usage(0) eli...
unknown = arg
unknown.append(arg)
def main(): """Main program; parse options and go.""" try: opts, args = getopt.getopt(sys.argv[1:], 'hdfg:s:p:u:') except getopt.error, msg: usage(2, msg) if not opts: usage(2, "No options given") pck = DEFAULTDB good = spam = unknown = None do_filter = usedb = False for opt, arg in opts: if opt == '-h': usage(0) eli...
print "Training ham:" train(bayes, good, False)
for g in good: print "Training ham (%s):" % g train(bayes, g, False)
def main(): """Main program; parse options and go.""" try: opts, args = getopt.getopt(sys.argv[1:], 'hdfg:s:p:u:') except getopt.error, msg: usage(2, msg) if not opts: usage(2, "No options given") pck = DEFAULTDB good = spam = unknown = None do_filter = usedb = False for opt, arg in opts: if opt == '-h': usage(0) eli...
print "Training spam:" train(bayes, spam, True)
for s in spam: print "Training spam (%s):" % s train(bayes, s, True)
def main(): """Main program; parse options and go.""" try: opts, args = getopt.getopt(sys.argv[1:], 'hdfg:s:p:u:') except getopt.error, msg: usage(2, msg) if not opts: usage(2, "No options given") pck = DEFAULTDB good = spam = unknown = None do_filter = usedb = False for opt, arg in opts: if opt == '-h': usage(0) eli...
score(bayes, unknown)
for u in unknown: if len(unknown) > 1: print "Scoring", u score(bayes, u)
def main(): """Main program; parse options and go.""" try: opts, args = getopt.getopt(sys.argv[1:], 'hdfg:s:p:u:') except getopt.error, msg: usage(2, msg) if not opts: usage(2, "No options given") pck = DEFAULTDB good = spam = unknown = None do_filter = usedb = False for opt, arg in opts: if opt == '-h': usage(0) eli...
code_and_country = os.path.join(LC_DIR, "languages", lcode, 'DIALOGS')
code_and_country = os.path.join(DIALOGS_DIR, lcode, 'DIALOGS')
def _rebuild_syspath_for_dialogs(self): """Add to sys.path the directories of the translated dialogs.
if useDBM:
if useDBM == "dbm" or useDBM == True:
def runImport(dbFN, useDBM, newDBM, inFN): if newDBM: try: os.unlink(dbFN) except OSError: pass try: os.unlink(dbFN+".dat") except OSError: pass try: os.unlink(dbFN+".dir") except OSError: pass bayes = spambayes.storage.open_storage(dbFN, useDBM) try: fp = open(inFN, 'rb') except IOError, e: if e.errno != errno.EN...
useDBM = False
useDBM = "pickle"
def runImport(dbFN, useDBM, newDBM, inFN): if newDBM: try: os.unlink(dbFN) except OSError: pass try: os.unlink(dbFN+".dat") except OSError: pass try: os.unlink(dbFN+".dir") except OSError: pass bayes = spambayes.storage.open_storage(dbFN, useDBM) try: fp = open(inFN, 'rb') except IOError, e: if e.errno != errno.EN...
SetButtonImage(self, image)
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)
SetButtonImage(self, image)
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 SetButtonImage(button, fname):
def SetButtonImage(button, fname, manager):
def SetButtonImage(button, fname): # whew - http://support.microsoft.com/default.aspx?scid=KB;EN-US;q288771 # shows how to make a transparent bmp. # Also note that the clipboard takes ownership of the handle - # this, we can not simply perform this load once and reuse the image. if not os.path.isabs(fname): if hasattr(...
if hasattr(sys, "frozen"): fname = os.path.join(os.path.dirname(sys.argv[0]),
fname = os.path.join(manager.application_directory,
def SetButtonImage(button, fname): # whew - http://support.microsoft.com/default.aspx?scid=KB;EN-US;q288771 # shows how to make a transparent bmp. # Also note that the clipboard takes ownership of the handle - # this, we can not simply perform this load once and reuse the image. if not os.path.isabs(fname): if hasattr(...
else: fname = os.path.join( os.path.dirname(__file__), "images", fname)
def SetButtonImage(button, fname): # whew - http://support.microsoft.com/default.aspx?scid=KB;EN-US;q288771 # shows how to make a transparent bmp. # Also note that the clipboard takes ownership of the handle - # this, we can not simply perform this load once and reuse the image. if not os.path.isabs(fname): if hasattr(...
state.bayes.store() state.bayes.close()
if hasattr(state, "bayes"): state.bayes.store() state.bayes.close()
def _recreateState(): global state # Close the existing listeners and create new ones. This won't # affect any running proxies - once a listener has created a proxy, # that proxy is then independent of it. for proxy in proxyListeners: proxy.close() del proxyListeners[:] # Close the database; we should anyway, and gd...
'[0123456789]*', cacheSize=20)
'[0123456789\-]*', cacheSize=20)
def ensureDir(dirname): try: os.mkdir(dirname) except OSError, e: if e.errno != errno.EEXIST: raise
try: wi = state.bayes.wordinfo[word]
wi = state.bayes._wordinfoget(word) if wi:
def onWordquery(self, params): word = params['word'] word = word.lower() try: wi = state.bayes.wordinfo[word] members = wi.__dict__ members['spamprob'] = state.bayes.probability(wi) info = """Number of spam messages: <b>%(spamcount)d</b>.<br> Number of ham messages: <b>%(hamcount)d</b>.<br> Probability that a message c...
except KeyError:
else:
def onWordquery(self, params): word = params['word'] word = word.lower() try: wi = state.bayes.wordinfo[word] members = wi.__dict__ members['spamprob'] = state.bayes.probability(wi) info = """Number of spam messages: <b>%(spamcount)d</b>.<br> Number of ham messages: <b>%(hamcount)d</b>.<br> Probability that a message c...
h = hamdirs[:] s = spamdirs[:] hexclude = h.pop(i) sexclude = s.pop(i) d.forget(MsgStream(hexclude, [hexclude]), MsgStream(sexclude, [sexclude])) d.test(MsgStream("Data/Ham/*-Set%d" % (i+1), h), MsgStream("Data/Spam/*-Set%d" % (i+1), s))
h = hamdirs[i] s = spamdirs[i] hamstream = MsgStream(h, [h]) spamstream = MsgStream(s, [s]) d.forget(hamstream, spamstream) d.test(hamstream, spamstream)
def drive(nsets): print options.display() hamdirs = ["Data/Ham/Set%d" % i for i in range(1, nsets+1)] spamdirs = ["Data/Spam/Set%d" % i for i in range(1, nsets+1)] d = Driver() # Train it on all the data. d.train(MsgStream("%s-%d" % (hamdirs[0], nsets), hamdirs), MsgStream("%s-%d" % (spamdirs[0], nsets), spamdirs)) ...
print "TabProcessor Done"
def Done(self): print "TabProcessor Done" if self.currentPageHwnd is not None: if not self.currentPage.SaveAllControls(): win32gui.SendMessage(self.GetControl(), commctrl.TCM_SETCURSEL, self.currentPageIndex,0) return False return True
print "About to train with", config.training.spam_folder_ids
def WizardTrainer(mgr, config, progress): import os, manager, train bayes_base = os.path.join(mgr.data_directory, "$sbwiz$default_bayes_database") mdb_base = os.path.join(mgr.data_directory, "$sbwiz$default_message_database") fnames = [] for ext in ".pck", ".db": fnames.append(bayes_base+ext) fnames.append(mdb_base+ext...
options = dict([s.split('=') for s in login.split(", ")])
options = dict(self._login_splitter.findall(login))
def stripQuotes(s): return (s[0] == '"' and s[-1] == '"') and s[1:-1] or s
for id_header in [custom_header_id, "Message-ID\: ?\<([^\>]+)\>"]:
for id_header in [custom_header_id, "Message-ID\: ?\<([^\n\>]+)\>"]:
def __getitem__(self, key): """Return message matching the given *uid*.
return "\n".join([flatten(b) for b in body]) raise TypeError, ("unrecognized body type: %s" % type(body))
return "\n".join([flatten(b) for b in obj]) raise TypeError, ("unrecognized body type: %s" % type(obj))
def flatten(obj): # I do not know how to use the email package very well - all I want here # is the body of obj expressed as a string - there is probably a better # way to accomplish this which I haven't discovered. # three types are possible: string, Message (hasattr(get_payload)), list if isinstance(obj, str): return...
if options["Tokenizer", "search_for_habeas_headers"]:
if options["Tokenizer", "X-search_for_habeas_headers"]:
def tokenize_headers(self, msg): # Special tagging of header lines and MIME metadata.
if options["Tokenizer", "reduce_habeas_headers"]:
if options["Tokenizer", "X-reduce_habeas_headers"]:
def tokenize_headers(self, msg): # Special tagging of header lines and MIME metadata.
ratio += "%8s" % ("%d:%d" % (htest, stest))
if len(ratio) > len(rat2): ratio += " " ratio = ratio[0:(len(rat2) + 8)] rat2 += " %7s" % ("%d:%d" % (htest, stest)) else: rat2 += " " rat2 = rat2[0:(len(ratio) + 8)] ratio += " %7s" % ("%d:%d" % (htest, stest))
def windowsfy(fn): import os if os.path.exists(fn + '.txt'): return fn + '.txt' else: return fn
mapi_store = self.msgstore._GetMessageStore(self.id[0]) eid, ret_class = mapi_store.GetReceiveFolder(msg_class, 0) return mapi_store.CompareEntryIDs(eid, self.id[1])
try: mapi_store = self.msgstore._GetMessageStore(self.id[0]) eid, ret_class = mapi_store.GetReceiveFolder(msg_class, 0) return mapi_store.CompareEntryIDs(eid, self.id[1]) except pythoncom.com_error: return False
def IsReceiveFolder(self, msg_class = "IPM.Note"): # Is this folder the nominated "receive folder" for its store? mapi_store = self.msgstore._GetMessageStore(self.id[0]) eid, ret_class = mapi_store.GetReceiveFolder(msg_class, 0) return mapi_store.CompareEntryIDs(eid, self.id[1])
print ("Saving bayes database with %d spam and %d good messages" % (bayes.nspam, bayes.nham))
print "Saving bayes database with %d spam and %d good messages" %\ (bayes.nspam, bayes.nham)
def SaveBayes(self): bayes = self.bayes if self.verbose: print ("Saving bayes database with %d spam and %d good messages" % (bayes.nspam, bayes.nham)) print " ->", self.bayes_filename cPickle.dump(bayes, open(self.bayes_filename,"wb"), 1) if self.verbose: print " ->", self.message_db_filename cPickle.dump(self.message_...
msg = factory.create(key, message)
key = self.msg_name_func() msg = corpus.makeMessage(key, message) msg.setId(key)
def onTrain(self, file, text, which): """Train on an uploaded or pasted message.""" self._writePreamble(_("Train"))
disp = options.header_unknown_string
disp = options.header_unsure_string
def filter(self, msg, header=DISPHEADER, spam_cutoff=SPAM_THRESHOLD, ham_cutoff=HAM_THRESHOLD, debugheader=DEBUGHEADER, debug=DODEBUG): """Score (judge) a message and add a disposition header.
else: newbody.append(line)
newbody.append(line)
def deSA(msg): if msg['X-Spam-Status']: if msg['X-Spam-Status'].startswith('Yes'): pct = msg['X-Spam-Prev-Content-Type'] if pct: msg['Content-Type'] = pct pcte = msg['X-Spam-Prev-Content-Transfer-Encoding'] if pcte: msg['Content-Transfer-Encoding'] = pcte subj = re.sub(r'\*\*\*\*\*SPAM\*\*\*\*\* ', '', msg['Subject']...
print msg
gen(msg, unixfrom=1)
def process_mailbox(f, dosa=1, pats=None): for msg in mailbox.PortableUnixMailbox(f, Parser().parse): if pats is not None: unheader(msg, pats) if dosa: deSA(msg) print msg
sys.stdout.write(data)
if not null: sys.stdout.write(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...
opts, args = getopt.getopt(sys.argv[1:], 'htcvei:d:D:')
opts, args = getopt.getopt(sys.argv[1:], 'htcvl:e:i:d:D:')
def Logout(self, expunge): # sign off if expunge: imap.expunge() imap.logout()
doExpunge = not doExpunge
if arg == 'y': doExpunge = True else: doExpunge = False
def Logout(self, expunge): # sign off if expunge: imap.expunge() imap.logout()
if doTrain: imap_filter.Train() if doClassify: imap_filter.Filter()
print sleepTime while 1: if doTrain: if options.verbose: print "Training" imap_filter.Train() if doClassify: if options.verbose: print "Classifying" imap_filter.Filter() if sleepTime: time.sleep(sleepTime) else: break
def Logout(self, expunge): # sign off if expunge: imap.expunge() imap.logout()
if action.startswith("no"):
if action.startswith("un"):
def filter_message(msg, mgr, all_actions=True): config = mgr.config.filter prob = mgr.score(msg) 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 = "unsure" else: disposition = "No" attr_p...
fp = open(pn, 'rb')
fp = gzip.open(pn, 'rb')
def load(self): '''Read the Message substance from the file'''
self.setSubstance(fp.read()) fp.close()
try: self.setSubstance(fp.read()) except IOError, e: if str(e) == 'Not a gzipped file': fp.close() try: fp = open(self.pathname(), 'rb') except IOError, e: if e.errno != errno.ENOENT: raise else: self.setSubstance(fp.read()) fp.close() else: fp.close()
def load(self): '''Read the Message substance from the file'''
def load(self): '''Read the Message substance from the file''' if options["globals", "verbose"]: print 'loading', self.file_name pn = self.pathname() try: fp = gzip.open(pn, 'rb') except IOError, e: if e.errno != errno.ENOENT: raise else: self.setSubstance(fp.read()) fp.close()
def create(self, key, directory): '''Create a message object from a filename in a directory'''
except ItemError:
except KeyError:
def get(self, var_path): """Get value""" obj = self._data for var in var_path.split('.'): try: obj = obj[var] except ItemError: raise NoConfigVariable return obj
except ItemError:
except KeyError:
def set(self, var_path, value): """Set value""" obj = self._data vars = var_path.split('.') for var in vars[:-1]: try: obj = obj[var] except ItemError: raise NoConfigVariable obj[vars[-1]] = value
except ItemError:
except KeyError:
def create(self, var_path, default=''): """Create the variable with hierarchy Suppose, if var_path = 'a.b.c' and only 'a' exists, both 'b' and 'c' will be created in hierarchy Return new node's value """ obj = self._data vars = var_path.split('.') for var in vars[:-1]: try: obj = obj[var] except ItemError: obj[var] =...
self.pwmfile=open(path.format(*pins[number])) def setwidth(self,width):
if not os.path.exists(pwmpath.format(*pins[number])): os.system('echo MULTC > /sys/devices/bone_capemgr.8/slots') self.pwmfile=open(pwmpath.format(*pins[number])) def set_width(self,width):
def __init__(self,number): self.pwmfile=open(path.format(*pins[number]))
sys.stdout.write(' -c <file> XML configuration file\n')
def usage(): pgm_nme = os.path.basename(sys.argv[0]) sys.stdout.write('%s %s (%s)\n' % (pgm_nme, __version__, __date__)) sys.stdout.write('usage: %s [options] source_file\n' % (pgm_nme)) sys.stdout.write('\noptions:\n') sys.stdout.write(' -c <file> XML configuration file\n') sys.stdout.write(' -l <file> Output log\...
elif cur_name == 'comp': comp = []
elif cur_name == 'ele': while reader.MoveToNextAttribute(): if reader.Name() == 'id': ele_id = reader.Value() elif cur_name == 'subele': while reader.MoveToNextAttribute(): if reader.Name() == 'id': subele_id = reader.Value()
def convert(filename, fd_out): global logger try: reader = libxml2.newTextReaderFilename(filename) ret = reader.Read() found_text = False while ret == 1: tmpNodeType = reader.NodeType() #print tmpNodeType, reader.Name(), reader.Value() if tmpNodeType == NodeType['element_start']: found_text = False cur_name = reader.Na...
if cur_name in ('ele', 'subele'): seg_data.append(reader.Value().replace('\n', ''))
if cur_name == 'ele': seg_data.set(ele_id, reader.Value().replace('\n', '')) found_text = True elif cur_name == 'subele': seg_data.set(subele_id, reader.Value().replace('\n', ''))
def convert(filename, fd_out): global logger try: reader = libxml2.newTextReaderFilename(filename) ret = reader.Read() found_text = False while ret == 1: tmpNodeType = reader.NodeType() #print tmpNodeType, reader.Name(), reader.Value() if tmpNodeType == NodeType['element_start']: found_text = False cur_name = reader.Na...
seg_data.append(reader.Value())
seg_data.set(ele_id, reader.Value())
def convert(filename, fd_out): global logger try: reader = libxml2.newTextReaderFilename(filename) ret = reader.Read() found_text = False while ret == 1: tmpNodeType = reader.NodeType() #print tmpNodeType, reader.Name(), reader.Value() if tmpNodeType == NodeType['element_start']: found_text = False cur_name = reader.Na...
comp.append(reader.Value())
seg_data.set(subele_id, reader.Value())
def convert(filename, fd_out): global logger try: reader = libxml2.newTextReaderFilename(filename) ret = reader.Read() found_text = False while ret == 1: tmpNodeType = reader.NodeType() #print tmpNodeType, reader.Name(), reader.Value() if tmpNodeType == NodeType['element_start']: found_text = False cur_name = reader.Na...
elif cur_name == 'ele' and not found_text: seg_data.append('')
elif cur_name == 'ele': if not found_text: seg_data.set(ele_id, '') found_text = True ele_id = None elif cur_name == 'subele' and not found_text: seg_data.set(subele_id, '')
def convert(filename, fd_out): global logger try: reader = libxml2.newTextReaderFilename(filename) ret = reader.Read() found_text = False while ret == 1: tmpNodeType = reader.NodeType() #print tmpNodeType, reader.Name(), reader.Value() if tmpNodeType == NodeType['element_start']: found_text = False cur_name = reader.Na...
elif cur_name == 'subele' and not found_text: comp.append('') found_text = True
subele_id = None
def convert(filename, fd_out): global logger try: reader = libxml2.newTextReaderFilename(filename) ret = reader.Read() found_text = False while ret == 1: tmpNodeType = reader.NodeType() #print tmpNodeType, reader.Name(), reader.Value() if tmpNodeType == NodeType['element_start']: found_text = False cur_name = reader.Na...