rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
self.total_control_ticks = 100 | self.total_control_ticks = 40 | def __init__(self): # dont use dlg self.hprogress = self.hdlg = 0 self.dlg = None self.stopping = False self.total_control_ticks = 100 self.current_stage = 0 self.set_stages( (("", 1.0),) ) |
p.set_max_ticks(1000) for i in range(1000): p.tick() | p.set_max_ticks(20) for i in range(20): p.tick() print "Second stage test" p = HackProgress() stages = ("Stage 1", 0.9), ("Stage 2", 0.1) p.set_stages(stages) p.set_max_ticks(10) for i in range(7): p.tick() p.set_max_ticks(2) for i in range(2): p.tick() print "Third stage test" p = HackProgress() stages = ("Stage 1", 0... | def __init__(self): # dont use dlg self.hprogress = self.hdlg = 0 self.dlg = None self.stopping = False self.total_control_ticks = 100 self.current_stage = 0 self.set_stages( (("", 1.0),) ) |
o port: The TCP/IP port to listen on | o port: The TCP/IP (address, port) to listen on. Usually '' - meaning bind to all IP addresses that the machine has - will be passed as the address. If `port` is just an int, an address of '' will be assumed. | def __init__(self, port, factory, factoryArgs, socketMap=_defaultContext._map): """Creates a listener object, which will listen for incoming connections when Dibbler.run is called: |
self.bind(('', port)) | if type(port) != type(()): port = ('', port) self.bind(port) | def __init__(self, port, factory, factoryArgs, socketMap=_defaultContext._map): """Creates a listener object, which will listen for incoming connections when Dibbler.run is called: |
`port` specifies the TCP/IP port on which to run, defaulting to port 80. | `port` specifies the TCP/IP (address, port) on which to run, defaulting to ('', 80). | def handle_accept(self): """Asyncore override.""" # If an incoming connection is instantly reset, eg. by following a # link in the web interface then instantly following another one or # hitting stop, handle_accept() will be triggered but accept() will # return None. result = self.accept() if result: clientSocket, clie... |
def __init__(self, port=80, context=_defaultContext): | def __init__(self, port=('', 80), context=_defaultContext): | def __init__(self, port=80, context=_defaultContext): """Create an `HTTPServer` for the given port.""" Listener.__init__(self, port, _HTTPHandler, (self, context), context._map) self._plugins = [] context._HTTPPort = port |
context._HTTPPort = port | try: context._HTTPPort = port[1] except TypeError: context._HTTPPort = port | def __init__(self, port=80, context=_defaultContext): """Create an `HTTPServer` for the given port.""" Listener.__init__(self, port, _HTTPHandler, (self, context), context._map) self._plugins = [] context._HTTPPort = port |
self.pushError(400, "Malformed request: '%s'" % requestLine) | self.writeError(400, "Malformed request: '%s'" % requestLine) | def found_terminator(self): """Asynchat override.""" # Parse the HTTP request. requestLine, headers = (self._request+'\r\n').split('\r\n', 1) try: method, url, version = requestLine.strip().split() except ValueError: self.pushError(400, "Malformed request: '%s'" % requestLine) self.close_when_done() return |
def import_core_spambayes_stuff(ini_filename): | def import_core_spambayes_stuff(ini_filenames): global bayes_classifier, bayes_tokenize, bayes_storage | def import_core_spambayes_stuff(ini_filename): if "spambayes.Options" in sys.modules: # Manager probably being re-initialized (via the Outlook 'addin' GUI # Check that nothing has changed underneath us. if __debug__: import spambayes.Options assert spambayes.Options.optionsPathname == \ ini_filename.encode(filesystem_e... |
if __debug__: import spambayes.Options assert spambayes.Options.optionsPathname == \ ini_filename.encode(filesystem_encoding), \ "'spambayes.Options' was imported too early, with the " \ "incorrect directory %r" \ % (spambayes.Options.optionsPathname,) | assert hasattr(sys, "frozen") | def import_core_spambayes_stuff(ini_filename): if "spambayes.Options" in sys.modules: # Manager probably being re-initialized (via the Outlook 'addin' GUI # Check that nothing has changed underneath us. if __debug__: import spambayes.Options assert spambayes.Options.optionsPathname == \ ini_filename.encode(filesystem_e... |
global bayes_classifier, bayes_tokenize, bayes_storage os.environ["BAYESCUSTOMIZE"] = ini_filename.encode(filesystem_encoding) | use_names = [] for name in ini_filenames: if isinstance(name, unicode): name = name.encode(filesystem_encoding) use_names.append(name) os.environ["BAYESCUSTOMIZE"] = os.pathsep.join(use_names) | def import_core_spambayes_stuff(ini_filename): if "spambayes.Options" in sys.modules: # Manager probably being re-initialized (via the Outlook 'addin' GUI # Check that nothing has changed underneath us. if __debug__: import spambayes.Options assert spambayes.Options.optionsPathname == \ ini_filename.encode(filesystem_e... |
bayes_options_filename = os.path.join(self.data_directory, "default_bayes_customize.ini") import_core_spambayes_stuff(bayes_options_filename) | bayes_option_filenames = [] for look_dir in [self.application_directory, self.data_directory]: look_file = os.path.join(look_dir, "default_bayes_customize.ini") if os.path.isfile(look_file): bayes_option_filenames.append(look_file) import_core_spambayes_stuff(bayes_option_filenames) | def __init__(self, config_base="default", outlook=None, verbose=0): self.never_configured = True self.reported_error_map = {} self.reported_startup_error = False self.config = self.options = None self.addin = None self.verbose = verbose self.outlook = outlook self.dialog_parser = None self.test_suite_running = False |
self._MigrateFile("default_bayes_customize.ini", False) | def MigrateDataDirectory(self): # A bit of a nod to save people doing a full retrain. # Try and locate our files in the old location, and move # them to the new one. # Also used first time SpamBayes is run - this will cause # the ini file to be *copied* to the correct directory self._MigrateFile("default_bayes_customiz... | |
def _MigrateFile(self, filename, do_move = True): | def _MigrateFile(self, filename): | 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): # shutil in 2.2 and earlier don't contain 'move'. # Win95 and Win98 don't support MoveFileEx. shutil.copyfile... |
if do_move: os.remove(src) | 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): # shutil in 2.2 and earlier don't contain 'move'. # Win95 and Win98 don't support MoveFileEx. shutil.copyfile... |
if type(options.valid_input(sect, opt)) in types.StringTypes: | if isinstance(valid_input, types.StringTypes): | def _buildConfigPageBody(self, html, parm_map): configTable = None section = None |
for val in options.valid_input(sect, opt): | for val in valid_input: | def _buildConfigPageBody(self, html, parm_map): configTable = None section = None |
if type(options.valid_input(sect, opt)) == type((0,1)): | if isinstance(valid_input, types.TupleType): | def verifyInput(self, parms, pmap): '''Check that the given input is valid.''' # Most of the work here is done by the options class, but # we may have a few extra checks that are beyond its capabilities errmsg = '' |
for valid in options.valid_input(sect, opt): | for valid in valid_input: | def verifyInput(self, parms, pmap): '''Check that the given input is valid.''' # Most of the work here is done by the options class, but # we may have a few extra checks that are beyond its capabilities errmsg = '' |
url) | "../docs/outlook", url) if not os.path.isfile(fname): fname = os.path.join(os.path.dirname(sys.argv[0]), url) | def ShowHtml(self,url): """Displays the main SpamBayes documentation in your Web browser""" import sys, os, urllib if urllib.splittype(url)[0] is None: # just a file spec if hasattr(sys, "frozen"): # Same directory as to the executable. fname = os.path.join(os.path.dirname(sys.argv[0]), url) else: # (ie, main Outlook20... |
files = [t[-1] for t in files] | def distribute(dir): files = glob.glob(os.path.join(dir, "*", "*")) # Sort by time received, earliest first. The base names must be such # that sorting by basename accomplishes this; that's true if # sort+group.py was run first. files = [(os.path.basename(f), f) for f in files] files.sort() files = [t[-1] for t in fil... | |
for f in files: newgroup = (f.split('-'))[0] | for basename, f in files: newgroup = basename.split('-')[0] | def distribute(dir): files = glob.glob(os.path.join(dir, "*", "*")) # Sort by time received, earliest first. The base names must be such # that sorting by basename accomplishes this; that's true if # sort+group.py was run first. files = [(os.path.basename(f), f) for f in files] files.sort() files = [t[-1] for t in fil... |
newname = os.path.join(dir, "reservoir", os.path.basename(f)) | newname = os.path.join(dir, "reservoir", basename) | def distribute(dir): files = glob.glob(os.path.join(dir, "*", "*")) # Sort by time received, earliest first. The base names must be such # that sorting by basename accomplishes this; that's true if # sort+group.py was run first. files = [(os.path.basename(f), f) for f in files] files.sort() files = [t[-1] for t in fil... |
newname = os.path.join(dir, "Set%d" % cset, os.path.basename(f)) | newname = os.path.join(dir, "Set%d" % cset, basename) | def distribute(dir): files = glob.glob(os.path.join(dir, "*", "*")) # Sort by time received, earliest first. The base names must be such # that sorting by basename accomplishes this; that's true if # sort+group.py was run first. files = [(os.path.basename(f), f) for f in files] files.sort() files = [t[-1] for t in fil... |
print "after ensure object" print type(prop), prop, type(0) | def SetField(self, prop, val): self._EnsureObject() print "after ensure object" print type(prop), prop, type(0) if type(prop)!=type(0): props = ( (mapi.PS_PUBLIC_STRINGS, prop), ) propIds = self.mapi_object.GetIDsFromNames(props, mapi.MAPI_CREATE) type_tag = _MapiTypeMap.get(type(val)) if type_tag is None: raise ValueE... | |
self.manager.classifier_data.message_db.store_msg(msg) | self.manager.classifier_data.message_db.store_msg(msgstore_message) | def OnClick(self, button, cancel): msgstore = self.manager.message_store msgstore_messages = self.explorer.GetSelectedMessages(True) if not msgstore_messages: return # If we are not yet enabled, tell the user. # (This is better than disabling the button as a) the user may not # understand why it is disabled, and b) as ... |
elif start_delay > 30 or interval > 30: | elif start_delay > 60 or interval > 60: | def Init(self, *args): _BaseItemsEvent.Init(self, *args) timer_enabled = self.manager.config.filter.timer_enabled start_delay = self.manager.config.filter.timer_start_delay interval = self.manager.config.filter.timer_interval use_timer = timer_enabled and start_delay and interval if timer_enabled and not use_timer: pri... |
original_score = msgstore_message.GetField(mgr.config.general.field_score_name) | original_score = 100 * msgstore_message.GetField(\ mgr.config.general.field_score_name) | 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... |
"as %s (it scored %d%%)." % (original_class, original_score*100)) | "as %s (it scored %d%%)." % (original_class, original_score)) | 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... |
return self._force_CRLF(email.Message.Message.as_string(self, unixfrom)) | try: return self._force_CRLF(\ email.Message.Message.as_string(self, unixfrom)) except TypeError: parts = [] for part in self.get_payload(): parts.append(email.Message.Message.as_string(part, unixfrom)) return self._force_CRLF("\n".join(parts)) | def as_string(self, unixfrom=False): # The email package stores line endings in the "internal" Python # format ('\n'). It is up to whoever transmits that information to # convert to appropriate line endings (according to RFC822, that is # \r\n *only*). imaplib *should* take care of this for us (in the # append functi... |
butcher_pos = text.lower().find("\ncontent-type: ") if butcher_pos < 0: raise RuntimeError( "email package croaked with boundary error, but " "there appears to be no 'Content-Type' header") butchered = text[:butcher_pos] + "\nSpamBayes-" + \ text[butcher_pos+1:] + "\n\n" msg = email.message_from_string(butchered) | msg = None except email.Errors.HeaderParseError: msg = None if msg is None: butcher_pos = text.lower().find("\ncontent-type: ") if butcher_pos < 0: raise RuntimeError( "email package croaked with a MIME related error, but " "there appears to be no 'Content-Type' header") butchered = text[:butcher_pos] + "\nSpa... | def GetEmailPackageObject(self, strip_mime_headers=True): # Return an email.Message object. # # strip_mime_headers is a hack, and should be left True unless you're # trying to display all the headers for diagnostic purposes. If we # figure out something better to do, it should go away entirely. # # Problem #1: suppos... |
This is just like classifier.Bayes, except that the dictionary is a database. You take less disk this way, I think, and you can pretend it's persistent. It's much slower training, but much faster checking, and takes less memory all around. On destruction, an instantiation of this class will write it's state | This is just like classifier.Bayes, except that the dictionary is a database. You take less disk this way and you can pretend it's persistent. The tradeoffs vs. a pickle are: 1. it's slower training, but faster checking, and 2. it needs less memory to run, but takes more space on the hard drive. On destruction, an i... | def itervalues(self): return self.__iter__(lambda k: k[1]) |
<td class='reviewheaders' nowrap><b> <a href='javascript: onHeader("%s", "Discard");'>Discard</a> / <a href='javascript: onHeader("%s", "Defer");'>Defer</a> / <a href='javascript: onHeader("%s", "Ham");'>Ham</a> / <a href='javascript: onHeader("%s", "Spam");'>Spam</a> </b></td></tr>""" | <td class='reviewheaders'><a href='javascript: onHeader("%s", "Discard");'>Discard</a></td> <td class='reviewheaders'><a href='javascript: onHeader("%s", "Defer");'>Defer</a></td> <td class='reviewheaders'><a href='javascript: onHeader("%s", "Ham");'>Ham</a></td> <td class='reviewheaders'><a href='javascript: onHeader(... | def __init__(self, uiPort, socketMap=asyncore.socket_map): Listener.__init__(self, uiPort, UserInterface, (), socketMap=socketMap) print 'User interface url is http://localhost:%d' % (uiPort) |
def appendMessages(self, lines, keyedMessages, label): | def appendMessages(self, lines, keyedMessages, label, startAt, howMany): | def appendMessages(self, lines, keyedMessages, label): """Appends the lines of a table of messages to 'lines'.""" buttons = \ """<input type='radio' name='classify:%s:%s' value='discard'> <input type='radio' name='classify:%s:%s' value='defer' %s> <input type='radio' name='classify:%s:%s' value='ham' %s>&nb... |
if label == 'Spam': | if buttonLabel == 'Spam': | def appendMessages(self, lines, keyedMessages, label): """Appends the lines of a table of messages to 'lines'.""" buttons = \ """<input type='radio' name='classify:%s:%s' value='discard'> <input type='radio' name='classify:%s:%s' value='defer' %s> <input type='radio' name='classify:%s:%s' value='ham' %s>&nb... |
elif label == 'Ham': | elif buttonLabel == 'Ham': | def appendMessages(self, lines, keyedMessages, label): """Appends the lines of a table of messages to 'lines'.""" buttons = \ """<input type='radio' name='classify:%s:%s' value='discard'> <input type='radio' name='classify:%s:%s' value='defer' %s> <input type='radio' name='classify:%s:%s' value='ham' %s>&nb... |
elif label == 'Unsure': | elif buttonLabel == 'Unsure': | def appendMessages(self, lines, keyedMessages, label): """Appends the lines of a table of messages to 'lines'.""" buttons = \ """<input type='radio' name='classify:%s:%s' value='discard'> <input type='radio' name='classify:%s:%s' value='defer' %s> <input type='radio' name='classify:%s:%s' value='ham' %s>&nb... |
subject = "<span title=\"%s\">%s</span>" % (text, subject) radioGroup = buttons % (label, key, label, key, defer, label, key, ham, label, key, spam) | subject = ('<span title="%s">' '<a target=_top href="/view?key=%s&corpus=%s">' '%s' '</a>' '</span>') % (text, key, label, subject) radioGroup = buttons % (buttonLabel, key, buttonLabel, key, defer, buttonLabel, key, ham, buttonLabel, key, spam) | def appendMessages(self, lines, keyedMessages, label): """Appends the lines of a table of messages to 'lines'.""" buttons = \ """<input type='radio' name='classify:%s:%s' value='discard'> <input type='radio' name='classify:%s:%s' value='defer' %s> <input type='radio' name='classify:%s:%s' value='ham' %s>&nb... |
<td align='center'>%s</td></tr>""" % \ | %s</tr>""" % \ | def appendMessages(self, lines, keyedMessages, label): """Appends the lines of a table of messages to 'lines'.""" buttons = \ """<input type='radio' name='classify:%s:%s' value='discard'> <input type='radio' name='classify:%s:%s' value='defer' %s> <input type='radio' name='classify:%s:%s' value='ham' %s>&nb... |
if key.startswith('classify:'): | if key == 'startAt': startAt = int(value) elif key == 'howMany': howMany = int(value) elif key.startswith('classify:'): | def onReview(self, params): """Present a list of message for (re)training.""" # Train/discard submitted messages. id = '' numTrained = 0 numDeferred = 0 for key, value in params.items(): if key.startswith('classify:'): id = key.split(':')[2] if value == 'spam': targetCorpus = state.spamCorpus elif value == 'ham': targe... |
self.reviewHeader % (prior, next, priorState, nextState)] | self.reviewHeader % (prior, next, startAt+howMany, howMany, priorState, nextState)] | def onReview(self, params): """Present a list of message for (re)training.""" # Train/discard submitted messages. id = '' numTrained = 0 numDeferred = 0 for key, value in params.items(): if key.startswith('classify:'): id = key.split(':')[2] if value == 'spam': targetCorpus = state.spamCorpus elif value == 'ham': targe... |
lines.append("<tr><td> </td><td></td><td></td></tr>") | lines.append("<tr><td> </td><td></td></tr>") | def onReview(self, params): """Present a list of message for (re)training.""" # Train/discard submitted messages. id = '' numTrained = 0 numDeferred = 0 for key, value in params.items(): if key.startswith('classify:'): id = key.split(':')[2] if value == 'spam': targetCorpus = state.spamCorpus elif value == 'ham': targe... |
self.appendMessages(lines, keyedMessages[header], label) lines.append("""<tr><td></td><td></td><td align='center'> <br> | self.appendMessages(lines, keyedMessages[header], label, startAt, howMany) lines.append("""<tr><td></td><td></td><td align='center' colspan='4'> <br> | def onReview(self, params): """Present a list of message for (re)training.""" # Train/discard submitted messages. id = '' numTrained = 0 numDeferred = 0 for key, value in params.items(): if key.startswith('classify:'): id = key.split(':')[2] if value == 'spam': targetCorpus = state.spamCorpus elif value == 'ham': targe... |
self.isTest = False | 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... | |
if not self.isTest: def ensureDir(dirname): try: os.mkdir(dirname) except OSError, e: if e.errno != errno.EEXIST: raise map(ensureDir, [self.spamCache, self.hamCache, self.unknownCache]) if self.gzipCache: factory = GzipFileMessageFactory() else: factory = FileMessageFactory() age = options.pop3proxy_cache_expiry_day... | def ensureDir(dirname): try: os.mkdir(dirname) except OSError, e: if e.errno != errno.EEXIST: raise map(ensureDir, [self.spamCache, self.hamCache, self.unknownCache]) if self.gzipCache: factory = GzipFileMessageFactory() else: factory = FileMessageFactory() age = options.pop3proxy_cache_expiry_days*24*60*60 self.spam... | 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...", self.bayes = storage.DBDictClassifier(self.databaseFilename) print "Done." |
spam1 = """From: friend@public.com Subject: Make money fast Hello tim_chandler , Want to save money ? Now is a good time to consider refinancing. Rates are low so you can cut your current payments and save money. http://64.251.22.101/interest/index%38%30%300%2E%68t%6D Take off list on site [s5] """ good1 = """From:... | def main(uiPort, launchUI): """Runs the proxy forever or until a 'KILL' command is received or someone hits Ctrl+Break.""" UserInterfaceListener(uiPort) if launchUI: webbrowser.open_new("http://localhost:%d/" % uiPort) asyncore.loop() | |
sys.setrecursionlimit(100) | 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() for opt, arg in opts: if opt == '-h': print >>sys.stderr, __doc__ sys.exit() elif opt == '-b': state.launchUI = True elif opt == '-d': state... | |
self.warning = "%s\nWarning: you have much more %s than %s - " \ | self.warning = "Warning: you have much more %s than %s - " \ | 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 = True options["Storage", "persistent_storage_file"] = \ '_pop3proxy_... |
"numbers of ham and spam." % (db_status, big, small) | "numbers of ham and spam." % (big, small) | 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 = True options["Storage", "persistent_storage_file"] = \ '_pop3proxy_... |
for file in file_list: self.merge_file(file) | for f in file_list: self.merge_file(f) | def merge_files(self, file_list): for file in file_list: self.merge_file(file) |
option = 'x-'+option | l_option = 'x-' + option u_option = 'X-' + option | 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)): if option.startswith('x-'): # try setting option without the X-... |
if self._options.has_key((section, option)): self.convert_and_set(section, option, value) print >> sys.stderr, ( "warning: option %s in" " section %s is deprecated" % (opt, sect)) | if self._options.has_key((section, l_option)): self.convert_and_set(section, l_option, value) self._report_deprecated_error(section, option) elif self._options.has_key((section, u_option)): self.convert_and_set(section, u_option, value) self._report_deprecated_error(section, option) | 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)): if option.startswith('x-'): # try setting option without the X-... |
def train_message(msg, is_spam, mgr): | def train_message(msg, is_spam, mgr, update_probs = True): | def train_message(msg, is_spam, mgr): # 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. from tokenizer import tokenize stream = msg.GetEmailPackageObject() tok... |
if train_message(message, isspam, mgr): | if train_message(message, isspam, mgr, False): | def train_folder( f, isspam, mgr, progress): num = num_added = 0 for message in f.GetMessageGenerator(): if progress.stop_requested(): break progress.tick() try: if train_message(message, isspam, mgr): num_added += 1 except: print "Error training message '%s'" % (message,) traceback.print_exc() num += 1 print "Checked"... |
if value is None or value == "": | if value is None: | def is_valid_multiple(self, value): |
if tv == type(Set()): return True | def is_valid_multiple(self, value): | |
current_pos = m.end() | current_pos += m.end() | def configure_mozilla(config_location): """Configure Mozilla to use the SpamBayes POP3 and SMTP proxies, and configure SpamBayes to proxy the servers that Mozilla was connecting to.""" prefs_file = file("%s%sprefs.js" % (config_location, os.sep), "r") prefs = prefs_file.read() prefs_file.close() save_prefs = prefs pop_... |
port_string = 'user_pref("mail.smtpserver.smtp1.port", ' | port_string = 'user_pref("mail.smtpserver.smtp%d.port", ' \ % (server_num,) | def configure_mozilla(config_location): """Configure Mozilla to use the SpamBayes POP3 and SMTP proxies, and configure SpamBayes to proxy the servers that Mozilla was connecting to.""" prefs_file = file("%s%sprefs.js" % (config_location, os.sep), "r") prefs = prefs_file.read() prefs_file.close() save_prefs = prefs pop_... |
spam_folder_url = "mailbox:////%s//Junk%20Mail" % (store_name,) unsure_folder_url = "mailbox:////%s//Possible%20Junk" % (store_name,) | spam_folder_url = "mailbox:////%s//Junk%%20Mail" % (store_name,) unsure_folder_url = "mailbox:////%s//Possible%%20Junk" % (store_name,) | def configure_mozilla(config_location): """Configure Mozilla to use the SpamBayes POP3 and SMTP proxies, and configure SpamBayes to proxy the servers that Mozilla was connecting to.""" prefs_file = file("%s%sprefs.js" % (config_location, os.sep), "r") prefs = prefs_file.read() prefs_file.close() save_prefs = prefs pop_... |
server = "%s:%s" % (account[server_key][0], account[port_key][0]) | def configure_outlook_express(unused): """Configure OE to use the SpamBayes POP3 and SMTP proxies, and configure SpamBayes to proxy the servers that OE was connecting to.""" # Requires win32all to be available (or for someone to write a # Mac version <wink>) if win32api is None: raise ImportError("win32 extensions requ... | |
tfn = os.path.join(path, "tmp", | tfn = os.path.join(path, os.path.normpath(os.path.join("..", "tmp")), | 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.jo... |
open_storage(db_name, True) | open_storage(db_name, "dbm") | def testNoDBMAvailable(self): import tempfile from spambayes.storage import open_storage |
_login_splitter = re.compile('([a-zA-Z])+=(".*?"|.*?),?') | _login_splitter = re.compile('([a-zA-Z]+)=(".*?"|.*?),?') | def getCancelMessage(self): """Override: Specify the cancel message for an HTTP Authentication.""" return "You must log in." |
text = text.replace(' ', ' ') text = re.sub(r'(\s)\s+', r'\1', text) text = text.strip() | if type(text) == type([]): text = "(this message is a digest of %s messages)" % (len(text)) else: text = text.replace(' ', ' ') text = re.sub(r'(\s)\s+', r'\1', text) text = text.strip() | def _makeMessageInfo(self, message): """Given an email.Message, return an object with subjectHeader, fromHeader and bodySummary attributes. These objects are passed into appendMessages by onReview - passing email.Message objects directly uses too much memory.""" subjectHeader = message["Subject"] or "(none)" fromHeade... |
def splitTo(self, address): """Return 'address' as undressed (host, fulladdress) tuple. Handy for use with TO: addresses.""" start = string.index(address, '<') + 1 sep = string.index(address, '@') + 1 end = string.index(address, '>') return (address[sep:end], address[start:end],) | def splitTo(self, address): """Return 'address' as undressed (host, fulladdress) tuple. Handy for use with TO: addresses.""" start = string.index(address, '<') + 1 sep = string.index(address, '@') + 1 end = string.index(address, '>') return (address[sep:end], address[start:end],) | |
toHost, toFull = self.splitTo(args[0]) | toFull = self.stripAddress(args[0]) | def onRcptTo(self, command, args): toHost, toFull = self.splitTo(args[0]) if toFull == options["smtpproxy", "spam_address"]: self.train_as_spam = True self.train_as_ham = False self.blockData = True self.push("250 OK\r\n") return None elif toFull == options["smtpproxy", "ham_address"]: self.train_as_ham = True self.tra... |
item = parent.Controls.Add(Type=control_type, Temporary=False) | item = parent.Controls.Add(Type=control_type, Temporary=temporary) | def _AddControl(self, parent, # who the control is added to control_type, # type of control to add. events_class, events_init_args, # class/Init() args **item_attrs): # extra control attributes. # Outlook Toolbars suck :) # We have tried a number of options: temp/perm in the standard toolbar, # Always creating our own ... |
flags = re.sub(r"\\Recent ?|\\ ?Recent", "", flags) | flags = re.sub(r"\\Recent ?| ?\\Recent", "", flags) | 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... |
raise BadIMAPReponseError(command) | raise BadIMAPResponseError(command) | def Save(self): """Save message to IMAP server. |
classifier.unlearn(msg.asTokens(), not isSpam) | classifier.unlearn(msg.tokenize(), not isSpam) | def Train(self, classifier, isSpam): """Train folder as spam/ham.""" num_trained = 0 for msg in self: if msg.GetTrained() == (not isSpam): msg = msg.get_full_message() if msg.could_not_retrieve: # Something went wrong, and we couldn't even get # an invalid message, so just skip this one. # Annoyingly, we'll try to do i... |
classifier.learn(msg.asTokens(), isSpam) | classifier.learn(msg.tokenize(), isSpam) | def Train(self, classifier, isSpam): """Train folder as spam/ham.""" num_trained = 0 for msg in self: if msg.GetTrained() == (not isSpam): msg = msg.get_full_message() if msg.could_not_retrieve: # Something went wrong, and we couldn't even get # an invalid message, so just skip this one. # Annoyingly, we'll try to do i... |
(prob, clues) = classifier.spamprob(msg.asTokens(), | (prob, clues) = classifier.spamprob(msg.tokenize(), | def Filter(self, classifier, spamfolder, unsurefolder, hamfolder): count = {} count["ham"] = 0 count["spam"] = 0 count["unsure"] = 0 for msg in self: if msg.GetClassification() is None: msg = msg.get_full_message() if msg.could_not_retrieve: # Something went wrong, and we couldn't even get # an invalid message, so just... |
msg = message_from_string(data) | msg = sbheadermessage_from_string(data) | def extractSpambayesID(self, data): msg = message_from_string(data) |
assert re.search(r"(?s)<html>.*Spambayes proxy.*</html>", response) | assert re.search(r"(?s)<html>.*SpamBayes proxy.*</html>", response) | def runUIAndProxy(): httpServer = UserInterfaceServer(8881) proxyUI = ProxyUserInterface(state, _recreateState) httpServer.register(proxyUI) BayesProxyListener('localhost', 8110, ('', 8111)) state.bayes.learn(tokenizer.tokenize(spam1), True) state.bayes.learn(tokenizer.tokenize(good1), False) proxyReady.set() Dibbler.r... |
usage(2, "Must specify one of -d or -D") | usedb = options["Storage", "persistent_use_database"] pck = get_pathname_option("Storage", "persistent_storage_file") | def main(): """Main program; parse options and go.""" global loud try: opts, args = getopt.getopt(sys.argv[1:], 'hfqnrd:D:g:s:o:') except getopt.error, msg: usage(2, msg) if not opts: usage(2, "No options given") pck = None usedb = None force = False trainnew = False removetrained = False good = [] spam = [] for op... |
msg = spambayes.message.SBHeaderMessage() msg.setPayload(messageText) msg.setId(state.getNewMessageName()) (prob, clues) = state.bayes.spamprob(msg.asTokens(),\ evidence=True) msg.addSBHeaders(prob, clues) if command == 'RETR': cls = msg.GetClassification() if cls == options["Hammie", "header_ham_string"]: state.num... | try: msg = spambayes.message.SBHeaderMessage() msg.setPayload(messageText) msg.setId(state.getNewMessageName()) (prob, clues) = state.bayes.spamprob(msg.asTokens(),\ evidence=True) msg.addSBHeaders(prob, clues) if command == 'RETR': cls = msg.GetClassification() if cls == options["Hammie", "header_ham_string"]: stat... | 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): # Break off the first line, which will b... |
disp += ("; %."+str(options["Headers", "header_score_digits"])+"f") % prob | disp += "; %.*f" % (options["Headers", "header_score_digits"], prob) | def filter(self, msg, header=None, spam_cutoff=None, ham_cutoff=None, debugheader=None, debug=None, train=None): """Score (judge) a message and add a disposition header. |
self.wordinfo = dict([(k, self._WordInfoFactory(v)) \ | self.wordinfo = dict([(self.uunquote(k), self._WordInfoFactory(v)) \ | def load(self): if os.path.exists(self.db_name): db = open(self.db_name, "rb") data = dict(cdb.Cdb(db)) db.close() self.nham, self.nspam = [int(i) for i in \ data[self.statekey].split(',')] self.wordinfo = dict([(k, self._WordInfoFactory(v)) \ for k, v in data.iteritems() \ if k != self.statekey]) if options["globals",... |
disp = str(prob) | disp = ("%."+str(options["Headers", "header_score_digits"])+"f") % prob | def addSBHeaders(self, prob, clues): """Add hammie header, and remember message's classification. Also, add optional headers if needed.""" |
if prob >= self.spam_cutoff: self.push('503 Error: probable spam') self.log_message(data) return | t3 = time.time() try: if prob >= self.spam_cutoff: self.log_message(data) print >> smtpd.DEBUGSTREAM, 'probable spam: %.2f' % prob return '503 Error: probable spam' | def process_message(self, peer, mailfrom, rcpttos, data): try: msg = email.Parser.Parser().parsestr(data) except: pass else: msg.add_header("X-Peer", peer[0]) prob, data = self.h.score_and_filter(msg) if prob >= self.spam_cutoff: self.push('503 Error: probable spam') self.log_message(data) return |
refused = self._deliver(mailfrom, rcpttos, data) print >> smtpd.DEBUGSTREAM, 'we got some refusals:', refused | refused = self._deliver(mailfrom, rcpttos, data) t4 = time.time() print >> smtpd.DEBUGSTREAM, 'we got some refusals:', refused print >> smtpd.DEBUGSTREAM, 'deliver time:', t4-t3 finally: print >> smtpd.DEBUGSTREAM, 'parse time:', t2-t1 print >> smtpd.DEBUGSTREAM, 'score time:', t3-t2 | def process_message(self, peer, mailfrom, rcpttos, data): try: msg = email.Parser.Parser().parsestr(data) except: pass else: msg.add_header("X-Peer", peer[0]) prob, data = self.h.score_and_filter(msg) if prob >= self.spam_cutoff: self.push('503 Error: probable spam') self.log_message(data) return |
if self.current_folder != folder: if self.current_folder != None: | if self.current_folder != None: if self.current_folder != folder: | def SelectFolder(self, folder): '''A method to point ensuing imap operations at a target folder''' if self.current_folder != folder: if self.current_folder != None: if self.do_expunge: # It is faster to do close() than a single # expunge when we log out (because expunge returns # a list of all the deleted messages, tha... |
imap.SelectFolder(self.spam_folder) imap.SelectFolder(self.unsure_folder) | imap.SelectFolder(self.spam_folder.name) imap.SelectFolder(self.unsure_folder.name) | def Filter(self): if options["globals", "verbose"]: t = time.time() |
self.expunge() | if self.logged_in: for fol in ["spam_folder", "unsure_folder",]: self.select(options["imap", fol]) self.expunge() for fol_list in ["ham_train_folders", "spam_train_folders",]: for fol in options["imap", fol_list]: self.select(fol) self.expunge() | def logout(self): # sign off if self.do_expunge: self.expunge() BaseIMAP.logout(self) # superclass logout |
from imaplib import IMAP_SSL | from imaplib import IMAP4_SSL | def __init__(self, cls, imap, pwd, imap_session_class): global parm_map # Only offer SSL if it is available try: from imaplib import IMAP_SSL except ImportError: parm_list = list(parm_map) parm_list.remove(("imap", "use_ssl")) parm_map = tuple(parm_list) UserInterface.UserInterface.__init__(self, cls, parm_map, adv_map... |
"Platform mutex still help after stop") | "Platform mutex still held after stop") | def _stop_spawner(self, spawner): self.failUnless(spawner.is_running(), "must be running to stop") self.failUnless(is_any_sb_server_running(), "Platform mutex must be held to stop") spawner.stop() self.failUnless(not spawner.is_running(), "didn't stop after stop") self.failUnless(not is_any_sb_server_running(), "Platfo... |
return type(self.value) in MultiContainerTypes | return type(self.default_value) in MultiContainerTypes | def multiple_values_allowed(self): '''Multiple values are allowed for this option.''' return type(self.value) in MultiContainerTypes |
m = re.search(r"{\d+}", fol[0]) | m = self.number_re.search(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 BadIMAPResponseError: # We want to keep going, so just print out a warning, and # return an empty list. print "Could not retrieve folder ... |
r = re.compile(r"\(([\w\\ ]*)\) ") m = r.search(fol) | m = self.folder_re.search(fol) | 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 BadIMAPResponseError: # We want to keep going, so just print out a warning, and # return an empty list. print "Could not retrieve folder ... |
flags = re.sub(r"\\Recent ?| ?\\Recent", "", flags) | flags = self.recent_re.sub("", flags) | def Save(self): """Save message to IMAP server. |
data = self.imap_server.check_response("fetch %s rfc822.header" \ % (key,), response) data = self.imap_server.extract_fetch_data(data[0]) | response_data = self.imap_server.check_response(\ "fetch %s rfc822.header" % (key,), response) data = self.imap_server.extract_fetch_data(response_data[0]) | def __getitem__(self, key): """Return message matching the given *uid*. |
custom_header_id = re.escape(options["Headers", "mailid_header_name"]) + \ "\:\s*(\d+(?:\-\d)?)" | try: headers = data["RFC822.HEADER"] except KeyError: print >> sys.stderr, "Trouble parsing response:", \ response_data, data print >> sys.stderr, "Please report this to spambayes@python.org" if options["globals", "verbose"]: sys.stdout.write("?") return msg | def __getitem__(self, key): """Return message matching the given *uid*. |
for id_header in [custom_header_id, "Message-ID\: ?\<([^\n\>]+)\>"]: mo = re.search(id_header, data["RFC822.HEADER"], re.IGNORECASE) | for id_header_re in [self.custom_header_id_re, self.message_id_re]: mo = id_header_re.search(headers) | def __getitem__(self, key): """Return message matching the given *uid*. |
h = win32gui.SendMessage(self.list, commctrl.TVM_GETSELECTEDITEM, commctrl.TVGN_CARET, h) | h = win32gui.SendMessage(self.list, commctrl.TVM_GETNEXTITEM, commctrl.TVGN_CARET, 0) | def _YieldCheckedChildren(self): if self.single_select: # If single-select, the checked state is not used, just the # selected state. try: h = win32gui.SendMessage(self.list, commctrl.TVM_GETSELECTEDITEM, commctrl.TVGN_CARET, h) except win32gui.error: return info = self._GetLVItem(h) spec = self.item_map[info[7]] yield... |
if include_sub: folders = item.Folders folder = folders.GetFirst() while folder is not None: self.EnsureOutlookFieldsForFolder(folder.EntryID, True) folder = folders.GetNext() | 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... | |
valid = parent is not None and parent.GetParent() is not None | try: grandparent = parent.GetParent() except self.manager.message_storeMsgStoreException, details: if "0x80070005" in details: valid = parent is not None else: raise else: valid = parent is not None and grandparent is not None | def _CheckSelectionsValid(self, is_close = False): if self.in_check_selections_valid: return self.in_check_selections_valid = True try: if self.single_select: if is_close: # Make sure one is selected. for ignore in self._YieldCheckedChildren(): break else: self.manager.ReportInformation("You must select a folder") retu... |
print "Eeek - couldn't get the folder to check valid" | print "Eeek - couldn't get the folder to check " \ "valid:", details | def _CheckSelectionsValid(self, is_close = False): if self.in_check_selections_valid: return self.in_check_selections_valid = True try: if self.single_select: if is_close: # Make sure one is selected. for ignore in self._YieldCheckedChildren(): break else: self.manager.ReportInformation("You must select a folder") retu... |
child_folder = manager.message_store.GetFolder(temp_id) if child_folder is not None: spec = FolderSpec(child_folder.GetID(), name, folder_spec.ignore_eids) table = child_folder.OpenEntry().GetHierarchyTable(0) if table.GetRowCount(0) == 0: spec.children = [] else: spec.children = None children.append(spec) | try: child_folder = manager.message_store.GetFolder(temp_id) if child_folder is not None: spec = FolderSpec(child_folder.GetID(), name, folder_spec.ignore_eids) table = child_folder.OpenEntry().GetHierarchyTable(0) if table.GetRowCount(0) == 0: spec.children = [] else: spec.children = None children.append(spec) excep... | def _BuildFoldersMAPI(manager, folder_spec): # This is called dynamically as folders are expanded. win32ui.DoWaitCursor(1) folder = manager.message_store.GetFolder(folder_spec.folder_id).OpenEntry() # Get the hierarchy table for it. table = folder.GetHierarchyTable(0) children = [] order = (((PR_DISPLAY_NAME_A, mapi.TA... |
return self.bayes | return self.classifier_data.bayes | def GetClassifier(self): """Return the classifier we're using.""" return self.bayes |
"(delay=%s milliseconds, interval=%s milliseconds)" \ | " (delay=%s seconds, interval=%s seconds)" \ | def Init(self, *args): _BaseItemsEvent.Init(self, *args) timer_enabled = self.manager.config.filter.timer_enabled start_delay = self.manager.config.filter.timer_start_delay interval = self.manager.config.filter.timer_interval use_timer = timer_enabled and start_delay and interval if timer_enabled and not use_timer: pri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.