rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
start_response('200 OK', [('Content-Type', 'text/html')])
start_response('200 OK', [('Content-Type', 'text/html'), charset])
def paste(environ, start_response): params = FieldStorage(fp=environ['wsgi.input'], environ=environ, keep_blank_values = True) html_pre = u'''<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
options += "&hl=" + params.getvalue('hl')
options += '&hl=' + params.getvalue('hl')
def paste(environ, start_response): params = FieldStorage(fp=environ['wsgi.input'], environ=environ, keep_blank_values = True) html_pre = u'''<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
options += "&ne"
options += '&ne'
def paste(environ, start_response): params = FieldStorage(fp=environ['wsgi.input'], environ=environ, keep_blank_values = True) html_pre = u'''<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
start_response('200 OK', [('Content-Type', 'text/html'), ('charset', 'utf-8')]) return (html_pre + body + html_post).encode('utf-8')
start_response('200 OK', [('Content-Type', 'text/html'), charset]) return html_pre.encode('utf-8') + body + html_post.encode('utf-8')
def paste(environ, start_response): params = FieldStorage(fp=environ['wsgi.input'], environ=environ, keep_blank_values = True) html_pre = u'''<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
start(8081)
start(8080)
def start(port): srv = make_server('localhost', port, paste) srv.serve_forever()
def run_sumo(runpath, sumo_command, config_file_name, remote_port, seed, client_socket, unused_port_lock, keep_temp):
def run_sumo(runpath, sumo_command, shlex, config_file_name, remote_port, seed, client_socket, unused_port_lock, keep_temp):
def run_sumo(runpath, sumo_command, config_file_name, remote_port, seed, client_socket, unused_port_lock, keep_temp): """ Actually run SUMO. """ # create log files sumoLogOut = open(os.path.join(runpath, 'sumo-launchd.out.log'), 'w') sumoLogErr = open(os.path.join(runpath, 'sumo-launchd.err.log'), 'w') # start SUMO s...
cmd = [sumo_command, "-c", config_file_name]
cmd = [] if shlex: import shlex cmd = shlex.split(sumo_command.replace('{}', '-c ' + unicode(config_file_name).encode())) else: cmd = [sumo_command, "-c", config_file_name]
def run_sumo(runpath, sumo_command, config_file_name, remote_port, seed, client_socket, unused_port_lock, keep_temp): """ Actually run SUMO. """ # create log files sumoLogOut = open(os.path.join(runpath, 'sumo-launchd.out.log'), 'w') sumoLogErr = open(os.path.join(runpath, 'sumo-launchd.err.log'), 'w') # start SUMO s...
sumo = subprocess.Popen(cmd, cwd=runpath, stdin=None, stdout=sumoLogOut, stderr=sumoLogErr, close_fds=True)
sumo = subprocess.Popen(cmd, cwd=runpath, stdin=None, stdout=sumoLogOut, stderr=sumoLogErr)
def run_sumo(runpath, sumo_command, config_file_name, remote_port, seed, client_socket, unused_port_lock, keep_temp): """ Actually run SUMO. """ # create log files sumoLogOut = open(os.path.join(runpath, 'sumo-launchd.out.log'), 'w') sumoLogErr = open(os.path.join(runpath, 'sumo-launchd.err.log'), 'w') # start SUMO s...
def handle_launch_configuration(sumo_command, launch_xml_string, client_socket, keep_temp):
def handle_launch_configuration(sumo_command, shlex, launch_xml_string, client_socket, keep_temp):
def handle_launch_configuration(sumo_command, launch_xml_string, client_socket, keep_temp): """ Process launch configuration in launch_xml_string. """ # create temporary directory logging.debug("Creating temporary directory...") runpath = tempfile.mkdtemp(prefix="sumo-launchd-tmp-") if not runpath: raise RuntimeError(...
result_xml = run_sumo(runpath, sumo_command, config_file_name, remote_port, seed, client_socket, unused_port_lock, keep_temp)
result_xml = run_sumo(runpath, sumo_command, shlex, config_file_name, remote_port, seed, client_socket, unused_port_lock, keep_temp)
def handle_launch_configuration(sumo_command, launch_xml_string, client_socket, keep_temp): """ Process launch configuration in launch_xml_string. """ # create temporary directory logging.debug("Creating temporary directory...") runpath = tempfile.mkdtemp(prefix="sumo-launchd-tmp-") if not runpath: raise RuntimeError(...
def handle_connection(sumo_command, conn, addr, keep_temp):
def handle_connection(sumo_command, shlex, conn, addr, keep_temp):
def handle_connection(sumo_command, conn, addr, keep_temp): """ Handle incoming connection. """ logging.debug("Handling connection from %s on port %d" % addr) try: data = read_launch_config(conn) handle_launch_configuration(sumo_command, data, conn, keep_temp) except Exception, e: logging.error("Aborting on error: %...
handle_launch_configuration(sumo_command, data, conn, keep_temp)
handle_launch_configuration(sumo_command, shlex, data, conn, keep_temp)
def handle_connection(sumo_command, conn, addr, keep_temp): """ Handle incoming connection. """ logging.debug("Handling connection from %s on port %d" % addr) try: data = read_launch_config(conn) handle_launch_configuration(sumo_command, data, conn, keep_temp) except Exception, e: logging.error("Aborting on error: %...
def wait_for_connections(sumo_command, sumo_port, bind_address, do_daemonize, do_kill, pidfile, keep_temp):
def wait_for_connections(sumo_command, shlex, sumo_port, bind_address, do_daemonize, do_kill, pidfile, keep_temp):
def wait_for_connections(sumo_command, sumo_port, bind_address, do_daemonize, do_kill, pidfile, keep_temp): """ Open TCP socket, wait for connections, call handle_connection for each """ if do_kill: check_kill_daemon(pidfile) listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listener.setsockopt(socket.SOL_...
thread.start_new_thread(handle_connection, (sumo_command, conn, addr, keep_temp))
thread.start_new_thread(handle_connection, (sumo_command, shlex, conn, addr, keep_temp))
def wait_for_connections(sumo_command, sumo_port, bind_address, do_daemonize, do_kill, pidfile, keep_temp): """ Open TCP socket, wait for connections, call handle_connection for each """ if do_kill: check_kill_daemon(pidfile) listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listener.setsockopt(socket.SOL_...
wait_for_connections(options.command, options.port, options.bind, options.daemonize, options.kill, options.pidfile, options.keep_temp)
wait_for_connections(options.command, options.shlex, options.port, options.bind, options.daemonize, options.kill, options.pidfile, options.keep_temp)
def main(): """ Program entry point when run interactively. """ # Option handling parser = OptionParser() parser.add_option("-c", "--command", dest="command", default="sumo", help="run SUMO as COMMAND [default: %default]", metavar="COMMAND") parser.add_option("-p", "--port", dest="port", type="int", default=9999, acti...
"""Try to convert ``value`` to a floating-point number. If
"""Try to convert `value` to a floating-point number. If
def float_or_0(value): """Try to convert ``value`` to a floating-point number. If conversion fails, return 0. """ try: return float(value) except ValueError: return 0
def match_columns(x_expr, y_exprs, fieldnames): """Match ``x_expr`` and ``y_exprs`` to all available column names in ``fieldnames``. Return the matched ``x_column`` and ``y_columns``. If no matches are found for any expression, raise a ``NoMatch`` exception. """ def _matches(expr): """Return a list of matching column n...
def strip_prefix(strings): """Strip a common prefix from a sequence of strings. Return `(prefix, stripped)` where `prefix` is the string that is common, and `stripped` is strings with the prefix removed. """ prefix = '' for letters in zip(*strings): if len(set(letters)) == 1: prefix += letters[0] index = len(prefix)...
def match_columns(x_expr, y_exprs, fieldnames): """Match ``x_expr`` and ``y_exprs`` to all available column names in ``fieldnames``. Return the matched ``x_column`` and ``y_columns``. If no matches are found for any expression, raise a ``NoMatch`` exception. """ def _matches(expr): """Return a list of matching column n...
axes.xaxis.set_major_locator(dates.HourLocator(interval=24))
locator = dates.DayLocator(interval=1)
def add_date_labels(axes, min_date, max_date): """Add date labels to the given Axes. """ axes.set_xlim(min_date, max_date) date_range = max_date - min_date date_format = '%H:%M' # If date range is more than 2 days, label each day if date_range > timedelta(days=2): axes.xaxis.set_major_locator(dates.HourLocator(interva...
axes.xaxis.set_major_locator(dates.HourLocator(interval=12))
locator = dates.HourLocator(interval=12)
def add_date_labels(axes, min_date, max_date): """Add date labels to the given Axes. """ axes.set_xlim(min_date, max_date) date_range = max_date - min_date date_format = '%H:%M' # If date range is more than 2 days, label each day if date_range > timedelta(days=2): axes.xaxis.set_major_locator(dates.HourLocator(interva...
axes.xaxis.set_major_locator(dates.MinuteLocator(interval=30))
locator = dates.HourLocator(interval=1)
def add_date_labels(axes, min_date, max_date): """Add date labels to the given Axes. """ axes.set_xlim(min_date, max_date) date_range = max_date - min_date date_format = '%H:%M' # If date range is more than 2 days, label each day if date_range > timedelta(days=2): axes.xaxis.set_major_locator(dates.HourLocator(interva...
axes.xaxis.set_major_locator(dates.MinuteLocator(interval=10))
locator = dates.MinuteLocator(interval=10)
def add_date_labels(axes, min_date, max_date): """Add date labels to the given Axes. """ axes.set_xlim(min_date, max_date) date_range = max_date - min_date date_format = '%H:%M' # If date range is more than 2 days, label each day if date_range > timedelta(days=2): axes.xaxis.set_major_locator(dates.HourLocator(interva...
axes.xaxis.set_major_locator(dates.MinuteLocator(interval=5))
locator = dates.MinuteLocator(interval=5)
def add_date_labels(axes, min_date, max_date): """Add date labels to the given Axes. """ axes.set_xlim(min_date, max_date) date_range = max_date - min_date date_format = '%H:%M' # If date range is more than 2 days, label each day if date_range > timedelta(days=2): axes.xaxis.set_major_locator(dates.HourLocator(interva...
axes.xaxis.set_major_locator(dates.MinuteLocator()) axes.xaxis.set_major_formatter(dates.DateFormatter(date_format))
locator = dates.MinuteLocator() formatter = dates.DateFormatter(date_format) return (locator, formatter)
def add_date_labels(axes, min_date, max_date): """Add date labels to the given Axes. """ axes.set_xlim(min_date, max_date) date_range = max_date - min_date date_format = '%H:%M' # If date range is more than 2 days, label each day if date_range > timedelta(days=2): axes.xaxis.set_major_locator(dates.HourLocator(interva...
return x_values, y_values
return (x_values, y_values) class Graph (object): """A graph of data from a CSV file. """ def __init__(self, csv_file, x_expr, y_exprs, title='', date_format='', line_style=''): """Create a graph from `csvfile`, with `x_expr` defining the x-axis, and `y_exprs` being columns to get y-values from. """ self.csv_file = c...
def read_csv_values(reader, x_column, y_columns, date_format=''): """Read values from a csv `DictReader`, and return all values in `x_column` and `y_columns`. """ x_values = [] y_values = {} for row in reader: x_value = row[x_column] if date_format: x_value = datetime.strptime(x_value, date_format) else: x_value = floa...
def do_graph(csvfile, x_expr, y_exprs, title='', save_file='', date_format='', line_style='-'): """Generate a graph from `csvfile`, with `x_expr` defining the x-axis, and `y_exprs` being columns to get y-values from. """ print("Reading '%s'" % csvfile) reader = csv.DictReader(open(csvfile, 'r')) try: x_column, y_colu...
def do_graph(csvfile, x_expr, y_exprs, title='', save_file='', date_format='', line_style='-'): """Generate a graph from `csvfile`, with `x_expr` defining the x-axis, and `y_exprs` being columns to get y-values from. """ print("Reading '%s'" % csvfile) reader = csv.DictReader(open(csvfile, 'r')) # Attempt to match col...
usage_error("Unknown option: %s" % arg)
usage_error("Unknown option: %s" % opt)
def shorten_labels(labels): """Given a list of column labels of the form "\A\B\C", return a new list of labels with any common A, B, C parts. """ # Don't try to shorten fewer than 2 labels if len(labels) < 2: return labels split_labels = (label.split('\\') for label in labels) transposed = zip(*split_labels) while len(...
do_graph(csvfile, x_expr, y_exprs, title, save_file, date_format, line_style)
graph = Graph(csvfile, x_expr, y_exprs, title, date_format, line_style) graph.generate() if save_file: graph.save(save_file) else: graph.show()
def shorten_labels(labels): """Given a list of column labels of the form "\A\B\C", return a new list of labels with any common A, B, C parts. """ # Don't try to shorten fewer than 2 labels if len(labels) < 2: return labels split_labels = (label.split('\\') for label in labels) transposed = zip(*split_labels) while len(...
locator = dates.HourLocator(interval=12)
locator = dates.HourLocator(interval=6)
def date_locator_formatter(min_date, max_date): """Determine suitable locator and format to use for a range of dates. Returns `(locator, formatter)` where `locator` is an `RRuleLocator`, and `formatter` is a `DateFormatter`. """ date_range = max_date - min_date # Use HH:MM format by default date_format = '%H:%M' # For...
def add_notes(figure, axes, notes_file): annot_lines = [ axes.axvline(x_values[4]), axes.axvline(x_values[8]), ] annot_labels = [ 'Hello world', 'Goodbye cruel world', ] annot_legend = figure.legend(annot_lines, annot_labels, prop={'size': 9})
def print_columns(csv_file): """Display column names in the given .csv file. """ infile = open(csv_file, 'r') first = infile.readline() infile.close() columns = [col.strip(' "') for col in first.strip().split(',')] print("Column names found in '%s'" % csv_file) print('\n'.join(columns))
def show(self): """Display the graph in a GUI window. """ pylab.show()
if len(sys.argv) < 4: usage_error("Need a filename and at least two column names")
if len(sys.argv) == 2 and sys.argv[1].lower().endswith('.csv'): print_columns(sys.argv[1]) sys.exit() elif len(sys.argv) < 4: usage_error("Need a .csv filename and at least two column names")
def add_notes(figure, axes, notes_file): # Draw a vertical line annot_lines = [ axes.axvline(x_values[4]), axes.axvline(x_values[8]), ] annot_labels = [ 'Hello world', 'Goodbye cruel world', ] annot_legend = figure.legend(annot_lines, annot_labels, prop={'size': 9})
if not csv_file.endswith('.csv'):
if not csv_file.lower().endswith('.csv'):
def add_notes(figure, axes, notes_file): # Draw a vertical line annot_lines = [ axes.axvline(x_values[4]), axes.axvline(x_values[8]), ] annot_labels = [ 'Hello world', 'Goodbye cruel world', ] annot_legend = figure.legend(annot_lines, annot_labels, prop={'size': 9})
""" for dt_format in _date_time_formats: format, regexp = format_regexp(dt_format) if re.search(regexp, string, re.IGNORECASE):
>>> guess_format('Aug 15 2009 15:24') '%b %d %Y %H:%M' >>> guess_format('3-14-15 9:26:53.589') '%m-%d-%y %H:%M:%S.%f' """ for format, regexp in _format_regexps: if regexp.search(string):
def guess_format(string): """Try to guess the date/time format of ``string``, or raise a `CannotParse` exception. Examples:: >>> guess_format('2010/01/28 13:25:49') '%Y/%m/%d %H:%M:%S' >>> guess_format('01/28/10 1:25:49 PM') '%m/%d/%y %I:%M:%S %p' >>> guess_format('01/28/2010 13:25:49.123') '%m/%d/%Y %H:%M:%S.%f' ...
outFile.write("!!OID TIME OBS_TYPE RA DEC APPMAG FILTER OBSERVATORY RMS_RA RMS_DEC RMS_MAG S2N Secret_name")
outFile.write("!!OID TIME OBS_TYPE RA DEC APPMAG FILTER OBSERVATORY RMS_RA RMS_DEC RMS_MAG S2N Secret_name\n")
def writeTrackletsFile(detsFile, outFile): """ translate from MITI detections to orbit_server.x input format 'tracklets.' we don't really write tracklets at all - orbit_server.x will actually allow 'singleton' tracklets of size one, which are basically just detections. The 'tracklets' we write have the same IDs as the...
outFile.write("%d %5.10f %d %3.12f %3.12f %3.12f %s %s %3.12f %3.12f %3.12f %3.12f %s\n" \
outFile.write("%d %5.10f %s %3.12f %3.12f %3.12f %s %s %3.12f %3.12f %3.12f %3.12f %s\n" \
def writeTrackletsFile(detsFile, outFile): """ translate from MITI detections to orbit_server.x input format 'tracklets.' we don't really write tracklets at all - orbit_server.x will actually allow 'singleton' tracklets of size one, which are basically just detections. The 'tracklets' we write have the same IDs as the...
while trackLine != "":
count = 0 while trackLine != "":
def writeRequest(inTracks, requestFile): """ write the .in.request file given a set of DIA IDs which comprise the tracks.""" requestFile.write("!!ID_OID NID TRACKLET_OIDs OP_CODE N_OBS N_SOLUTIONS N_NIGHTS ARC_TYPE NO_RADAR PARAM(4)\n") trackLine = inTracks.readline() while trackLine != "": diaIds = map(int, trackLine....
count += 1 if DEBUG and count > 1000: return
def writeRequest(inTracks, requestFile): """ write the .in.request file given a set of DIA IDs which comprise the tracks.""" requestFile.write("!!ID_OID NID TRACKLET_OIDs OP_CODE N_OBS N_SOLUTIONS N_NIGHTS ARC_TYPE NO_RADAR PARAM(4)\n") trackLine = inTracks.readline() while trackLine != "": diaIds = map(int, trackLine....
nextTrack = map(int, inTracksFile.readline().split())
nextTrackLine = inTracksFile.readline()
def writeOrbitServerInputFiles(inTracksFile, outPrefix, cursor, maxTrackletsPerFile, maxTracksPerFile): """writes sets of input files for orbit_server.x. create as many sets of output files as needed""" curFileSetNum = 0 totalTracksWritten = 0 requestFile, trackletsFile = createNewFiles(outPrefix, curFileSetNum) nextT...
while nextTrack != "":
while nextTrackLine != "": nextTrack = map(int, nextTrackLine.split())
def writeOrbitServerInputFiles(inTracksFile, outPrefix, cursor, maxTrackletsPerFile, maxTracksPerFile): """writes sets of input files for orbit_server.x. create as many sets of output files as needed""" curFileSetNum = 0 totalTracksWritten = 0 requestFile, trackletsFile = createNewFiles(outPrefix, curFileSetNum) nextT...
readaheadTrack = inTracksFile.readline() readaheadTrack = map(int, readaheadTrack.split())
readaheadTrackLine = inTracksFile.readline() readaheadTrack = map(int, readaheadTrackLine.split())
def writeOrbitServerInputFiles(inTracksFile, outPrefix, cursor, maxTrackletsPerFile, maxTracksPerFile): """writes sets of input files for orbit_server.x. create as many sets of output files as needed""" curFileSetNum = 0 totalTracksWritten = 0 requestFile, trackletsFile = createNewFiles(outPrefix, curFileSetNum) nextT...
if readaheadTrack == "" or \
if readaheadTrackLine == "" or \
def writeOrbitServerInputFiles(inTracksFile, outPrefix, cursor, maxTrackletsPerFile, maxTracksPerFile): """writes sets of input files for orbit_server.x. create as many sets of output files as needed""" curFileSetNum = 0 totalTracksWritten = 0 requestFile, trackletsFile = createNewFiles(outPrefix, curFileSetNum) nextT...
nextTrack = readaheadTrack
nextTrackLine = readaheadTrackLine
def writeOrbitServerInputFiles(inTracksFile, outPrefix, cursor, maxTrackletsPerFile, maxTracksPerFile): """writes sets of input files for orbit_server.x. create as many sets of output files as needed""" curFileSetNum = 0 totalTracksWritten = 0 requestFile, trackletsFile = createNewFiles(outPrefix, curFileSetNum) nextT...
print sorted(zip(k, v))
def test_iter(): J = judy.JudyIntObjectMap() P = { } random.seed(0) k = [random.randint(0, 10000) for i in xrange(10)] v = ['a', ['a'], [{},{'a':'b'}], 'k', u'arni', 1.00001, 7, 2, 1, 10] for K, V in zip(k, v): J[K] = V P[K] = V A = list(J) B = sorted(list(P)) assert(A == B) A = list(J.iterkeys()) B = sorted(list(P...
print 'A', A print 'B', B
def test_iter(): J = judy.JudyIntObjectMap() P = { } random.seed(0) k = [random.randint(0, 10000) for i in xrange(10)] v = ['a', ['a'], [{},{'a':'b'}], 'k', u'arni', 1.00001, 7, 2, 1, 10] for K, V in zip(k, v): J[K] = V P[K] = V A = list(J) B = sorted(list(P)) assert(A == B) A = list(J.iterkeys()) B = sorted(list(P...
print repr(J) print repr(P)
def test_iter(): J = judy.JudyIntObjectMap() P = { } random.seed(0) k = [random.randint(0, 10000) for i in xrange(10)] v = ['a', ['a'], [{},{'a':'b'}], 'k', u'arni', 1.00001, 7, 2, 1, 10] for K, V in zip(k, v): J[K] = V P[K] = V A = list(J) B = sorted(list(P)) assert(A == B) A = list(J.iterkeys()) B = sorted(list(P...
def test_print(): J = judy.JudyIntObjectMap() P = { } random.seed(0) k = [random.randint(0, 10000) for i in xrange(10)] v = ['a', ['a'], [{},{'a':'b'}], 'k', u'arni', 1.00001, 7, 2, 1, 10] for K, V in zip(k, v): J[K] = V P[K] = V for i in xrange(10000000): buffer = cStringIO.StringIO() print >> buffer, repr(J) print...
shutil.copytree(src, dst)
shutil.copytree(src, dst, ignore=shutil.ignore_patterns(IGNORE_FILES))
def parse_jid(string): value = jid.JID(string) if value.node is None: raise jid.JIDError("JID has to be of form node@domain") value = unicode(value) try: return str(value) except UnicodeDecodeError: return value
return self.parseCountry(string)[1]
return self.getCountry(string)[1]
def getCountryCode(self, string=None): if string == None: return self.countryCode else: return self.parseCountry(string)[1]
return self.parseCountry(string)[0]
return self.getCountry(string)[0] def getCountry(self, string=None): if string == None: return [self.countryName, self.countryCode] else: country = self.parseCountry(string) if country != None and len(country) >= 2: self.countryName = country[0] self.countryCode = country[1] return[country[0], country[1]] else: return...
def getCountryName(self, string=None): if string == None: return self.countryName else: return self.parseCountry(string)[0]
args.extend(["-m", module])
args.extend(["-m", "runpy", module])
def signal_handler(sig, frame): sys.exit()
self.dsts = roomfarm.Counter()
self.asns = roomfarm.Counter()
def __init__(self, xmpp, host, port, channel, own_nick, feed_nick, password, use_ssl): roomfarm.RoomFarm.__init__(self)
for room, _ in self.dsts: room.send(event)
for asn in event.attrs.get("asn", ()): rooms = self.asns.get(asn) for room in rooms: room.send(event)
def distribute(inner, self): while True: yield inner
def session(inner, self, state, room, **keys):
def session(inner, self, state, asn, room, **keys): asn = str(asn)
def session(inner, self, state, room, **keys): room = self.rooms(inner, room) self.dsts.inc(room) try: while True: yield inner except services.Stop: inner.finish() finally: self.dsts.dec(room) self.rooms(inner)
self.dsts.inc(room)
self.asns.inc(asn, room)
def session(inner, self, state, room, **keys): room = self.rooms(inner, room) self.dsts.inc(room) try: while True: yield inner except services.Stop: inner.finish() finally: self.dsts.dec(room) self.rooms(inner)
self.dsts.dec(room)
self.asns.dec(asn, room)
def session(inner, self, state, room, **keys): room = self.rooms(inner, room) self.dsts.inc(room) try: while True: yield inner except services.Stop: inner.finish() finally: self.dsts.dec(room) self.rooms(inner)
def format_time(timestamp): return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp))
def format_time(timestamp, format="%Y-%m-%d %H:%M:%S"): return time.strftime(format, time.localtime(timestamp))
def format_time(timestamp): return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp))
if not match_rule(event):
if match_rule and not match_rule(event):
def event_parser(self, message, requester, room_jid, **attrs): for element in message.children("event"): event = events.Event.from_element(element)
self.xmpp.core.message(requester, event.to_element(), **attrs)
elements = [event.to_element(), delay_element(etime)] self.xmpp.core.message(requester, *elements, **attrs)
def event_parser(self, message, requester, room_jid, **attrs): for element in message.children("event"): event = events.Event.from_element(element)
self.xmpp.core.message(requester, event.to_element(), **attrs)
def command_parser(self, message, requester, room_jid, **attrs): for body in message.children("body"): matcher, start, end = parse_command(body, "historian") if matcher is None: continue
data = yield inner.sub(utils.fetch_url(url, opener))
_, data = yield inner.sub(utils.fetch_url(url, opener))
def fetch_extras(inner, opener, url): try: data = yield inner.sub(utils.fetch_url(url, opener)) except utils.FetchUrlFailed: inner.finish(list()) match = TABLE_REX.search(data) if match is None: inner.finish(list()) table = etree.XML(match.group(1)) keys = [th.text or "" for th in table.findall("thead/tr/th")] keys =...
data = yield inner.sub(utils.fetch_url(url, opener))
_, data = yield inner.sub(utils.fetch_url(url, opener))
def atlassrf(inner, dedup, opener, url): try: print "Downloading the report" data = yield inner.sub(utils.fetch_url(url, opener)) except utils.FetchUrlFailed, fuf: print >> sys.stderr, "Failed to download the report:", fuf return print "Downloaded the report" count = 0 for _, elem in etree.iterparse(StringIO.StringIO(...
self.log.critical(msg) return
raise imaplib.IMAP4.abort(msg)
def connect(self): self.log.info("Connecting to IMAP server %r port %d", self.mail_server, self.mail_port) mailbox = imaplib.IMAP4_SSL(self.mail_server, self.mail_port) self.log.info("Logging in to IMAP server %s port %d", self.mail_server, self.mail_port) mailbox.login(self.mail_user, self.mail_password) try: status,...
if (ai == None): self.log.error("No abuse info found for %s", str(ip)) continue
def distribute(inner, self, name): count = 0 while True: yield inner
times = set(t.lower() for t in times)
def alert(inner, *times): times = set(t.lower() for t in times) while True: if times: sleeper = timer.sleep(min(map(next_time, times))) else: sleeper = threado.Channel() while not sleeper.has_result(): try: yield inner, sleeper except: sleeper.rethrow() raise inner.send()
for to in to_addrs + cc_addrs: inner.send(from_addr[1], to[1], subject, msg_data)
for to_addr in to_addrs + cc_addrs: inner.send(from_addr[1], to_addr[1], subject, msg_data)
def _collect(inner, self, to=[], cc=[], subject="", template="", **keys): from email.header import Header from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.charset import Charset, QP from email.utils import formatdate, make_msgid, getaddresses, formataddr
yield inner.sub(fetch_url(match, filename_rex))
try: info, cvs_data = yield inner.sub(utils.fetch_url(match)) except utils.FetchUrlFailed, fuf: print >> sys.stderr, "Could not fetch report %r:" % match, fuf
def fetch_content(inner, mailbox, filter, url_rex, filename_rex): mailbox.noop() result, data = mailbox.search(None, filter) if not data or not data[0]: return for num in data[0].split(): for path, content_type in find_payload(mailbox, num): if content_type != "text/plain": continue fetch = "(BODY.PEEK[%s]<0.2048>)" ...
def fetch_url(inner, url, filename_rex): opened = urllib2.urlopen(url) try: info = str(opened.info()) header = email.parser.Parser().parsestr(info, headersonly=True) filename = header.get_filename(None) groupdict = dict() if filename is not None: match = filename_rex.match(filename) if match is not None: groupdict = ...
def parse_cvs(inner, info, cvs_data): groupdict = dict() filename = info.get_filename(None) if filename is not None: match = filename_rex.match(filename) if match is not None: groupdict = match.groupdict() for row in csv.DictReader(cvs_data.splitlines()): event = events.Event() for key, value in groupdict.items(): if...
def fetch_url(inner, url, filename_rex): opened = urllib2.urlopen(url) try: info = str(opened.info()) header = email.parser.Parser().parsestr(info, headersonly=True) filename = header.get_filename(None) groupdict = dict() if filename is not None: match = filename_rex.match(filename) if match is not None: groupdict = ...
opened.close()
list(inner)
def fetch_url(inner, url, filename_rex): opened = urllib2.urlopen(url) try: info = str(opened.info()) header = email.parser.Parser().parsestr(info, headersonly=True) filename = header.get_filename(None) groupdict = dict() if filename is not None: match = filename_rex.match(filename) if match is not None: groupdict = ...
state_file=None, filter=None, url_rex=None, filename_rex=None):
filter=None, url_rex=None, filename_rex=None, poll_interval=60.0, state_file=None):
def __init__(self, xmpp, mail_server, mail_user, mail_password, state_file=None, filter=None, url_rex=None, filename_rex=None):
self.poll_frequency = 300.0
self.poll_interval = poll_interval
def __init__(self, xmpp, mail_server, mail_user, mail_password, state_file=None, filter=None, url_rex=None, filename_rex=None):
while True: current_time = time.time() if self.expire_time > current_time: yield self.inner, timer.sleep(self.expire_time-current_time) else:
try: while True: yield self.inner, timer.sleep(self.poll_interval)
def run(self): while True: current_time = time.time() if self.expire_time > current_time: yield self.inner, timer.sleep(self.expire_time-current_time) else: yield self.inner.sub(fetch_content(self.mailbox, self.filter, self.url_rex, self.filename_rex) | self.distribute())
self.expire_time = time.time() + self.poll_frequency
except services.Stop: self.inner.finish()
def run(self): while True: current_time = time.time() if self.expire_time > current_time: yield self.inner, timer.sleep(self.expire_time-current_time) else: yield self.inner.sub(fetch_content(self.mailbox, self.filter, self.url_rex, self.filename_rex) | self.distribute())
filter, url_rex, filename_rex)
filter, url_rex, filename_rex, poll_interval, state_file)
def bot(inner): print "Connecting XMPP server with JID", xmpp_jid xmpp = yield connect(xmpp_jid, xmpp_password) xmpp.core.presence()
data = yield inner.sub(utils.fetch_url(opener, url))
data = yield inner.sub(utils.fetch_url(url, opener))
def fetch_extras(inner, opener, url): try: data = yield inner.sub(utils.fetch_url(opener, url)) except utils.FetchUrlFailed: inner.finish(list()) match = TABLE_REX.search(data) if match is None: inner.finish(list()) table = etree.XML(match.group(1)) keys = [th.text or "" for th in table.findall("thead/tr/th")] keys =...
data = yield inner.sub(utils.fetch_url(opener, url))
data = yield inner.sub(utils.fetch_url(url, opener))
def atlassrf(inner, dedup, opener, url): try: print "Downloading the report" data = yield inner.sub(utils.fetch_url(opener, url)) except utils.FetchUrlFailed, fuf: print >> sys.stderr, "Failed to download the report:", fuf return print "Downloaded the report" count = 0 for _, elem in etree.iterparse(StringIO.StringIO(...
path = session.format_path(config)
path = session.path
def run(self): print "digraph G {" print "node [ shape=box, style=filled, color=lightgrey ];"
def _inc(inner, self, key, channel, channels):
def _inc(inner, self, key):
def _inc(inner, self, key, channel, channels): try: while not channel.has_result(): for item in inner: inner.send(item) for _ in channel: pass yield inner, channel finally: channels.discard(channel) if self.counter.dec(key): callqueue.add(self._check, key) inner.finish(channel.result())
while not channel.has_result():
while True: yield inner
def _inc(inner, self, key, channel, channels): try: while not channel.has_result(): for item in inner: inner.send(item) for _ in channel: pass yield inner, channel finally: channels.discard(channel) if self.counter.dec(key): callqueue.add(self._check, key) inner.finish(channel.result())
for _ in channel: pass yield inner, channel
def _inc(inner, self, key, channel, channels): try: while not channel.has_result(): for item in inner: inner.send(item) for _ in channel: pass yield inner, channel finally: channels.discard(channel) if self.counter.dec(key): callqueue.add(self._check, key) inner.finish(channel.result())
channels.discard(channel)
def _inc(inner, self, key, channel, channels): try: while not channel.has_result(): for item in inner: inner.send(item) for _ in channel: pass yield inner, channel finally: channels.discard(channel) if self.counter.dec(key): callqueue.add(self._check, key) inner.finish(channel.result())
inner.finish(channel.result())
def _inc(inner, self, key, channel, channels): try: while not channel.has_result(): for item in inner: inner.send(item) for _ in channel: pass yield inner, channel finally: channels.discard(channel) if self.counter.dec(key): callqueue.add(self._check, key) inner.finish(channel.result())
_, channels = self.tasks[key] channel = threado.Channel()
channel = self._inc(key) if task.has_result(): return task | channel
def inc(self, *args, **keys): key = self._key(*args, **keys)
return self._inc(key, channel, channels)
return channel
def inc(self, *args, **keys): key = self._key(*args, **keys)
while True: yield inner.sub(self.fetch_content(mailbox, self.filter)) yield inner, timer.sleep(self.poll_interval) finally: yield inner.thread(mailbox.close) finally:
inner.thread(mailbox.close) except: pass
def feed(inner, self): self.log.info("Connecting to IMAP server %r port %d", self.mail_server, self.mail_port) mailbox = yield inner.thread(imaplib.IMAP4_SSL, self.mail_server, self.mail_port)
top_header, _ = parts[0][0]
top_header = parts[0][0][0]
def fetch_mails(inner, self, filter): result, data = yield inner.sub(self.call("uid", "SEARCH", None, filter)) if not data or not data[0]: return
self.update(key, event.values())
self.update(key, event.values(key))
def __init__(self, *events): self._attrs = dict()
map(inner.send, self._augment_events(events, bites))
for event in self._augment_events(events, bites): inner.send(event)
def iteration(inner, self, ips): for ip in list(ips): values = self.cache.get(ip, None) if values is None: continue events = self.pending.pop(ip, ()) map(inner.send, self._augment_events(events, values)) ips.discard(ip) if not ips: return
pending = yield self.inner.sub(self.iteration(set(self.pending)))
yield inner.sub(self.iteration(set(self.pending)))
def wake(inner, self): sleeper = timer.sleep(self.throttle_time / 2.0)
body_rex_str = r"\s*\d+\s+\(UID %s BODY\[%s\]\s+" % (uid, section)
body_rex_str = r"\s*\d+\s+\((UID %s )?\s*BODY\[%s\]\s+" % (uid, section)
def get_header(inner, self, uid, section): body_rex_str = r"\s*\d+\s+\(UID %s BODY\[%s\]\s+" % (uid, section) body_rex = re.compile(body_rex_str, re.I) fetch = "(BODY.PEEK[%s])" % section result, data = yield inner.sub(self.call("uid", "FETCH", uid, fetch))
bot_name = params["bot_name"] self.log.info("Launching bot %r from module %r", bot_name, module)
name = params["bot_name"] self.log.info("Launching bot %r from module %r", name, module)
def signal_handler(sig, frame): sys.exit()
processes[startup] = process
processes[startup] = name, process
def signal_handler(sig, frame): sys.exit()
for startup, process in processes.items():
for startup, (_, process) in processes.items():
def signal_handler(sig, frame): sys.exit()
kill_processes(processes.values(), signal.SIGTERM)
kill_processes([x[1] for x in processes.values()], signal.SIGTERM)
def signal_handler(sig, frame): sys.exit()
for startup, process in list(processes.items()):
for startup, (name, process) in list(processes.items()):
def check_processes(self, processes): processes = dict(processes)
self.log.info("Bot %r exited with return value %d", startup.bot_name, retval)
self.log.info("Bot %r exited with return value %d", name, retval)
def check_processes(self, processes): processes = dict(processes)
"abusehelper.thirdparty", "abusehelper.year3000",
def generate_version(): base_path, _ = os.path.split(__file__) module_path = os.path.join(base_path, "abusehelper", "core") module_info = imp.find_module("version", [module_path]) version_module = imp.load_module("version", *module_info) version_module.generate(base_path) return version_module.version()
def default_configs(globals):
def default_configs(globals, set_names=True):
def default_configs(globals): for key, value in globals.items(): if isinstance(value, Config): if not hasattr(value, "name"): setattr(value, "name", key) yield value
if not hasattr(value, "name"):
if set_names and not hasattr(value, "name"):
def default_configs(globals): for key, value in globals.items(): if isinstance(value, Config): if not hasattr(value, "name"): setattr(value, "name", key) yield value
if configs is None:
if configs is None or not callable(configs):
def load_configs(module_name, config_func_name="configs"): module = load_module(module_name, False) configs = getattr(module, config_func_name, None) if configs is None: raise ImportError("no callable %r defined" % config_func_name) for value in configs(): yield value
for value in configs(): yield value
return configs()
def load_configs(module_name, config_func_name="configs"): module = load_module(module_name, False) configs = getattr(module, config_func_name, None) if configs is None: raise ImportError("no callable %r defined" % config_func_name) for value in configs(): yield value
service.session(None, **keys) yield inner.sub(service)
yield inner.sub(service.session(None, **keys) | service)
def _run(inner, self): ver_str = version.version_str() self.log.info("Starting service %r version %s", self.bot_name, ver_str) self.xmpp = yield inner.sub(self.xmpp_connect())
@threado.stream
@threado.stream_fast
def _guard(inner, self, channels): try: while True: yield inner for item in inner: inner.send(item) except: for channel in channels: channel.rethrow()