rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
log.debug('Caching trace to {0}'.format(dst))
|
log.debug('Caching {0}'.format(key_hr))
|
def cache_trace(dst, trace=None): if isinstance(dst, types.StringTypes): dst = unpack(b'!i', socket.inet_aton(dst))[0] cur = geoip_db.cursor() if trace is None: cur.execute('SELECT trace, ts FROM trace_cache WHERE dst = ?', (dst,)) # exit() try: trace, ts = next(cur) except StopIteration: raise KeyError if ts < time() - optz.trace_cache_obsoletion: raise KeyError(ts) return pickle.loads(bytes(trace)) else: log.debug('Caching trace to {0}'.format(dst)) cur.execute( 'INSERT OR REPLACE' ' INTO trace_cache (dst, trace, ts) VALUES (?, ?, ?)', (dst, buffer(pickle.dumps(trace, -1)), int(time())) ) # GC global _cache_gc_counter try: _cache_gc_counter() except StopIteration: cur.execute('SELECT COUNT(*) FROM trace_cache') log.debug('GC - trace_cache oversaturation: {0}'.format(clean_count)) clean_count = next(cur)[0] - optz.trace_cache_max_size if clean_count > 0: cur.execute( 'DELETE FROM trace_cache' ' ORDER BY ts LIMIT ?', (clean_count,) ) _cache_gc_counter.reset() except TypeError: _cache_gc_counter = countdown(optz.trace_cache_max_size / 10, 'trace_cache') geoip_db.commit() return trace
|
' INTO trace_cache (dst, trace, ts) VALUES (?, ?, ?)', (dst, buffer(pickle.dumps(trace, -1)), int(time())) )
|
' INTO object_cache (key, value, ts) VALUES (?, ?, ?)', (key, buffer(pickle.dumps(value, -1)), int(time())) )
|
def cache_trace(dst, trace=None): if isinstance(dst, types.StringTypes): dst = unpack(b'!i', socket.inet_aton(dst))[0] cur = geoip_db.cursor() if trace is None: cur.execute('SELECT trace, ts FROM trace_cache WHERE dst = ?', (dst,)) # exit() try: trace, ts = next(cur) except StopIteration: raise KeyError if ts < time() - optz.trace_cache_obsoletion: raise KeyError(ts) return pickle.loads(bytes(trace)) else: log.debug('Caching trace to {0}'.format(dst)) cur.execute( 'INSERT OR REPLACE' ' INTO trace_cache (dst, trace, ts) VALUES (?, ?, ?)', (dst, buffer(pickle.dumps(trace, -1)), int(time())) ) # GC global _cache_gc_counter try: _cache_gc_counter() except StopIteration: cur.execute('SELECT COUNT(*) FROM trace_cache') log.debug('GC - trace_cache oversaturation: {0}'.format(clean_count)) clean_count = next(cur)[0] - optz.trace_cache_max_size if clean_count > 0: cur.execute( 'DELETE FROM trace_cache' ' ORDER BY ts LIMIT ?', (clean_count,) ) _cache_gc_counter.reset() except TypeError: _cache_gc_counter = countdown(optz.trace_cache_max_size / 10, 'trace_cache') geoip_db.commit() return trace
|
cur.execute('SELECT COUNT(*) FROM trace_cache') log.debug('GC - trace_cache oversaturation: {0}'.format(clean_count)) clean_count = next(cur)[0] - optz.trace_cache_max_size
|
cur.execute('SELECT COUNT(*) FROM object_cache') log.debug('GC - object_cache oversaturation: {0}'.format(clean_count)) clean_count = next(cur)[0] - optz.cache_max_size
|
def cache_trace(dst, trace=None): if isinstance(dst, types.StringTypes): dst = unpack(b'!i', socket.inet_aton(dst))[0] cur = geoip_db.cursor() if trace is None: cur.execute('SELECT trace, ts FROM trace_cache WHERE dst = ?', (dst,)) # exit() try: trace, ts = next(cur) except StopIteration: raise KeyError if ts < time() - optz.trace_cache_obsoletion: raise KeyError(ts) return pickle.loads(bytes(trace)) else: log.debug('Caching trace to {0}'.format(dst)) cur.execute( 'INSERT OR REPLACE' ' INTO trace_cache (dst, trace, ts) VALUES (?, ?, ?)', (dst, buffer(pickle.dumps(trace, -1)), int(time())) ) # GC global _cache_gc_counter try: _cache_gc_counter() except StopIteration: cur.execute('SELECT COUNT(*) FROM trace_cache') log.debug('GC - trace_cache oversaturation: {0}'.format(clean_count)) clean_count = next(cur)[0] - optz.trace_cache_max_size if clean_count > 0: cur.execute( 'DELETE FROM trace_cache' ' ORDER BY ts LIMIT ?', (clean_count,) ) _cache_gc_counter.reset() except TypeError: _cache_gc_counter = countdown(optz.trace_cache_max_size / 10, 'trace_cache') geoip_db.commit() return trace
|
cur.execute( 'DELETE FROM trace_cache'
|
cur.execute( 'DELETE FROM object_cache'
|
def cache_trace(dst, trace=None): if isinstance(dst, types.StringTypes): dst = unpack(b'!i', socket.inet_aton(dst))[0] cur = geoip_db.cursor() if trace is None: cur.execute('SELECT trace, ts FROM trace_cache WHERE dst = ?', (dst,)) # exit() try: trace, ts = next(cur) except StopIteration: raise KeyError if ts < time() - optz.trace_cache_obsoletion: raise KeyError(ts) return pickle.loads(bytes(trace)) else: log.debug('Caching trace to {0}'.format(dst)) cur.execute( 'INSERT OR REPLACE' ' INTO trace_cache (dst, trace, ts) VALUES (?, ?, ?)', (dst, buffer(pickle.dumps(trace, -1)), int(time())) ) # GC global _cache_gc_counter try: _cache_gc_counter() except StopIteration: cur.execute('SELECT COUNT(*) FROM trace_cache') log.debug('GC - trace_cache oversaturation: {0}'.format(clean_count)) clean_count = next(cur)[0] - optz.trace_cache_max_size if clean_count > 0: cur.execute( 'DELETE FROM trace_cache' ' ORDER BY ts LIMIT ?', (clean_count,) ) _cache_gc_counter.reset() except TypeError: _cache_gc_counter = countdown(optz.trace_cache_max_size / 10, 'trace_cache') geoip_db.commit() return trace
|
except TypeError: _cache_gc_counter = countdown(optz.trace_cache_max_size / 10, 'trace_cache')
|
def cache_trace(dst, trace=None): if isinstance(dst, types.StringTypes): dst = unpack(b'!i', socket.inet_aton(dst))[0] cur = geoip_db.cursor() if trace is None: cur.execute('SELECT trace, ts FROM trace_cache WHERE dst = ?', (dst,)) # exit() try: trace, ts = next(cur) except StopIteration: raise KeyError if ts < time() - optz.trace_cache_obsoletion: raise KeyError(ts) return pickle.loads(bytes(trace)) else: log.debug('Caching trace to {0}'.format(dst)) cur.execute( 'INSERT OR REPLACE' ' INTO trace_cache (dst, trace, ts) VALUES (?, ?, ?)', (dst, buffer(pickle.dumps(trace, -1)), int(time())) ) # GC global _cache_gc_counter try: _cache_gc_counter() except StopIteration: cur.execute('SELECT COUNT(*) FROM trace_cache') log.debug('GC - trace_cache oversaturation: {0}'.format(clean_count)) clean_count = next(cur)[0] - optz.trace_cache_max_size if clean_count > 0: cur.execute( 'DELETE FROM trace_cache' ' ORDER BY ts LIMIT ?', (clean_count,) ) _cache_gc_counter.reset() except TypeError: _cache_gc_counter = countdown(optz.trace_cache_max_size / 10, 'trace_cache') geoip_db.commit() return trace
|
|
return trace
|
return value
|
def cache_trace(dst, trace=None): if isinstance(dst, types.StringTypes): dst = unpack(b'!i', socket.inet_aton(dst))[0] cur = geoip_db.cursor() if trace is None: cur.execute('SELECT trace, ts FROM trace_cache WHERE dst = ?', (dst,)) # exit() try: trace, ts = next(cur) except StopIteration: raise KeyError if ts < time() - optz.trace_cache_obsoletion: raise KeyError(ts) return pickle.loads(bytes(trace)) else: log.debug('Caching trace to {0}'.format(dst)) cur.execute( 'INSERT OR REPLACE' ' INTO trace_cache (dst, trace, ts) VALUES (?, ?, ?)', (dst, buffer(pickle.dumps(trace, -1)), int(time())) ) # GC global _cache_gc_counter try: _cache_gc_counter() except StopIteration: cur.execute('SELECT COUNT(*) FROM trace_cache') log.debug('GC - trace_cache oversaturation: {0}'.format(clean_count)) clean_count = next(cur)[0] - optz.trace_cache_max_size if clean_count > 0: cur.execute( 'DELETE FROM trace_cache' ' ORDER BY ts LIMIT ?', (clean_count,) ) _cache_gc_counter.reset() except TypeError: _cache_gc_counter = countdown(optz.trace_cache_max_size / 10, 'trace_cache') geoip_db.commit() return trace
|
try: return defer.succeed((ip, port, cache_trace(ip)))
|
cache = ft.partial(cache_object, ip, ext='trace') try: return defer.succeed((ip, port, cache()))
|
def trace(ip, port): try: return defer.succeed((ip, port, cache_trace(ip))) except KeyError: tracer = optz.trace_pool.run(_trace, ip) tracer.addCallback(ft.partial(cache_trace, ip)) tracer.addCallback(lambda res,ip=ip,port=port: (ip,port,res)) return tracer
|
tracer.addCallback(ft.partial(cache_trace, ip))
|
tracer.addCallback(cache)
|
def trace(ip, port): try: return defer.succeed((ip, port, cache_trace(ip))) except KeyError: tracer = optz.trace_pool.run(_trace, ip) tracer.addCallback(ft.partial(cache_trace, ip)) tracer.addCallback(lambda res,ip=ip,port=port: (ip,port,res)) return tracer
|
dst, '"{0}" color={1}'.format(ip, color) )))
|
dst, '"{0}" color={1}'.format(label, color) )))
|
def generate_overlay(self, traces): arcs, markers = list(), list() markers.append(' '.join(str_cat( optz.home_lat, optz.home_lon, '"{0}"'.format(optz.home_label) ))) for ip,port,trace in it.imap(op.itemgetter(1), it.ifilter(op.itemgetter(0), traces)): if not trace: log.debug('Dropped completely unresolved trace to {0}'.format(ip)) continue src = optz.home_lat, optz.home_lon color = '0x{0:06x}'.format(optz.svc_colors.get(port) or optz.svc_colors['default']) for dst in trace: arcs.append(' '.join(str_cat(src, dst, 'color={0}'.format(color)))) # spacing, thickness markers.append(' '.join(str_cat(dst, 'color={0}'.format(color)))) # radius, font, align src = dst markers.pop() # last marker will be replaced w/ labelled one markers.append(' '.join(str_cat( dst, '"{0}" color={1}'.format(ip, color) ))) # radius, font, align with open(optz.instance_arcs, 'wb') as dst: try: shutil.copyfileobj(open(optz.arc_base, 'rb'), dst) except (OSError, IOError): pass dst.write('\n' + '\n'.join(set(arcs)) + '\n') with open(optz.instance_markers, 'wb') as dst: try: shutil.copyfileobj(open(optz.marker_base, 'rb'), dst) except (OSError, IOError): pass dst.write('\n' + '\n'.join(set(markers)) + '\n') self.render()
|
parser.add_option('--trace-cache-obsoletion', action='store', default=3600, type='int', help='Time, after which cache entry considered obsolete (default: %default).') parser.add_option('--trace-cache-max-size', action='store', default=50000, type='int', help='Max number of cached traces to keep (default: %default).')
|
def geoip_db_var(var, cur=None): if cur is None: cur = geoip_db.cursor() cur.execute('SELECT val FROM meta WHERE var = ?', (var,)) try: return next(cur)[0] except StopIteration: raise KeyError(var)
|
|
geoip_db_ver = 2 if os.path.exists(geoip_db_path) and optz.maxmind_db: ts = os.stat(optz.maxmind_db).st_mtime
|
geoip_db_ver = 3 if os.path.exists(geoip_db_path):
|
def geoip_db_var(var, cur=None): if cur is None: cur = geoip_db.cursor() cur.execute('SELECT val FROM meta WHERE var = ?', (var,)) try: return next(cur)[0] except StopIteration: raise KeyError(var)
|
ts_chk = geoip_db_var('mmdb_timestamp', cur) + 1 if ts_chk < ts: log.debug( 'MaxMind archive seem to be newer' ' than sqlite db ({0} > {1})'.format(ts_chk, ts) ) raise KeyError ts_chk = geoip_db_var('db_version', cur) if ts_chk < geoip_db_ver: build_geoip_db(from_version=ts_chk, link=link, cur=cur)
|
if optz.maxmind_db: ts = os.stat(optz.maxmind_db).st_mtime ts_chk = geoip_db_var('mmdb_timestamp', cur) + 1 if ts_chk < ts: log.debug( 'MaxMind archive seem to be newer' ' than sqlite db ({0} > {1})'.format(ts_chk, ts) ) raise KeyError
|
def geoip_db_var(var, cur=None): if cur is None: cur = geoip_db.cursor() cur.execute('SELECT val FROM meta WHERE var = ?', (var,)) try: return next(cur)[0] except StopIteration: raise KeyError(var)
|
else: render_task = LoopingCall(optz.refresh, planetscape.snap)
|
else: render_task = LoopingCall(planetscape.snap) render_task.start(optz.refresh) log.debug('Starting eventloop')
|
def geoip_db_var(var, cur=None): if cur is None: cur = geoip_db.cursor() cur.execute('SELECT val FROM meta WHERE var = ?', (var,)) try: return next(cur)[0] except StopIteration: raise KeyError(var)
|
def build_geoip_db(spool_path, mmdb_zip, from_version=0, link=None, cur=None):
|
def build_geoip_db(geoip_db_path, spool_path, mmdb_zip, from_version=0, link=None, cur=None):
|
def build_geoip_db(spool_path, mmdb_zip, from_version=0, link=None, cur=None): if from_version < 1: # i.e. from scratch ## Unzip CSVs unzip_root = os.path.join(spool_path, 'mmdb_tmp') log.debug('Unpacking MaxMind db (to: {0})'.format(unzip_root)) if os.path.exists(unzip_root): shutil.rmtree(unzip_root) os.mkdir(unzip_root) from subprocess import Popen, PIPE Popen(['unzip', '-qq', mmdb_zip], cwd=unzip_root).wait() from glob import glob csvs = glob(os.path.join(unzip_root, '*', '*.csv')) csv_blocks, = filter(lambda name: 'Blocks' in name, csvs) csv_loc, = filter(lambda name: 'Location' in name, csvs) log.debug('Unpacked blocks: {0}, blocks-loc: {1}'.format(csv_blocks, csv_loc)) ## Read field headers csv_blocks, csv_loc = it.imap(open, (csv_blocks, csv_loc)) csv_blocks.readline(), csv_loc.readline() csv_blocks_key, csv_loc_key = ( csv.readline().strip().split(',') for csv in (csv_blocks, csv_loc) ) csv_blocks_key = op.itemgetter(*it.imap( csv_blocks_key.index, ('startIpNum', 'endIpNum', 'locId') )) csv_loc_key = op.itemgetter(*it.imap( csv_loc_key.index, ('locId', 'latitude', 'longitude') )) ## Unlink paths (shouldn't be adressed again) shutil.rmtree(unzip_root) ## Init src/dst import csv csv_blocks, csv_loc = it.imap(ft.partial( csv.reader, delimiter=b',', quoting=csv.QUOTE_ALL ), (csv_blocks, csv_loc)) log.debug('Building sqlite geoip db cache') if link: link.close() link = sqlite3.connect(geoip_db_path) cur = link.cursor() log.debug('Initializing tables') cur.execute( 'CREATE TABLE ip_blocks' ' (id INTEGER PRIMARY KEY AUTOINCREMENT,' ' ip_min INT, ip_max INT, lat FLOAT, lon FLOAT)' ) loc_id = dict() # Building/querying same index in sqlite takes a lot more time, # downside is that py-based one would have to fit into RAM. # Up to 50M RAM on my machine, but minus minute or two from the process. log.debug('Building loc_id index') for line in it.imap(csv_loc_key, csv_loc): loc_id[line[0]] = line[1:] log.debug('Filling lat/lon for ip ranges') for line in it.imap(csv_blocks_key, csv_blocks): loc = loc_id.get(line[2]) if not loc: log.debug('Unable to find location for loc_id {0}'.format(line[2])) continue cur.execute( 'INSERT INTO ip_blocks' ' (ip_min, ip_max, lat, lon) VALUES (?, ?, ?, ?)', line[:2] + loc ) log.debug('Dropping overlapping intervals') # Overlapping intervals don't make any sense in this context, # plus it's much easier to work w/ non-overlapping stuff (no need for interval trees). # Should be pretty fast and non-memory-hungry. cur.execute('SELECT id, ip_min, ip_max, lat, lon FROM ip_blocks ORDER BY ip_min') prev_rowid = prev_ip_max = prev_loc = None for rowid, ip_min, ip_max, lat, lon in cur: if prev_rowid is not None and prev_ip_max >= ip_min: cur.execute('UPDATE ip_blocks SET ip_max = ? WHERE id = ?', (ip_min-1, prev_rowid)) if prev_ip_max > ip_max: # one interval is enclosed into another, restore the missing "tail" cur.execute( 'INSERT INTO ip_blocks' ' (ip_min, ip_max, lat, lon) VALUES (?, ?, ?, ?)', (ip_max+1, prev_ip_max) + prev_loc ) prev_rowid, prev_ip_max, prev_loc = rowid, ip_max, (lat, lon) log.debug('Adding indexes') cur.execute('CREATE UNIQUE INDEX ip_from ON ip_blocks (ip_min)') log.debug('Adding metadata table') cur.execute('CREATE TABLE meta (var VARCHAR(15), val FLOAT)') cur.execute('CREATE UNIQUE INDEX meta_var ON meta (var)') cur.execute("INSERT INTO meta (var, val) VALUES ('mmdb_timestamp', ?)", (time(),)) else: if not link: link = sqlite3.connect(geoip_db_path) if not cur else cur.connection if not cur: cur = link.cursor() if from_version < 2: cur.execute('CREATE TABLE trace_cache (dst INT PRIMARY KEY, ts INT, trace BLOB)') cur.execute('CREATE INDEX trace_cache_ts ON trace_cache (ts)') if from_version < 3: cur.execute('DROP TABLE trace_cache') cur.execute('CREATE TABLE object_cache (key BLOB PRIMARY KEY, value BLOB, ts INT)') cur.execute('CREATE INDEX object_cache_ts ON object_cache (ts)') log.debug('Updating db version to {0}'.format(geoip_db_version)) cur.execute( 'INSERT OR REPLACE INTO meta' " (var, val) VALUES ('db_version', ?)", (geoip_db_version,) ) log.debug('Syncing database') link.commit()
|
import sqlite3
|
def initialize(optz): 'Prepare necessary paths, locks and geoip_db. Must be run before event-loop.' optz = AttrDict._from_optz(optz) ### Logging logging.basicConfig( level=logging.DEBUG if optz.debug else logging.WARNING ) ### Check/expand paths os.umask(077) # no need to share cache w/ someone if optz.maxmind_db: from glob import iglob try: optz.maxmind_db = os.path.abspath(sorted(iglob(optz.maxmind_db))[-1]) # latest one except IndexError: log.warn('Unable to stat MaxMind GeoIP database: {0}'.format(optz.maxmind_db)) optz.maxmind_db = None log.debug('Globbed MaxMind db path: {0}'.format(optz.maxmind_db)) optz.spool_path = os.path.abspath(optz.spool_path) if not os.path.exists(optz.spool_path): log.debug('Creating spool path: {0}'.format(optz.spool_path)) os.mkdir(optz.spool_path) os.chdir(optz.spool_path) ### Instance lock optz.display = (optz.display or os.getenv('DISPLAY') or '').lstrip(':') if not optz.display: parser.error('Unable to determine X display for instance, try setting it explicitly') elif not re.match('\d+(\.\d+)?', optz.display): parser.error('Incorrect X display specification, expected something like ":1.0"') optz.instance = 'planetscape_{0}'.format(optz.display) import fcntl optz.instance_lock = open(os.path.join(optz.spool_path, '{0}.lock'.format(optz.instance)), 'w+') try: fcntl.flock(optz.instance_lock, fcntl.LOCK_EX | fcntl.LOCK_NB) except (OSError, IOError): parser.error('Unable to secure instance lock for display "{0}"'.format(optz.display)) else: optz.instance_lock.seek(0, os.SEEK_SET) optz.instance_lock.truncate() optz.instance_lock.write(str(os.getpid()) + '\n') optz.instance_lock.flush() ### GeoIP db management import sqlite3 geoip_db_path = os.path.join(optz.spool_path, 'geoip.sqlite') geoip_db_build = ft.partial(build_geoip_db, optz.spool_path, optz.maxmind_db) ## Path/mtime/schema version checks if os.path.exists(geoip_db_path): with sqlite3.connect(geoip_db_path) as link: with closing(link.cursor()) as cur: try: if optz.maxmind_db: ts = os.stat(optz.maxmind_db).st_mtime ts_chk = geoip_db_var(cur, 'mmdb_timestamp') + 1 # for rounding quirks if ts_chk < ts: log.debug( 'MaxMind archive seem to be newer' ' than sqlite db ({0} > {1})'.format(ts_chk, ts) ) raise KeyError except (KeyError, sqlite3.OperationalError): log.debug('Dropping sqlite geoip db cache') os.unlink(geoip_db_path) ts_chk = geoip_db_var(cur, 'db_version') if ts_chk < geoip_db_version: geoip_db_build(from_version=ts_chk, link=link, cur=cur) if optz.discard_cache: cur.execute('DELETE FROM object_cache') link.commit() ## (Re)Build, if necessary if not os.path.exists(geoip_db_path): if not optz.maxmind_db or not os.path.exists(optz.maxmind_db): parser.error('No path to MaxMind GeoIP database specified' ' and no geoip data cached, one of these issues should be addressed.') geoip_db_build() ## Maps if optz.get('image'): try: if isinstance(optz.image, types.StringTypes): raise ValueError img_day, img_night = optz.image except ValueError: img_day = img_night = optz.image img_path = os.path.join(optz.spool_path, 'images') if not os.path.exists(img_path): os.mkdir(img_path) img_day_src, img_day = img_day, os.path.basename(img_day) shutil.copy(img_day_src, os.path.join(img_path, img_day)) img_night_src, img_night = img_night, os.path.basename(img_night) shutil.copy(img_night_src, os.path.join(img_path, img_night)) else: img_day, img_night = 'earth.jpg', 'night.jpg' ## Static configuration file optz.instance_conf = os.path.join(optz.spool_path, '{0}.conf'.format(optz.instance)) for k in 'arcs', 'markers': path = os.path.join(optz.spool_path, k) if not os.path.exists(path): os.mkdir(path) setattr(optz, 'instance_{0}'.format(k), os.path.join(path, optz.instance)) del k, path with open(optz.instance_conf, 'wb') as conf: conf.write('\n'.join([ '[default]', 'marker_color=red', 'shade=30', 'text_color={255,0,0}', 'twilight=6', '[earth]', '"Earth"', 'color={28, 82, 110}', 'image={0}'.format(img_day), 'night_map={0}'.format(img_night), 'arc_file={0}'.format(os.path.basename(optz.instance_arcs)), 'marker_file={0}'.format(os.path.basename(optz.instance_markers)), 'marker_fontsize=10' ])+'\n') ### Home location if not optz.home_lat and optz.home_lon and (optz.home_lat or optz.home_lon): parser.error('Either both latitude/longitude options should be specified or neither.') if not optz.home_lat or not optz.home_lon: log.debug('Determining home-location') from BeautifulSoup import BeautifulSoup from urllib2 import urlopen, URLError, HTTPError socket_to = socket.getdefaulttimeout() socket.setdefaulttimeout(10) try: soup = BeautifulSoup(urlopen( 'http://www.geobytes.com/' 'IpLocator.htm?GetLocation&template=php3.txt' ).read()) optz.home_lat = soup.find('meta', dict(name='latitude'))['content'] optz.home_lon = soup.find('meta', dict(name='longitude'))['content'] except (TypeError, KeyError, URLError, HTTPError): parser.error('Unable to determine current location via online lookup') finally: socket.setdefaulttimeout(socket_to) log.debug('Auto-detected home-location: {0} {1}'.format(optz.home_lat, optz.home_lon)) ### Netstat/trace/xplanet options # I don't use raw /proc/net/tcp here because it does not contain v6-mapped # ipv4's, although I guess these should be available somewhere else try: optz.ns_tool = ft.partial( proc_skel, **dict(it.izip((b'protocol', b'command'), dict( ss = (SS, (optz.ns_tool_binary or '/sbin/ss', '-tn')) )[optz.ns_tool])) ) except KeyError: parser.error(( 'Netstat-like command {0} protocol' ' is not implemented (yet?)' ).format(optz.ns_tool)) try: optz.trace_tool = ft.partial( proc_skel, **dict(it.izip((b'protocol', b'command'), dict( mtr = (MTR, lambda ip: ( optz.trace_tool_binary or '/usr/sbin/mtr', '-c{0}'.format(optz.trace_count), '-r', '--raw', '--no-dns', ip )) )[optz.trace_tool])) ) except KeyError: parser.error(( 'Trace command {0} protocol' ' is not implemented (yet?)' ).format(optz.trace_tool)) if optz.oneshot: optz.xplanet_args += ['-num_times', '1'] optz.xplanet = ft.partial( proc_skel, protocol=XPlanet, command=list(str_cat( optz.xplanet, '-searchdir', optz.spool_path, '-config', os.path.basename(optz.instance_conf), '-latitude', optz.home_lat, '-longitude', optz.home_lon, optz.xplanet_args )) ) ### Service colors/names optz.svc_colors = { 'default': 0xffffff, # basic stuff 21: 0x00ffff, # ftp 22: 0xffff00, # ssh 23: 0xffff00, # telnet 53: 0x99ff00, # dns 79: 0x0099ff, # finger # web 80: 0x9900ff, # http 443: 0x9900ff, # https 3128: 0x9900ff, # http proxy # mail stuff 25: 0xff00ff, # smtp 110: 0xff9900, # pop3 119: 0xff9900, # nntp 143: 0xff9900, # imap 993: 0xff9900, # imaps 995: 0xff9900, # pop3s # IM 5190: 0x009999, # AIM 5222: 0x009999, # XMPP (Jabber) 5223: 0x009999, # XMPP with old-fashioned SSL (GMail XMPP) # others 873: 0x999900, # rsync 6667: 0x990099, # irc 7000: 0x990099 # ircs } optz.svc_names = dict() for port in optz.svc_colors.iterkeys(): try: optz.svc_names[port] = socket.getservbyport(port) except (TypeError, socket.error): pass ### Parametrized calls optz.geoip_db = sqlite3.connect(geoip_db_path) optz.cache = ft.partial( cache_object, optz.geoip_db, obsoletion=optz.cache_obsoletion, max_size=optz.cache_max_size ) optz.trace = ft.partial( trace, cache=optz.cache, trace_pool = defer.DeferredSemaphore(optz.trace_pool_size), trace_tool = lambda ip, trace=optz.trace_tool, resolve=ft.partial( ips_to_locs, cur=optz.geoip_db.cursor() ): trace(ip).addCallback(resolve) ) optz.ptr_lookup = ft.partial(ptr_lookup, cache=optz.cache) return optz
|
|
geoip_db_build = ft.partial(build_geoip_db, optz.spool_path, optz.maxmind_db)
|
geoip_db_build = ft.partial( build_geoip_db, geoip_db_path, optz.spool_path, optz.maxmind_db )
|
def initialize(optz): 'Prepare necessary paths, locks and geoip_db. Must be run before event-loop.' optz = AttrDict._from_optz(optz) ### Logging logging.basicConfig( level=logging.DEBUG if optz.debug else logging.WARNING ) ### Check/expand paths os.umask(077) # no need to share cache w/ someone if optz.maxmind_db: from glob import iglob try: optz.maxmind_db = os.path.abspath(sorted(iglob(optz.maxmind_db))[-1]) # latest one except IndexError: log.warn('Unable to stat MaxMind GeoIP database: {0}'.format(optz.maxmind_db)) optz.maxmind_db = None log.debug('Globbed MaxMind db path: {0}'.format(optz.maxmind_db)) optz.spool_path = os.path.abspath(optz.spool_path) if not os.path.exists(optz.spool_path): log.debug('Creating spool path: {0}'.format(optz.spool_path)) os.mkdir(optz.spool_path) os.chdir(optz.spool_path) ### Instance lock optz.display = (optz.display or os.getenv('DISPLAY') or '').lstrip(':') if not optz.display: parser.error('Unable to determine X display for instance, try setting it explicitly') elif not re.match('\d+(\.\d+)?', optz.display): parser.error('Incorrect X display specification, expected something like ":1.0"') optz.instance = 'planetscape_{0}'.format(optz.display) import fcntl optz.instance_lock = open(os.path.join(optz.spool_path, '{0}.lock'.format(optz.instance)), 'w+') try: fcntl.flock(optz.instance_lock, fcntl.LOCK_EX | fcntl.LOCK_NB) except (OSError, IOError): parser.error('Unable to secure instance lock for display "{0}"'.format(optz.display)) else: optz.instance_lock.seek(0, os.SEEK_SET) optz.instance_lock.truncate() optz.instance_lock.write(str(os.getpid()) + '\n') optz.instance_lock.flush() ### GeoIP db management import sqlite3 geoip_db_path = os.path.join(optz.spool_path, 'geoip.sqlite') geoip_db_build = ft.partial(build_geoip_db, optz.spool_path, optz.maxmind_db) ## Path/mtime/schema version checks if os.path.exists(geoip_db_path): with sqlite3.connect(geoip_db_path) as link: with closing(link.cursor()) as cur: try: if optz.maxmind_db: ts = os.stat(optz.maxmind_db).st_mtime ts_chk = geoip_db_var(cur, 'mmdb_timestamp') + 1 # for rounding quirks if ts_chk < ts: log.debug( 'MaxMind archive seem to be newer' ' than sqlite db ({0} > {1})'.format(ts_chk, ts) ) raise KeyError except (KeyError, sqlite3.OperationalError): log.debug('Dropping sqlite geoip db cache') os.unlink(geoip_db_path) ts_chk = geoip_db_var(cur, 'db_version') if ts_chk < geoip_db_version: geoip_db_build(from_version=ts_chk, link=link, cur=cur) if optz.discard_cache: cur.execute('DELETE FROM object_cache') link.commit() ## (Re)Build, if necessary if not os.path.exists(geoip_db_path): if not optz.maxmind_db or not os.path.exists(optz.maxmind_db): parser.error('No path to MaxMind GeoIP database specified' ' and no geoip data cached, one of these issues should be addressed.') geoip_db_build() ## Maps if optz.get('image'): try: if isinstance(optz.image, types.StringTypes): raise ValueError img_day, img_night = optz.image except ValueError: img_day = img_night = optz.image img_path = os.path.join(optz.spool_path, 'images') if not os.path.exists(img_path): os.mkdir(img_path) img_day_src, img_day = img_day, os.path.basename(img_day) shutil.copy(img_day_src, os.path.join(img_path, img_day)) img_night_src, img_night = img_night, os.path.basename(img_night) shutil.copy(img_night_src, os.path.join(img_path, img_night)) else: img_day, img_night = 'earth.jpg', 'night.jpg' ## Static configuration file optz.instance_conf = os.path.join(optz.spool_path, '{0}.conf'.format(optz.instance)) for k in 'arcs', 'markers': path = os.path.join(optz.spool_path, k) if not os.path.exists(path): os.mkdir(path) setattr(optz, 'instance_{0}'.format(k), os.path.join(path, optz.instance)) del k, path with open(optz.instance_conf, 'wb') as conf: conf.write('\n'.join([ '[default]', 'marker_color=red', 'shade=30', 'text_color={255,0,0}', 'twilight=6', '[earth]', '"Earth"', 'color={28, 82, 110}', 'image={0}'.format(img_day), 'night_map={0}'.format(img_night), 'arc_file={0}'.format(os.path.basename(optz.instance_arcs)), 'marker_file={0}'.format(os.path.basename(optz.instance_markers)), 'marker_fontsize=10' ])+'\n') ### Home location if not optz.home_lat and optz.home_lon and (optz.home_lat or optz.home_lon): parser.error('Either both latitude/longitude options should be specified or neither.') if not optz.home_lat or not optz.home_lon: log.debug('Determining home-location') from BeautifulSoup import BeautifulSoup from urllib2 import urlopen, URLError, HTTPError socket_to = socket.getdefaulttimeout() socket.setdefaulttimeout(10) try: soup = BeautifulSoup(urlopen( 'http://www.geobytes.com/' 'IpLocator.htm?GetLocation&template=php3.txt' ).read()) optz.home_lat = soup.find('meta', dict(name='latitude'))['content'] optz.home_lon = soup.find('meta', dict(name='longitude'))['content'] except (TypeError, KeyError, URLError, HTTPError): parser.error('Unable to determine current location via online lookup') finally: socket.setdefaulttimeout(socket_to) log.debug('Auto-detected home-location: {0} {1}'.format(optz.home_lat, optz.home_lon)) ### Netstat/trace/xplanet options # I don't use raw /proc/net/tcp here because it does not contain v6-mapped # ipv4's, although I guess these should be available somewhere else try: optz.ns_tool = ft.partial( proc_skel, **dict(it.izip((b'protocol', b'command'), dict( ss = (SS, (optz.ns_tool_binary or '/sbin/ss', '-tn')) )[optz.ns_tool])) ) except KeyError: parser.error(( 'Netstat-like command {0} protocol' ' is not implemented (yet?)' ).format(optz.ns_tool)) try: optz.trace_tool = ft.partial( proc_skel, **dict(it.izip((b'protocol', b'command'), dict( mtr = (MTR, lambda ip: ( optz.trace_tool_binary or '/usr/sbin/mtr', '-c{0}'.format(optz.trace_count), '-r', '--raw', '--no-dns', ip )) )[optz.trace_tool])) ) except KeyError: parser.error(( 'Trace command {0} protocol' ' is not implemented (yet?)' ).format(optz.trace_tool)) if optz.oneshot: optz.xplanet_args += ['-num_times', '1'] optz.xplanet = ft.partial( proc_skel, protocol=XPlanet, command=list(str_cat( optz.xplanet, '-searchdir', optz.spool_path, '-config', os.path.basename(optz.instance_conf), '-latitude', optz.home_lat, '-longitude', optz.home_lon, optz.xplanet_args )) ) ### Service colors/names optz.svc_colors = { 'default': 0xffffff, # basic stuff 21: 0x00ffff, # ftp 22: 0xffff00, # ssh 23: 0xffff00, # telnet 53: 0x99ff00, # dns 79: 0x0099ff, # finger # web 80: 0x9900ff, # http 443: 0x9900ff, # https 3128: 0x9900ff, # http proxy # mail stuff 25: 0xff00ff, # smtp 110: 0xff9900, # pop3 119: 0xff9900, # nntp 143: 0xff9900, # imap 993: 0xff9900, # imaps 995: 0xff9900, # pop3s # IM 5190: 0x009999, # AIM 5222: 0x009999, # XMPP (Jabber) 5223: 0x009999, # XMPP with old-fashioned SSL (GMail XMPP) # others 873: 0x999900, # rsync 6667: 0x990099, # irc 7000: 0x990099 # ircs } optz.svc_names = dict() for port in optz.svc_colors.iterkeys(): try: optz.svc_names[port] = socket.getservbyport(port) except (TypeError, socket.error): pass ### Parametrized calls optz.geoip_db = sqlite3.connect(geoip_db_path) optz.cache = ft.partial( cache_object, optz.geoip_db, obsoletion=optz.cache_obsoletion, max_size=optz.cache_max_size ) optz.trace = ft.partial( trace, cache=optz.cache, trace_pool = defer.DeferredSemaphore(optz.trace_pool_size), trace_tool = lambda ip, trace=optz.trace_tool, resolve=ft.partial( ips_to_locs, cur=optz.geoip_db.cursor() ): trace(ip).addCallback(resolve) ) optz.ptr_lookup = ft.partial(ptr_lookup, cache=optz.cache) return optz
|
print "Generated prefs" print "URL", settings.url
|
def main(): settings = preferences.Preferences() print "Generated prefs" print "URL", settings.url dialog = preferences.ConfigDialog(None, "settings", settings) print "Creating dialog" dialog.show() app.exec_()
|
|
print "Creating dialog"
|
def main(): settings = preferences.Preferences() print "Generated prefs" print "URL", settings.url dialog = preferences.ConfigDialog(None, "settings", settings) print "Creating dialog" dialog.show() app.exec_()
|
|
if st.getPlayer().isNoble() and count > REQUESTED_AMOUNT:
|
if st.getPlayer().isNoble() and count >= REQUESTED_AMOUNT:
|
def onEvent(self,event,st): htmltext = "<html><head><body>I have nothing to say you</body></html>" count=st.getQuestItemsCount(REQUESTED_ITEM) if event == "66667-clanOk.htm" : if st.getPlayer().isClanLeader() and st.getPlayer().getClan().getLevel()<8: if st.getPlayer().isNoble() and count > REQUESTED_AMOUNT: htmltext=event st.getPlayer().getClan().changeLevel(8) st.playSound("ItemSound.quest_finish") st.takeItems(REQUESTED_ITEM,REQUESTED_AMOUNT) else : htmltext="66667-no_clan.htm" st.exitQuest(1) else : htmltext="66667-no_clan.htm" st.exitQuest(1) elif event == "66667-repOk.htm" : if st.getPlayer().isClanLeader() and st.getPlayer().getClan().getLevel() >= 5 and st.getPlayer().getClan().getReputationScore() < NEW_REP_SCORE : if st.getPlayer().isNoble() and count > REQUESTED_AMOUNT: htmltext=event st.getPlayer().getClan().setReputationScore(NEW_REP_SCORE, true); st.playSound("ItemSound.quest_finish") st.takeItems(REQUESTED_ITEM,REQUESTED_AMOUNT) else : htmltext="66667-no_points.htm" st.exitQuest(1) else : htmltext="66667-no_points.htm" st.exitQuest(1) return htmltext
|
st.getPlayer().getClan().setReputationScore(NEW_REP_SCORE, true);
|
st.getPlayer().getClan().setReputationScore(NEW_REP_SCORE, 1);
|
def onEvent(self,event,st): htmltext = "<html><head><body>I have nothing to say you</body></html>" count=st.getQuestItemsCount(REQUESTED_ITEM) if event == "66667-clanOk.htm" : if st.getPlayer().isClanLeader() and st.getPlayer().getClan().getLevel()<8: if st.getPlayer().isNoble() and count > REQUESTED_AMOUNT: htmltext=event st.getPlayer().getClan().changeLevel(8) st.playSound("ItemSound.quest_finish") st.takeItems(REQUESTED_ITEM,REQUESTED_AMOUNT) else : htmltext="66667-no_clan.htm" st.exitQuest(1) else : htmltext="66667-no_clan.htm" st.exitQuest(1) elif event == "66667-repOk.htm" : if st.getPlayer().isClanLeader() and st.getPlayer().getClan().getLevel() >= 5 and st.getPlayer().getClan().getReputationScore() < NEW_REP_SCORE : if st.getPlayer().isNoble() and count > REQUESTED_AMOUNT: htmltext=event st.getPlayer().getClan().setReputationScore(NEW_REP_SCORE, true); st.playSound("ItemSound.quest_finish") st.takeItems(REQUESTED_ITEM,REQUESTED_AMOUNT) else : htmltext="66667-no_points.htm" st.exitQuest(1) else : htmltext="66667-no_points.htm" st.exitQuest(1) return htmltext
|
htmltext = "<html><head><body>This quest has already been completed.</body></html>"
|
htmltext = "<html><head><body>This quest have already been completed.</body></html>"
|
def onTalk (self,npc,player): htmltext = "<html><head><body>I have nothing to say you</body></html>" st = player.getQuestState(qn) if not st : return htmltext npcId = npc.getNpcId() id = st.getState() if id == CREATED : htmltext="66667-1.htm" elif id == COMPLETED : htmltext = "<html><head><body>This quest has already been completed.</body></html>" else : st.exitQuest(1) return htmltext
|
except getopt.GetoptError:
|
except getopt.GetoptError, e:
|
def main(): try: opts, args = getopt.getopt(sys.argv[1:], "l", ["list"]) except getopt.GetoptError: usage(e) if not args: usage() srcpath = args[0] if not isdir(srcpath): fatal("no such directory `%s'" % srcpath) for opt, val in opts: if opt == '-h': usage() if opt in ('-l', '--list'): return list(srcpath) try: version = args[1] except IndexError: version = None seek(srcpath, version)
|
commits = self._getoutput("git-rev-list", "--all").split("\n")
|
branch = basename(self.verseek_head or self.head) commits = self._getoutput("git-rev-list", branch).split("\n")
|
def list(self): commits = self._getoutput("git-rev-list", "--all").split("\n") return self._getoutput("autoversion", *commits).split("\n")
|
lines = (line.strip() for line in file(path).readlines())
|
lines = (line.rstrip() for line in file(path).readlines() if not line.startswith(" "))
|
def parse_control(path): lines = (line.strip() for line in file(path).readlines()) return dict([ re.split("\s*:\s*", line, 1) for line in lines if line and not line.startswith(" ") ])
|
if line and not line.startswith(" ") ])
|
if line ])
|
def parse_control(path): lines = (line.strip() for line in file(path).readlines()) return dict([ re.split("\s*:\s*", line, 1) for line in lines if line and not line.startswith(" ") ])
|
if version and deb_get_version(path) != version:
|
if version and deb_get_version(self.path) != version:
|
def seek(self, version=None): if version and deb_get_version(path) != version: raise Error("can't seek to nonexistent version `%s'" % version)
|
self._is_changed = self.check_real_change(instance, mapper, connection) if not self.revisioning_disabled(instance) and self._is_changed:
|
self._is_changed[instance] = self.check_real_change(instance, mapper, connection) if not self.revisioning_disabled(instance) and self._is_changed[instance]:
|
def before_update(self, mapper, connection, instance): self._is_changed = self.check_real_change(instance, mapper, connection) if not self.revisioning_disabled(instance) and self._is_changed: logger.debug('before_update: %s' % instance) self.set_revision(instance) self._is_changed = self.check_real_change(instance, mapper, connection) return EXT_CONTINUE
|
self._is_changed = self.check_real_change(instance, mapper, connection)
|
self._is_changed[instance] = self.check_real_change( instance, mapper, connection)
|
def before_update(self, mapper, connection, instance): self._is_changed = self.check_real_change(instance, mapper, connection) if not self.revisioning_disabled(instance) and self._is_changed: logger.debug('before_update: %s' % instance) self.set_revision(instance) self._is_changed = self.check_real_change(instance, mapper, connection) return EXT_CONTINUE
|
self._is_changed = self.check_real_change(instance, mapper, connection) if not self.revisioning_disabled(instance) and self._is_changed:
|
self._is_changed[instance] = self.check_real_change(instance, mapper, connection) if not self.revisioning_disabled(instance) and self._is_changed[instance]:
|
def before_insert(self, mapper, connection, instance): self._is_changed = self.check_real_change(instance, mapper, connection) if not self.revisioning_disabled(instance) and self._is_changed: logger.debug('before_insert: %s' % instance) self.set_revision(instance) return EXT_CONTINUE
|
if not self.revisioning_disabled(instance) and self._is_changed:
|
if not self.revisioning_disabled(instance) and self._is_changed[instance]:
|
def after_update(self, mapper, connection, instance): if not self.revisioning_disabled(instance) and self._is_changed: logger.debug('after_update: %s' % instance) self.make_revision(instance, mapper, connection) return EXT_CONTINUE
|
if not self.revisioning_disabled(instance) and self._is_changed:
|
if not self.revisioning_disabled(instance) and self._is_changed[instance]:
|
def after_insert(self, mapper, connection, instance): if not self.revisioning_disabled(instance) and self._is_changed: logger.debug('after_insert: %s' % instance) self.make_revision(instance, mapper, connection) return EXT_CONTINUE
|
print get_editor_name_as_list()
|
def get_string_from_editor(base_string, prefix='idli-'): tf = tempfile.NamedTemporaryFile('w+b',prefix=prefix) tf.write(base_string) tf.seek(0) print get_editor_name_as_list() exit_status = subprocess.call(get_editor_name_as_list() + [tf.name]) result = tf.read() return (result, exit_status)
|
|
Virtual Spectrophotometric Measurements for Biologically and Physically-Based Rendering The Visual Computer, Volume 17, Issue 8, pp. 506-518, 2001.
|
Virtual spectrophotometric Measurements for biologically and physically-based rendering \textit{The Visual Computer}, Volume 17, Issue 8, pp. 506-518, 2001.
|
def latexBody(self): return r""" These are the results of your model run of \textbf{ABM-B} for the Natural Phenomenon Simulation Group (NPSG) at the University of Waterloo.
|
Remote Sensing of Environment, 100(3):335-347, 2006
|
\textit{Remote Sensing of Environment}, 100(3):335-347, 2006
|
def latexBody(self): return r""" These are the results of your model run of \textbf{ABM-B} for the Natural Phenomenon Simulation Group (NPSG) at the University of Waterloo.
|
An investigation on sieve and detour effects affecting the interaction of collimated and diffuse infrared radiation (750 to 2500 nm) with plant leaves IEEE Transactions on Geoscience and Remote Sensing, 45 (8):2593-2599, 2007
|
An investigation on sieve and detour effects affecting the interaction of collimated and diffuse infrared radiation (750 to 2500 nm) with plant leaves \textit{IEEE Transactions on Geoscience and Remote Sensing}, 45 (8):2593-2599, 2007
|
def latexBody(self): return r""" These are the results of your model run of \textbf{ABM-B} for the Natural Phenomenon Simulation Group (NPSG) at the University of Waterloo.
|
Improving the Reliability/Cost Ratio of Goniophotometric Comparisons Journal of Graphics Tools, Volume 9, Number 3, pp. 1-20, 2004.
|
Improving the reliability/cost ratio of goniophotometric comparisons \textit{Journal of Graphics Tools}, Volume 9, Number 3, pp. 1-20, 2004.
|
def latexBody(self): return r""" These are the results of your model run of \textbf{ABM-B} for the Natural Phenomenon Simulation Group (NPSG) at the University of Waterloo.
|
def executableParameters(self): return [ "-d", os.path.join(os.path.dirname(self.executable), "data"), "-n", str(self.nSamples.value), "-p", str(self.angleOfIncidence.value), "-s", str(5), "-w", str(self.wavelengths.value[0]), "-e", str(self.wavelengths.value[1]), "sample.json", "spectral_distribution.csv" ]
|
def executableParameters(self): return [ "-d", os.path.join(os.path.dirname(self.executable), "data"), "-n", str(self.nSamples.value), "-p", str(self.angleOfIncidence.value), "-s", str(5), #step "-w", str(self.wavelengths.value[0]), "-e", str(self.wavelengths.value[1]), "sample.json", "spectral_distribution.csv" ]
|
|
"palisadeCellCapsAspectRatio": 0.0,
|
"palisadeCellCapsAspectRatio": self.palisadeCellCapsAspectRatio.value,
|
def prepareExecution(self): with open(os.path.join(self.workingDirectory, "sample.json"), 'w') as f: f.write(json.dumps({ "wholeLeafThickness": self.wholeLeafThickness.value, "cuticleUndulationsAspectRatio": self.cuticleUndulationsAspectRatio.value, "epidermisCellCapsAspectRatio": self.epidermisCellCapsAspectRatio.value, "spongyCellCapsAspectRatio": self.spongyCellCapsAspectRatio.value, "palisadeCellCapsAspectRatio": 0.0, "linginConcentration": self.linginConcentration.value, "proteinConcentration": self.proteinConcentration.value, "celluloseConcentration": self.celluloseConcentration.value, "chlorophyllAConcentration": self.chlorophyllAConcentration.value, "chlorophyllBConcentration": self.chlorophyllBConcentration.value, "carotenoidConcentration": self.carotenoidConcentration.value, "mesophyllFraction": self.mesophyllPercentage.value / 100 }))
|
def prepareGraphs(self): wavelengths, reflectance, transmittance, absorptance = ([], [], [], []) with open(os.path.join(self.workingDirectory, "spectral_distribution.csv"), 'r') as f: spectralReader = csv.reader(f) headers = [e.strip() for e in spectralReader.next()] wIndex = headers.index("wavelength") rIndex = headers.index("reflectance") tIndex = headers.index("transmittance") aIndex = headers.index("absorptance") for row in spectralReader: wavelengths.append(float(row[wIndex])) reflectance.append(float(row[rIndex])) transmittance.append(float(row[tIndex])) absorptance.append(float(row[aIndex])) plt.clf() plt.plot(wavelengths, [e*100 for e in reflectance]) plt.xlabel("Wavelength (nm)") plt.ylabel("Reflectance (%)") plt.axis([wavelengths[0], wavelengths[-1], 0, max(reflectance) * 100 + 5]) plt.savefig(os.path.join(self.workingDirectory, "reflectance.pdf")) plt.savefig(os.path.join(self.workingDirectory, "reflectance.png")) plt.clf() plt.plot(wavelengths, [e*100 for e in transmittance]) plt.xlabel("Wavelength (nm)") plt.ylabel("Transmittance (%)") plt.axis([wavelengths[0], wavelengths[-1], 0, max(transmittance) * 100 + 5]) plt.savefig(os.path.join(self.workingDirectory, "transmittance.pdf")) plt.savefig(os.path.join(self.workingDirectory, "transmittance.png")) plt.clf() plt.plot(wavelengths, [e*100 for e in absorptance]) plt.xlabel("Wavelength (nm)") plt.ylabel("Absorptance (%)") plt.axis([wavelengths[0], wavelengths[-1], 0, max(absorptance) * 100 + 5]) plt.savefig(os.path.join(self.workingDirectory, "absorptance.pdf")) plt.savefig(os.path.join(self.workingDirectory, "absorptance.png")) plt.clf()
|
def prepareGraphs(self): wavelengths, reflectance, transmittance, absorptance = ([], [], [], [])
|
|
This is the results of your model run of \textbf{ABM-U} for the
|
This is the results of your model run of \textbf{ABM-B} for the
|
def latexBody(self): return r""" This is the results of your model run of \textbf{ABM-U} for the Natural Phenomenon Simulation Group (NPSG) at University of Waterloo.
|
The ABM-U employs an algorithmic Monte Carlo formulation to simulate light interactions with unifacial plant leaves (e.g., corn and sugar cane). More specifically, radiation propagation
|
The ABM-B employs an algorithmic Monte Carlo formulation to simulate light interactions with bifacial plant leaves (e.g., soybean and maple). More specifically, radiation propagation
|
def latexBody(self): return r""" This is the results of your model run of \textbf{ABM-U} for the Natural Phenomenon Simulation Group (NPSG) at University of Waterloo.
|
to the main tissue interfaces found in these leaves. For more details about this model, please refer to our related publications~\cite{Ba06,Ba07}. Although the ABM-U provides bidirectional readings,
|
to the main tissue interfaces found in these leaves. For more details about this model, please refer to our related publications~\cite{Ba06,Ba07}. Although the ABM-B provides bidirectional readings,
|
def latexBody(self): return r""" This is the results of your model run of \textbf{ABM-U} for the Natural Phenomenon Simulation Group (NPSG) at University of Waterloo.
|
\caption{Reflectance Curve}
|
\caption{Directional-hemispherical Reflectance}
|
def latexBody(self): return r""" This is the results of your model run of \textbf{ABM-U} for the Natural Phenomenon Simulation Group (NPSG) at University of Waterloo.
|
\caption{Transmittance Curve}
|
\caption{Directional-hemispherical Transmittance}
|
def latexBody(self): return r""" This is the results of your model run of \textbf{ABM-U} for the Natural Phenomenon Simulation Group (NPSG) at University of Waterloo.
|
\caption{Absorptance Curve}
|
\caption{Directional-hemispherical Absorptance}
|
def latexBody(self): return r""" This is the results of your model run of \textbf{ABM-U} for the Natural Phenomenon Simulation Group (NPSG) at University of Waterloo.
|
def __recvall(self, bytes): """__recvall(bytes) -> data
|
def __recvall(self, count): """__recvall(count) -> data
|
def __recvall(self, bytes): """__recvall(bytes) -> data Receive EXACTLY the number of bytes requested from the socket. Blocks until the required number of bytes have been received. """ data = "" while len(data) < bytes: d = self.recv(bytes-len(data)) if not d: raise GeneralProxyError("connection closed unexpectedly") data = data + d return data
|
data = "" while len(data) < bytes: d = self.recv(bytes-len(data)) if not d: raise GeneralProxyError("connection closed unexpectedly")
|
data = bytes("") while len(data) < count: d = self.recv(count-len(data)).decode() if not d: raise GeneralProxyError((0,"connection closed unexpectedly"))
|
def __recvall(self, bytes): """__recvall(bytes) -> data Receive EXACTLY the number of bytes requested from the socket. Blocks until the required number of bytes have been received. """ data = "" while len(data) < bytes: d = self.recv(bytes-len(data)) if not d: raise GeneralProxyError("connection closed unexpectedly") data = data + d return data
|
raise Socks5AuthError,((3,_socks5autherrors[3]))
|
raise Socks5AuthError((3,_socks5autherrors[3]))
|
def __negotiatesocks5(self,destaddr,destport): """__negotiatesocks5(self,destaddr,destport) Negotiates a connection through a SOCKS5 server. """ # First we'll send the authentication packages we support. if (self.__proxy[4]!=None) and (self.__proxy[5]!=None): # The username/password details were supplied to the # setproxy method so we support the USERNAME/PASSWORD # authentication (in addition to the standard none). self.sendall("\x05\x02\x00\x02") else: # No username/password were entered, therefore we # only support connections with no authentication. self.sendall("\x05\x01\x00") # We'll receive the server's response to determine which # method was selected chosenauth = self.__recvall(2) if chosenauth[0] != "\x05": self.close() raise GeneralProxyError((1,_generalerrors[1])) # Check the chosen authentication method if chosenauth[1] == "\x00": # No authentication is required pass elif chosenauth[1] == "\x02": # Okay, we need to perform a basic username/password # authentication. self.sendall("\x01" + chr(len(self.__proxy[4])) + self.__proxy[4] + chr(len(self.__proxy[5])) + self.__proxy[5]) authstat = self.__recvall(2) if authstat[0] != "\x01": # Bad response self.close() raise GeneralProxyError((1,_generalerrors[1])) if authstat[1] != "\x00": # Authentication failed self.close() raise Socks5AuthError,((3,_socks5autherrors[3])) # Authentication succeeded else: # Reaching here is always bad self.close() if chosenauth[1] == "\xFF": raise Socks5AuthError((2,_socks5autherrors[2])) else: raise GeneralProxyError((1,_generalerrors[1])) # Now we can request the actual connection req = "\x05\x01\x00" # If the given destination address is an IP address, we'll # use the IPv4 address request even if remote resolving was specified. try: ipaddr = socket.inet_aton(destaddr) req = req + "\x01" + ipaddr except socket.error: # Well it's not an IP number, so it's probably a DNS name. if self.__proxy[3]==True: # Resolve remotely ipaddr = None req = req + "\x03" + chr(len(destaddr)) + destaddr else: # Resolve locally ipaddr = socket.inet_aton(socket.gethostbyname(destaddr)) req = req + "\x01" + ipaddr req = req + struct.pack(">H",destport) self.sendall(req) # Get the response resp = self.__recvall(4) if resp[0] != "\x05": self.close() raise GeneralProxyError((1,_generalerrors[1])) elif resp[1] != "\x00": # Connection failed self.close() if ord(resp[1])<=8: raise Socks5Error((ord(resp[1]),_socks5errors[ord(resp[1])])) else: raise Socks5Error((9,_socks5errors[9])) # Get the bound address/port elif resp[3] == "\x01": boundaddr = self.__recvall(4) elif resp[3] == "\x03": resp = resp + self.recv(1) boundaddr = self.__recvall(ord(resp[4])) else: self.close() raise GeneralProxyError((1,_generalerrors[1])) boundport = struct.unpack(">H",self.__recvall(2))[0] self.__proxysockname = (boundaddr,boundport) if ipaddr != None: self.__proxypeername = (socket.inet_ntoa(ipaddr),destport) else: self.__proxypeername = (destaddr,destport)
|
req = req + struct.pack(">H",destport)
|
req = req + struct.pack(">H",destport).decode()
|
def __negotiatesocks5(self,destaddr,destport): """__negotiatesocks5(self,destaddr,destport) Negotiates a connection through a SOCKS5 server. """ # First we'll send the authentication packages we support. if (self.__proxy[4]!=None) and (self.__proxy[5]!=None): # The username/password details were supplied to the # setproxy method so we support the USERNAME/PASSWORD # authentication (in addition to the standard none). self.sendall("\x05\x02\x00\x02") else: # No username/password were entered, therefore we # only support connections with no authentication. self.sendall("\x05\x01\x00") # We'll receive the server's response to determine which # method was selected chosenauth = self.__recvall(2) if chosenauth[0] != "\x05": self.close() raise GeneralProxyError((1,_generalerrors[1])) # Check the chosen authentication method if chosenauth[1] == "\x00": # No authentication is required pass elif chosenauth[1] == "\x02": # Okay, we need to perform a basic username/password # authentication. self.sendall("\x01" + chr(len(self.__proxy[4])) + self.__proxy[4] + chr(len(self.__proxy[5])) + self.__proxy[5]) authstat = self.__recvall(2) if authstat[0] != "\x01": # Bad response self.close() raise GeneralProxyError((1,_generalerrors[1])) if authstat[1] != "\x00": # Authentication failed self.close() raise Socks5AuthError,((3,_socks5autherrors[3])) # Authentication succeeded else: # Reaching here is always bad self.close() if chosenauth[1] == "\xFF": raise Socks5AuthError((2,_socks5autherrors[2])) else: raise GeneralProxyError((1,_generalerrors[1])) # Now we can request the actual connection req = "\x05\x01\x00" # If the given destination address is an IP address, we'll # use the IPv4 address request even if remote resolving was specified. try: ipaddr = socket.inet_aton(destaddr) req = req + "\x01" + ipaddr except socket.error: # Well it's not an IP number, so it's probably a DNS name. if self.__proxy[3]==True: # Resolve remotely ipaddr = None req = req + "\x03" + chr(len(destaddr)) + destaddr else: # Resolve locally ipaddr = socket.inet_aton(socket.gethostbyname(destaddr)) req = req + "\x01" + ipaddr req = req + struct.pack(">H",destport) self.sendall(req) # Get the response resp = self.__recvall(4) if resp[0] != "\x05": self.close() raise GeneralProxyError((1,_generalerrors[1])) elif resp[1] != "\x00": # Connection failed self.close() if ord(resp[1])<=8: raise Socks5Error((ord(resp[1]),_socks5errors[ord(resp[1])])) else: raise Socks5Error((9,_socks5errors[9])) # Get the bound address/port elif resp[3] == "\x01": boundaddr = self.__recvall(4) elif resp[3] == "\x03": resp = resp + self.recv(1) boundaddr = self.__recvall(ord(resp[4])) else: self.close() raise GeneralProxyError((1,_generalerrors[1])) boundport = struct.unpack(">H",self.__recvall(2))[0] self.__proxysockname = (boundaddr,boundport) if ipaddr != None: self.__proxypeername = (socket.inet_ntoa(ipaddr),destport) else: self.__proxypeername = (destaddr,destport)
|
boundport = struct.unpack(">H",self.__recvall(2))[0]
|
boundport = struct.unpack(">H",bytes(self.__recvall(2), 'utf8'))[0]
|
def __negotiatesocks5(self,destaddr,destport): """__negotiatesocks5(self,destaddr,destport) Negotiates a connection through a SOCKS5 server. """ # First we'll send the authentication packages we support. if (self.__proxy[4]!=None) and (self.__proxy[5]!=None): # The username/password details were supplied to the # setproxy method so we support the USERNAME/PASSWORD # authentication (in addition to the standard none). self.sendall("\x05\x02\x00\x02") else: # No username/password were entered, therefore we # only support connections with no authentication. self.sendall("\x05\x01\x00") # We'll receive the server's response to determine which # method was selected chosenauth = self.__recvall(2) if chosenauth[0] != "\x05": self.close() raise GeneralProxyError((1,_generalerrors[1])) # Check the chosen authentication method if chosenauth[1] == "\x00": # No authentication is required pass elif chosenauth[1] == "\x02": # Okay, we need to perform a basic username/password # authentication. self.sendall("\x01" + chr(len(self.__proxy[4])) + self.__proxy[4] + chr(len(self.__proxy[5])) + self.__proxy[5]) authstat = self.__recvall(2) if authstat[0] != "\x01": # Bad response self.close() raise GeneralProxyError((1,_generalerrors[1])) if authstat[1] != "\x00": # Authentication failed self.close() raise Socks5AuthError,((3,_socks5autherrors[3])) # Authentication succeeded else: # Reaching here is always bad self.close() if chosenauth[1] == "\xFF": raise Socks5AuthError((2,_socks5autherrors[2])) else: raise GeneralProxyError((1,_generalerrors[1])) # Now we can request the actual connection req = "\x05\x01\x00" # If the given destination address is an IP address, we'll # use the IPv4 address request even if remote resolving was specified. try: ipaddr = socket.inet_aton(destaddr) req = req + "\x01" + ipaddr except socket.error: # Well it's not an IP number, so it's probably a DNS name. if self.__proxy[3]==True: # Resolve remotely ipaddr = None req = req + "\x03" + chr(len(destaddr)) + destaddr else: # Resolve locally ipaddr = socket.inet_aton(socket.gethostbyname(destaddr)) req = req + "\x01" + ipaddr req = req + struct.pack(">H",destport) self.sendall(req) # Get the response resp = self.__recvall(4) if resp[0] != "\x05": self.close() raise GeneralProxyError((1,_generalerrors[1])) elif resp[1] != "\x00": # Connection failed self.close() if ord(resp[1])<=8: raise Socks5Error((ord(resp[1]),_socks5errors[ord(resp[1])])) else: raise Socks5Error((9,_socks5errors[9])) # Get the bound address/port elif resp[3] == "\x01": boundaddr = self.__recvall(4) elif resp[3] == "\x03": resp = resp + self.recv(1) boundaddr = self.__recvall(ord(resp[4])) else: self.close() raise GeneralProxyError((1,_generalerrors[1])) boundport = struct.unpack(">H",self.__recvall(2))[0] self.__proxysockname = (boundaddr,boundport) if ipaddr != None: self.__proxypeername = (socket.inet_ntoa(ipaddr),destport) else: self.__proxypeername = (destaddr,destport)
|
req = "\x04\x01" + struct.pack(">H",destport) + ipaddr
|
req = "\x04\x01" + struct.pack(">H",destport).decode() + ipaddr
|
def __negotiatesocks4(self,destaddr,destport): """__negotiatesocks4(self,destaddr,destport) Negotiates a connection through a SOCKS4 server. """ # Check if the destination address provided is an IP address rmtrslv = False try: ipaddr = socket.inet_aton(destaddr) except socket.error: # It's a DNS name. Check where it should be resolved. if self.__proxy[3]==True: ipaddr = "\x00\x00\x00\x01" rmtrslv = True else: ipaddr = socket.inet_aton(socket.gethostbyname(destaddr)) # Construct the request packet req = "\x04\x01" + struct.pack(">H",destport) + ipaddr # The username parameter is considered userid for SOCKS4 if self.__proxy[4] != None: req = req + self.__proxy[4] req = req + "\x00" # DNS name if remote resolving is required # NOTE: This is actually an extension to the SOCKS4 protocol # called SOCKS4A and may not be supported in all cases. if rmtrslv==True: req = req + destaddr + "\x00" self.sendall(req) # Get the response from the server resp = self.__recvall(8) if resp[0] != "\x00": # Bad data self.close() raise GeneralProxyError((1,_generalerrors[1])) if resp[1] != "\x5A": # Server returned an error self.close() if ord(resp[1]) in (91,92,93): self.close() raise Socks4Error((ord(resp[1]),_socks4errors[ord(resp[1])-90])) else: raise Socks4Error((94,_socks4errors[4])) # Get the bound address/port self.__proxysockname = (socket.inet_ntoa(resp[4:]),struct.unpack(">H",resp[2:4])[0]) if rmtrslv != None: self.__proxypeername = (socket.inet_ntoa(ipaddr),destport) else: self.__proxypeername = (destaddr,destport)
|
self.__proxysockname = (socket.inet_ntoa(resp[4:]),struct.unpack(">H",resp[2:4])[0])
|
self.__proxysockname = (socket.inet_ntoa(resp[4:]),struct.unpack(">H",bytes(resp[2:4],'utf8'))[0])
|
def __negotiatesocks4(self,destaddr,destport): """__negotiatesocks4(self,destaddr,destport) Negotiates a connection through a SOCKS4 server. """ # Check if the destination address provided is an IP address rmtrslv = False try: ipaddr = socket.inet_aton(destaddr) except socket.error: # It's a DNS name. Check where it should be resolved. if self.__proxy[3]==True: ipaddr = "\x00\x00\x00\x01" rmtrslv = True else: ipaddr = socket.inet_aton(socket.gethostbyname(destaddr)) # Construct the request packet req = "\x04\x01" + struct.pack(">H",destport) + ipaddr # The username parameter is considered userid for SOCKS4 if self.__proxy[4] != None: req = req + self.__proxy[4] req = req + "\x00" # DNS name if remote resolving is required # NOTE: This is actually an extension to the SOCKS4 protocol # called SOCKS4A and may not be supported in all cases. if rmtrslv==True: req = req + destaddr + "\x00" self.sendall(req) # Get the response from the server resp = self.__recvall(8) if resp[0] != "\x00": # Bad data self.close() raise GeneralProxyError((1,_generalerrors[1])) if resp[1] != "\x5A": # Server returned an error self.close() if ord(resp[1]) in (91,92,93): self.close() raise Socks4Error((ord(resp[1]),_socks4errors[ord(resp[1])-90])) else: raise Socks4Error((94,_socks4errors[4])) # Get the bound address/port self.__proxysockname = (socket.inet_ntoa(resp[4:]),struct.unpack(">H",resp[2:4])[0]) if rmtrslv != None: self.__proxypeername = (socket.inet_ntoa(ipaddr),destport) else: self.__proxypeername = (destaddr,destport)
|
boundaddr = self.__recvall(resp[4])
|
boundaddr = self.__recvall(ord(resp[4]))
|
def __negotiatesocks5(self,destaddr,destport): """__negotiatesocks5(self,destaddr,destport) Negotiates a connection through a SOCKS5 server. """ # First we'll send the authentication packages we support. if (self.__proxy[4]!=None) and (self.__proxy[5]!=None): # The username/password details were supplied to the # setproxy method so we support the USERNAME/PASSWORD # authentication (in addition to the standard none). self.sendall("\x05\x02\x00\x02") else: # No username/password were entered, therefore we # only support connections with no authentication. self.sendall("\x05\x01\x00") # We'll receive the server's response to determine which # method was selected chosenauth = self.__recvall(2) if chosenauth[0] != "\x05": self.close() raise GeneralProxyError((1,_generalerrors[1])) # Check the chosen authentication method if chosenauth[1] == "\x00": # No authentication is required pass elif chosenauth[1] == "\x02": # Okay, we need to perform a basic username/password # authentication. self.sendall("\x01" + chr(len(self.__proxy[4])) + self.__proxy[4] + chr(len(self.proxy[5])) + self.__proxy[5]) authstat = self.__recvall(2) if authstat[0] != "\x01": # Bad response self.close() raise GeneralProxyError((1,_generalerrors[1])) if authstat[1] != "\x00": # Authentication failed self.close() raise Socks5AuthError,((3,_socks5autherrors[3])) # Authentication succeeded else: # Reaching here is always bad self.close() if chosenauth[1] == "\xFF": raise Socks5AuthError((2,_socks5autherrors[2])) else: raise GeneralProxyError((1,_generalerrors[1])) # Now we can request the actual connection req = "\x05\x01\x00" # If the given destination address is an IP address, we'll # use the IPv4 address request even if remote resolving was specified. try: ipaddr = socket.inet_aton(destaddr) req = req + "\x01" + ipaddr except socket.error: # Well it's not an IP number, so it's probably a DNS name. if self.__proxy[3]==True: # Resolve remotely ipaddr = None req = req + "\x03" + chr(len(destaddr)) + destaddr else: # Resolve locally ipaddr = socket.inet_aton(socket.gethostbyname(destaddr)) req = req + "\x01" + ipaddr req = req + struct.pack(">H",destport) self.sendall(req) # Get the response resp = self.__recvall(4) if resp[0] != "\x05": self.close() raise GeneralProxyError((1,_generalerrors[1])) elif resp[1] != "\x00": # Connection failed self.close() if ord(resp[1])<=8: raise Socks5Error(ord(resp[1]),_generalerrors[ord(resp[1])]) else: raise Socks5Error(9,_generalerrors[9]) # Get the bound address/port elif resp[3] == "\x01": boundaddr = self.__recvall(4) elif resp[3] == "\x03": resp = resp + self.recv(1) boundaddr = self.__recvall(resp[4]) else: self.close() raise GeneralProxyError((1,_generalerrors[1])) boundport = struct.unpack(">H",self.__recvall(2))[0] self.__proxysockname = (boundaddr,boundport) if ipaddr != None: self.__proxypeername = (socket.inet_ntoa(ipaddr),destport) else: self.__proxypeername = (destaddr,destport)
|
"""This puts a character at the current cursor position. cursor position if moved forward with wrap-around, but no scrolling is done if
|
"""This puts a character at the current cursor position. The cursor position is moved forward with wrap-around, but no scrolling is done if
|
def write_ch (self, ch):
|
self.put_abs(self.cur_r, self.cur_c, ' ')
|
def write_ch (self, ch):
|
|
data = data + self.recv(bytes-len(data))
|
d = self.recv(bytes-len(data)) if not d: raise GeneralProxyError("connection closed unexpectedly") data = data + d
|
def __recvall(self, bytes): """__recvall(bytes) -> data Receive EXACTLY the number of bytes requested from the socket. Blocks until the required number of bytes have been received. """ data = "" while len(data) < bytes: data = data + self.recv(bytes-len(data)) return data
|
self.sendall("\x01" + chr(len(self.__proxy[4])) + self.__proxy[4] + chr(len(self.proxy[5])) + self.__proxy[5])
|
self.sendall("\x01" + chr(len(self.__proxy[4])) + self.__proxy[4] + chr(len(self.__proxy[5])) + self.__proxy[5])
|
def __negotiatesocks5(self,destaddr,destport): """__negotiatesocks5(self,destaddr,destport) Negotiates a connection through a SOCKS5 server. """ # First we'll send the authentication packages we support. if (self.__proxy[4]!=None) and (self.__proxy[5]!=None): # The username/password details were supplied to the # setproxy method so we support the USERNAME/PASSWORD # authentication (in addition to the standard none). self.sendall("\x05\x02\x00\x02") else: # No username/password were entered, therefore we # only support connections with no authentication. self.sendall("\x05\x01\x00") # We'll receive the server's response to determine which # method was selected chosenauth = self.__recvall(2) if chosenauth[0] != "\x05": self.close() raise GeneralProxyError((1,_generalerrors[1])) # Check the chosen authentication method if chosenauth[1] == "\x00": # No authentication is required pass elif chosenauth[1] == "\x02": # Okay, we need to perform a basic username/password # authentication. self.sendall("\x01" + chr(len(self.__proxy[4])) + self.__proxy[4] + chr(len(self.proxy[5])) + self.__proxy[5]) authstat = self.__recvall(2) if authstat[0] != "\x01": # Bad response self.close() raise GeneralProxyError((1,_generalerrors[1])) if authstat[1] != "\x00": # Authentication failed self.close() raise Socks5AuthError,((3,_socks5autherrors[3])) # Authentication succeeded else: # Reaching here is always bad self.close() if chosenauth[1] == "\xFF": raise Socks5AuthError((2,_socks5autherrors[2])) else: raise GeneralProxyError((1,_generalerrors[1])) # Now we can request the actual connection req = "\x05\x01\x00" # If the given destination address is an IP address, we'll # use the IPv4 address request even if remote resolving was specified. try: ipaddr = socket.inet_aton(destaddr) req = req + "\x01" + ipaddr except socket.error: # Well it's not an IP number, so it's probably a DNS name. if self.__proxy[3]==True: # Resolve remotely ipaddr = None req = req + "\x03" + chr(len(destaddr)) + destaddr else: # Resolve locally ipaddr = socket.inet_aton(socket.gethostbyname(destaddr)) req = req + "\x01" + ipaddr req = req + struct.pack(">H",destport) self.sendall(req) # Get the response resp = self.__recvall(4) if resp[0] != "\x05": self.close() raise GeneralProxyError((1,_generalerrors[1])) elif resp[1] != "\x00": # Connection failed self.close() if ord(resp[1])<=8: raise Socks5Error((ord(resp[1]),_socks5errors[ord(resp[1])])) else: raise Socks5Error((9,_socks5errors[9])) # Get the bound address/port elif resp[3] == "\x01": boundaddr = self.__recvall(4) elif resp[3] == "\x03": resp = resp + self.recv(1) boundaddr = self.__recvall(ord(resp[4])) else: self.close() raise GeneralProxyError((1,_generalerrors[1])) boundport = struct.unpack(">H",self.__recvall(2))[0] self.__proxysockname = (boundaddr,boundport) if ipaddr != None: self.__proxypeername = (socket.inet_ntoa(ipaddr),destport) else: self.__proxypeername = (destaddr,destport)
|
raise Socks5Error(ord(resp[1]),_generalerrors[ord(resp[1])]) else: raise Socks5Error(9,_generalerrors[9])
|
raise Socks5Error((ord(resp[1]),_socks5errors[ord(resp[1])])) else: raise Socks5Error((9,_socks5errors[9]))
|
def __negotiatesocks5(self,destaddr,destport): """__negotiatesocks5(self,destaddr,destport) Negotiates a connection through a SOCKS5 server. """ # First we'll send the authentication packages we support. if (self.__proxy[4]!=None) and (self.__proxy[5]!=None): # The username/password details were supplied to the # setproxy method so we support the USERNAME/PASSWORD # authentication (in addition to the standard none). self.sendall("\x05\x02\x00\x02") else: # No username/password were entered, therefore we # only support connections with no authentication. self.sendall("\x05\x01\x00") # We'll receive the server's response to determine which # method was selected chosenauth = self.__recvall(2) if chosenauth[0] != "\x05": self.close() raise GeneralProxyError((1,_generalerrors[1])) # Check the chosen authentication method if chosenauth[1] == "\x00": # No authentication is required pass elif chosenauth[1] == "\x02": # Okay, we need to perform a basic username/password # authentication. self.sendall("\x01" + chr(len(self.__proxy[4])) + self.__proxy[4] + chr(len(self.proxy[5])) + self.__proxy[5]) authstat = self.__recvall(2) if authstat[0] != "\x01": # Bad response self.close() raise GeneralProxyError((1,_generalerrors[1])) if authstat[1] != "\x00": # Authentication failed self.close() raise Socks5AuthError,((3,_socks5autherrors[3])) # Authentication succeeded else: # Reaching here is always bad self.close() if chosenauth[1] == "\xFF": raise Socks5AuthError((2,_socks5autherrors[2])) else: raise GeneralProxyError((1,_generalerrors[1])) # Now we can request the actual connection req = "\x05\x01\x00" # If the given destination address is an IP address, we'll # use the IPv4 address request even if remote resolving was specified. try: ipaddr = socket.inet_aton(destaddr) req = req + "\x01" + ipaddr except socket.error: # Well it's not an IP number, so it's probably a DNS name. if self.__proxy[3]==True: # Resolve remotely ipaddr = None req = req + "\x03" + chr(len(destaddr)) + destaddr else: # Resolve locally ipaddr = socket.inet_aton(socket.gethostbyname(destaddr)) req = req + "\x01" + ipaddr req = req + struct.pack(">H",destport) self.sendall(req) # Get the response resp = self.__recvall(4) if resp[0] != "\x05": self.close() raise GeneralProxyError((1,_generalerrors[1])) elif resp[1] != "\x00": # Connection failed self.close() if ord(resp[1])<=8: raise Socks5Error(ord(resp[1]),_generalerrors[ord(resp[1])]) else: raise Socks5Error(9,_generalerrors[9]) # Get the bound address/port elif resp[3] == "\x01": boundaddr = self.__recvall(4) elif resp[3] == "\x03": resp = resp + self.recv(1) boundaddr = self.__recvall(ord(resp[4])) else: self.close() raise GeneralProxyError((1,_generalerrors[1])) boundport = struct.unpack(">H",self.__recvall(2))[0] self.__proxysockname = (boundaddr,boundport) if ipaddr != None: self.__proxypeername = (socket.inet_ntoa(ipaddr),destport) else: self.__proxypeername = (destaddr,destport)
|
bytes = bytes.encode()
|
try: bytes = bytes.encode() except Exception: pass
|
def sendall(self, bytes): if 'encode' in dir(bytes): bytes = bytes.encode() socket.socket.sendall(self, bytes)
|
def __recvall(self, count): """__recvall(count) -> data Receive EXACTLY the number of bytes requested from the socket. Blocks until the required number of bytes have been received. """ data = bytes("") while len(data) < count: d = self.recv(count-len(data)).decode() if not d: raise GeneralProxyError((0,"connection closed unexpectedly")) data = data + d return data def sendall(self, bytes):
|
def __decode(self, bytes): if 'decode' in dir(bytes): try: bytes = bytes.decode() except Exception: pass return bytes def __encode(self, bytes):
|
def __recvall(self, count): """__recvall(count) -> data Receive EXACTLY the number of bytes requested from the socket. Blocks until the required number of bytes have been received. """ data = bytes("") while len(data) < count: d = self.recv(count-len(data)).decode() if not d: raise GeneralProxyError((0,"connection closed unexpectedly")) data = data + d return data
|
socket.socket.sendall(self, bytes)
|
return bytes def __recvall(self, count): """__recvall(count) -> data Receive EXACTLY the number of bytes requested from the socket. Blocks until the required number of bytes have been received. """ data = bytes("") while len(data) < count: d = self.recv(count-len(data)) if not d: raise GeneralProxyError((0,"connection closed unexpectedly")) data = data + self.__decode(d) return data def sendall(self, bytes): socket.socket.sendall(self, self.__encode(bytes))
|
def sendall(self, bytes): if 'encode' in dir(bytes): try: bytes = bytes.encode() except Exception: pass socket.socket.sendall(self, bytes)
|
req = req + struct.pack(">H",destport).decode()
|
req = req + self.__decode(struct.pack(">H",destport))
|
def __negotiatesocks5(self,destaddr,destport): """__negotiatesocks5(self,destaddr,destport) Negotiates a connection through a SOCKS5 server. """ # First we'll send the authentication packages we support. if (self.__proxy[4]!=None) and (self.__proxy[5]!=None): # The username/password details were supplied to the # setproxy method so we support the USERNAME/PASSWORD # authentication (in addition to the standard none). self.sendall("\x05\x02\x00\x02") else: # No username/password were entered, therefore we # only support connections with no authentication. self.sendall("\x05\x01\x00") # We'll receive the server's response to determine which # method was selected chosenauth = self.__recvall(2) if chosenauth[0] != "\x05": self.close() raise GeneralProxyError((1,_generalerrors[1])) # Check the chosen authentication method if chosenauth[1] == "\x00": # No authentication is required pass elif chosenauth[1] == "\x02": # Okay, we need to perform a basic username/password # authentication. self.sendall("\x01" + chr(len(self.__proxy[4])) + self.__proxy[4] + chr(len(self.__proxy[5])) + self.__proxy[5]) authstat = self.__recvall(2) if authstat[0] != "\x01": # Bad response self.close() raise GeneralProxyError((1,_generalerrors[1])) if authstat[1] != "\x00": # Authentication failed self.close() raise Socks5AuthError((3,_socks5autherrors[3])) # Authentication succeeded else: # Reaching here is always bad self.close() if chosenauth[1] == "\xFF": raise Socks5AuthError((2,_socks5autherrors[2])) else: raise GeneralProxyError((1,_generalerrors[1])) # Now we can request the actual connection req = "\x05\x01\x00" # If the given destination address is an IP address, we'll # use the IPv4 address request even if remote resolving was specified. try: ipaddr = socket.inet_aton(destaddr) req = req + "\x01" + ipaddr except socket.error: # Well it's not an IP number, so it's probably a DNS name. if self.__proxy[3]==True: # Resolve remotely ipaddr = None req = req + "\x03" + chr(len(destaddr)) + destaddr else: # Resolve locally ipaddr = socket.inet_aton(socket.gethostbyname(destaddr)) req = req + "\x01" + ipaddr req = req + struct.pack(">H",destport).decode() self.sendall(req) # Get the response resp = self.__recvall(4) if resp[0] != "\x05": self.close() raise GeneralProxyError((1,_generalerrors[1])) elif resp[1] != "\x00": # Connection failed self.close() if ord(resp[1])<=8: raise Socks5Error((ord(resp[1]),_socks5errors[ord(resp[1])])) else: raise Socks5Error((9,_socks5errors[9])) # Get the bound address/port elif resp[3] == "\x01": boundaddr = self.__recvall(4) elif resp[3] == "\x03": resp = resp + self.recv(1) boundaddr = self.__recvall(ord(resp[4])) else: self.close() raise GeneralProxyError((1,_generalerrors[1])) boundport = struct.unpack(">H",bytes(self.__recvall(2), 'utf8'))[0] self.__proxysockname = (boundaddr,boundport) if ipaddr != None: self.__proxypeername = (socket.inet_ntoa(ipaddr),destport) else: self.__proxypeername = (destaddr,destport)
|
req = "\x04\x01" + struct.pack(">H",destport).decode() + ipaddr
|
req = "\x04\x01" + self.__decode(struct.pack(">H",destport)) + ipaddr
|
def __negotiatesocks4(self,destaddr,destport): """__negotiatesocks4(self,destaddr,destport) Negotiates a connection through a SOCKS4 server. """ # Check if the destination address provided is an IP address rmtrslv = False try: ipaddr = socket.inet_aton(destaddr) except socket.error: # It's a DNS name. Check where it should be resolved. if self.__proxy[3]==True: ipaddr = "\x00\x00\x00\x01" rmtrslv = True else: ipaddr = socket.inet_aton(socket.gethostbyname(destaddr)) # Construct the request packet req = "\x04\x01" + struct.pack(">H",destport).decode() + ipaddr # The username parameter is considered userid for SOCKS4 if self.__proxy[4] != None: req = req + self.__proxy[4] req = req + "\x00" # DNS name if remote resolving is required # NOTE: This is actually an extension to the SOCKS4 protocol # called SOCKS4A and may not be supported in all cases. if rmtrslv==True: req = req + destaddr + "\x00" self.sendall(req) # Get the response from the server resp = self.__recvall(8) if resp[0] != "\x00": # Bad data self.close() raise GeneralProxyError((1,_generalerrors[1])) if resp[1] != "\x5A": # Server returned an error self.close() if ord(resp[1]) in (91,92,93): self.close() raise Socks4Error((ord(resp[1]),_socks4errors[ord(resp[1])-90])) else: raise Socks4Error((94,_socks4errors[4])) # Get the bound address/port self.__proxysockname = (socket.inet_ntoa(resp[4:]),struct.unpack(">H",bytes(resp[2:4],'utf8'))[0]) if rmtrslv != None: self.__proxypeername = (socket.inet_ntoa(ipaddr),destport) else: self.__proxypeername = (destaddr,destport)
|
ops, 'Virtual(node_vtable)', None)
|
ops, ops)
|
def test_invalid_loop_1(self): ops = """ [p1] guard_isnull(p1) [] # p2 = new_with_vtable(ConstClass(node_vtable)) jump(p2) """ py.test.raises(InvalidLoop, self.optimize_loop, ops, 'Virtual(node_vtable)', None)
|
py.test.skip("this would fail if we had Fixed again in the specnodes")
|
def test_invalid_loop_2(self): py.test.skip("this would fail if we had Fixed again in the specnodes") ops = """ [p1] guard_class(p1, ConstClass(node_vtable2)) [] # p2 = new_with_vtable(ConstClass(node_vtable)) escape(p2) # prevent it from staying Virtual jump(p2) """ py.test.raises(InvalidLoop, self.optimize_loop, ops, '...', None)
|
|
ops, '...', None)
|
ops, ops)
|
def test_invalid_loop_2(self): py.test.skip("this would fail if we had Fixed again in the specnodes") ops = """ [p1] guard_class(p1, ConstClass(node_vtable2)) [] # p2 = new_with_vtable(ConstClass(node_vtable)) escape(p2) # prevent it from staying Virtual jump(p2) """ py.test.raises(InvalidLoop, self.optimize_loop, ops, '...', None)
|
py.test.raises(InvalidLoop, self.optimize_loop, ops, 'Virtual(node_vtable, nextdescr=Virtual(node_vtable))', None)
|
py.test.raises(InvalidLoop, self.optimize_loop, ops, ops)
|
def test_invalid_loop_3(self): ops = """ [p1] p2 = getfield_gc(p1, descr=nextdescr) guard_isnull(p2) [] # p3 = new_with_vtable(ConstClass(node_vtable)) p4 = new_with_vtable(ConstClass(node_vtable)) setfield_gc(p3, p4, descr=nextdescr) jump(p3) """ py.test.raises(InvalidLoop, self.optimize_loop, ops, 'Virtual(node_vtable, nextdescr=Virtual(node_vtable))', None)
|
if self._precision = -1:
|
if self._precision == -1:
|
def _format_float(self, w_float): space = self.space if self._alternate: msg = "alternate form not allowed in float formats" raise OperationError(space.w_ValueError, space.wrap(msg)) tp = self._type if tp == "\0": tp = "g" value = space.float_w(w_float) if tp == "%": tp = "f" value *= 100 if self._precision = -1: self._precision = 6
|
for x in testmap:
|
for x in self.fspath.listdir():
|
def collect(self): l = [] for x in testmap: name = x.basename regrtest = self.get(name) if regrtest is not None: #if option.extracttests: # l.append(InterceptedRunModule(name, self, regrtest)) #else: l.append(RunFileExternal(name, parent=self, regrtest=regrtest)) return l
|
if regrtest is not None:
|
if regrtest is not None: if bool(we_are_in_modified) ^ regrtest.ismodified(): continue
|
def collect(self): l = [] for x in testmap: name = x.basename regrtest = self.get(name) if regrtest is not None: #if option.extracttests: # l.append(InterceptedRunModule(name, self, regrtest)) #else: l.append(RunFileExternal(name, parent=self, regrtest=regrtest)) return l
|
return RegrDirectory(path, parent)
|
if path in (modregrtestdir, regrtestdir): return RegrDirectory(path, parent) def pytest_ignore_collect(path): if path.check(file=1): return True
|
def pytest_collect_directory(parent, path): return RegrDirectory(path, parent)
|
os.putenv('PYTHONPATH', old_pythonpath)
|
if old_pythonpath is not None: os.putenv('PYTHONPATH', old_pythonpath)
|
def chdir_and_unset_pythonpath(new_cwd): old_cwd = new_cwd.chdir() old_pythonpath = os.getenv('PYTHONPATH') os.unsetenv('PYTHONPATH') try: yield finally: old_cwd.chdir() os.putenv('PYTHONPATH', old_pythonpath)
|
assert isinstance(hashlib.new('sha1', u'xxx'), _hashlib.hash)
|
assert isinstance(hashlib.new('sha256', u'xxx'), _hashlib.hash)
|
def test_unicode(): assert isinstance(hashlib.new('sha1', u'xxx'), _hashlib.hash)
|
for _ in range((self.mc.size_of_gen_load_int+WORD)//WORD):
|
for _ in range(size//WORD):
|
def _prepare_sp_patch_location(self): """Generate NOPs as placeholder to patch the instruction(s) to update the sp according to the number of spilled variables""" l = self.mc.curraddr() for _ in range((self.mc.size_of_gen_load_int+WORD)//WORD): self.mc.MOV_rr(r.r0.value, r.r0.value) return l
|
def gettext(msg): """gettext(msg) -> string Return translation of msg.""" return _gettext(msg) def dgettext(domain, msg): """dgettext(domain, msg) -> string Return translation of msg in domain.""" return _dgettext(domain, msg) def dcgettext(domain, msg, category): """dcgettext(domain, msg, category) -> string Return translation of msg in domain and category.""" return _dcgettext(domain, msg, category) def textdomain(domain): """textdomain(domain) -> string Set the C library's textdomain to domain, returning the new domain.""" return _textdomain(domain) def bindtextdomain(domain, dir): """bindtextdomain(domain, dir) -> string Bind the C library's domain to dir.""" dirname = _bindtextdomain(domain, dir) if not dirname: errno = get_errno() raise OSError(errno) return dirname if _bind_textdomain_codeset: def bind_textdomain_codeset(domain, codeset): """bind_textdomain_codeset(domain, codeset) -> string Bind the C library's domain to codeset.""" codeset = _bind_textdomain_codeset(domain, codeset) if codeset: return codeset return None
|
if HAS_LIBINTL: def gettext(msg): """gettext(msg) -> string Return translation of msg.""" return _gettext(msg) def dgettext(domain, msg): """dgettext(domain, msg) -> string Return translation of msg in domain.""" return _dgettext(domain, msg) def dcgettext(domain, msg, category): """dcgettext(domain, msg, category) -> string Return translation of msg in domain and category.""" return _dcgettext(domain, msg, category) def textdomain(domain): """textdomain(domain) -> string Set the C library's textdomain to domain, returning the new domain.""" return _textdomain(domain) def bindtextdomain(domain, dir): """bindtextdomain(domain, dir) -> string Bind the C library's domain to dir.""" dirname = _bindtextdomain(domain, dir) if not dirname: errno = get_errno() raise OSError(errno) return dirname if HAS_BIND_TEXTDOMAIN_CODESET: def bind_textdomain_codeset(domain, codeset): """bind_textdomain_codeset(domain, codeset) -> string Bind the C library's domain to codeset.""" codeset = _bind_textdomain_codeset(domain, codeset) if codeset: return codeset return None
|
def gettext(msg): """gettext(msg) -> string Return translation of msg.""" return _gettext(msg)
|
'gettext', 'dgettext', 'dcgettext', 'textdomain', 'bindtextdomain',
|
def bind_textdomain_codeset(domain, codeset): """bind_textdomain_codeset(domain, codeset) -> string Bind the C library's domain to codeset.""" codeset = _bind_textdomain_codeset(domain, codeset) if codeset: return codeset return None
|
|
if _bind_textdomain_codeset: __all__ += ('bind_textdomain_codeset',)
|
if HAS_LIBINTL: __all__ += ('gettext', 'dgettext', 'dcgettext', 'textdomain', 'bindtextdomain') if HAS_BIND_TEXTDOMAIN_CODESET: __all__ += ('bind_textdomain_codeset',)
|
def bind_textdomain_codeset(domain, codeset): """bind_textdomain_codeset(domain, codeset) -> string Bind the C library's domain to codeset.""" codeset = _bind_textdomain_codeset(domain, codeset) if codeset: return codeset return None
|
def unpack_float(data,index,size,le): bytes = [ord(b) for b in data[index:index+size]] if len(bytes) != size: raise StructError,"Not enough data to unpack" if max(bytes) == 0: return 0.0 if le == 'big': bytes.reverse() if size == 4: bias = 127 exp = 8 prec = 23 else: bias = 1023 exp = 11 prec = 52 mantissa = long(bytes[size-2] & (2**(15-exp)-1)) for b in bytes[size-3::-1]: mantissa = mantissa << 8 | b mantissa = 1 + (1.0*mantissa)/(2**(prec)) mantissa /= 2 e = (bytes[-1] & 0x7f) << (exp - 7) e += (bytes[size-2] >> (15 - exp)) & (2**(exp - 7) -1) e -= bias e += 1 sign = bytes[-1] & 0x80 if e == bias + 2: if mantissa == 0.5: number = INFINITY else: return NAN else: number = math.ldexp(mantissa,e) if sign : number *= -1 return number
|
def unpack_float(data,index,size,le): bytes = [ord(b) for b in data[index:index+size]] if len(bytes) != size: raise StructError,"Not enough data to unpack" if max(bytes) == 0: return 0.0 if le == 'big': bytes.reverse() if size == 4: bias = 127 exp = 8 prec = 23 else: bias = 1023 exp = 11 prec = 52 mantissa = long(bytes[size-2] & (2**(15-exp)-1)) for b in bytes[size-3::-1]: mantissa = mantissa << 8 | b mantissa = 1 + (1.0*mantissa)/(2**(prec)) mantissa /= 2 e = (bytes[-1] & 0x7f) << (exp - 7) e += (bytes[size-2] >> (15 - exp)) & (2**(exp - 7) -1) e -= bias e += 1 sign = bytes[-1] & 0x80 if e == bias + 2: if mantissa == 0.5: number = INFINITY else: return NAN else: number = math.ldexp(mantissa,e) if sign : number *= -1 return number
|
|
def pack_float(number, size, le): if size == 4: bias = 127 exp = 8 prec = 23 else: bias = 1023 exp = 11 prec = 52 if isnan(number): sign = 0x80 man, e = 1.5, bias + 1 else: if number < 0: sign = 0x80 number *= -1 elif number == 0.0: return '\x00' * size else: sign = 0x00 if isinf(number): man, e = 1.0, bias + 1 else: man, e = math.frexp(number)
|
def pack_float(x, size, le): unsigned = float_pack(x, size)
|
def pack_float(number, size, le): if size == 4: bias = 127 exp = 8 prec = 23 else: bias = 1023 exp = 11 prec = 52 if isnan(number): sign = 0x80 man, e = 1.5, bias + 1 else: if number < 0: sign = 0x80 number *= -1 elif number == 0.0: return '\x00' * size else: sign = 0x00 if isinf(number): man, e = 1.0, bias + 1 else: man, e = math.frexp(number) result = [] if 0.5 <= man and man < 1.0: man *= 2 e -= 1 man -= 1 e += bias power_of_two = 1 << prec mantissa = int(power_of_two * man + 0.5) if mantissa >> prec : mantissa = 0 e += 1 for i in range(size-2): result.append(chr(mantissa & 0xff)) mantissa >>= 8 x = (mantissa & ((1<<(15-exp))-1)) | ((e & ((1<<(exp-7))-1))<<(15-exp)) result.append(chr(x)) x = sign | e >> (exp - 7) result.append(chr(x)) if le == 'big': result.reverse() return ''.join(result)
|
if 0.5 <= man and man < 1.0: man *= 2 e -= 1 man -= 1 e += bias power_of_two = 1 << prec mantissa = int(power_of_two * man + 0.5) if mantissa >> prec : mantissa = 0 e += 1 for i in range(size-2): result.append(chr(mantissa & 0xff)) mantissa >>= 8 x = (mantissa & ((1<<(15-exp))-1)) | ((e & ((1<<(exp-7))-1))<<(15-exp)) result.append(chr(x)) x = sign | e >> (exp - 7) result.append(chr(x)) if le == 'big':
|
for i in range(8): result.append(chr((unsigned >> (i * 8)) & 0xFF)) if le == "big":
|
def pack_float(number, size, le): if size == 4: bias = 127 exp = 8 prec = 23 else: bias = 1023 exp = 11 prec = 52 if isnan(number): sign = 0x80 man, e = 1.5, bias + 1 else: if number < 0: sign = 0x80 number *= -1 elif number == 0.0: return '\x00' * size else: sign = 0x00 if isinf(number): man, e = 1.0, bias + 1 else: man, e = math.frexp(number) result = [] if 0.5 <= man and man < 1.0: man *= 2 e -= 1 man -= 1 e += bias power_of_two = 1 << prec mantissa = int(power_of_two * man + 0.5) if mantissa >> prec : mantissa = 0 e += 1 for i in range(size-2): result.append(chr(mantissa & 0xff)) mantissa >>= 8 x = (mantissa & ((1<<(15-exp))-1)) | ((e & ((1<<(exp-7))-1))<<(15-exp)) result.append(chr(x)) x = sign | e >> (exp - 7) result.append(chr(x)) if le == 'big': result.reverse() return ''.join(result)
|
raise NotImplementedError
|
raise KeyError
|
def m(self): raise NotImplementedError
|
except NotImplementedError: pass
|
except KeyError: assert 0
|
def f(n): if n > 3: o = A() else: o = B() try: o.m() except NotImplementedError: pass return B().m()
|
self.interpret_raises(NotImplementedError, f, [7])
|
self.interpret_raises(KeyError, f, [7])
|
def f(n): if n > 3: o = A() else: o = B() try: o.m() except NotImplementedError: pass return B().m()
|
w_result = space.wrap(result[0])
|
if lltyp is rffi.FLOAT: w_result = space.wrap(rffi.cast(rffi.DOUBLE, result[0])) else: w_result = space.wrap(result[0])
|
def PyMember_GetOne(space, obj, w_member): addr = rffi.cast(ADDR, obj) addr += w_member.c_offset member_type = rffi.cast(lltype.Signed, w_member.c_type) for converter in integer_converters: typ, lltyp, _ = converter if typ == member_type: result = rffi.cast(rffi.CArrayPtr(lltyp), addr) w_result = space.wrap(result[0]) return w_result if member_type == T_STRING: result = rffi.cast(rffi.CCHARPP, addr) if result[0]: w_result = PyString_FromString(space, result[0]) else: w_result = space.w_None elif member_type == T_STRING_INPLACE: result = rffi.cast(rffi.CCHARP, addr) w_result = PyString_FromString(space, result) elif member_type == T_CHAR: result = rffi.cast(rffi.CCHARP, addr) w_result = space.wrap(result[0]) elif member_type == T_OBJECT: obj_ptr = rffi.cast(PyObjectP, addr) if obj_ptr[0]: w_result = from_ref(space, obj_ptr[0]) else: w_result = space.w_None elif member_type == T_OBJECT_EX: obj_ptr = rffi.cast(PyObjectP, addr) if obj_ptr[0]: w_result = from_ref(space, obj_ptr[0]) else: w_name = space.wrap(rffi.charp2str(w_member.c_name)) raise OperationError(space.w_AttributeError, w_name) else: raise OperationError(space.w_SystemError, space.wrap("bad memberdescr type")) return w_result
|
"guard_class", "guard_nonnull", "guard_isnull",
|
def main(n): s = 0 for i in range(n): s += g(n)[i] return s
|
|
array = arraybox.getref_base()
|
array = arraybox.getint()
|
def do_getarrayitem_raw(cpu, _, arraybox, indexbox, arraydescr): array = arraybox.getref_base() index = indexbox.getint() assert not arraydescr.is_array_of_pointers() if arraydescr.is_array_of_floats(): return BoxFloat(cpu.bh_getarrayitem_raw_f(arraydescr, array, index)) else: return BoxInt(cpu.bh_getarrayitem_raw_i(arraydescr, array, index))
|
self.encode32(mem, 0, regalloc.frame_manager.frame_depth-1)
|
self.encode32(mem, 0, regalloc.frame_manager.frame_depth)
|
def _gen_path_to_exit_path(self, op, args, regalloc, fcond=c.AL): """ types: \xEE = REF \xEF = INT location: \xFC = stack location \xFD = imm location \xFE = Empty arg """
|
n = (regalloc.frame_manager.frame_depth - 1)*WORD
|
n = (regalloc.frame_manager.frame_depth)*WORD
|
def _patch_sp_offset(self, addr, regalloc): cb = ARMv7InMemoryBuilder(addr, ARMv7InMemoryBuilder.size_of_gen_load_int) if regalloc.frame_manager.frame_depth == 1: return n = (regalloc.frame_manager.frame_depth - 1)*WORD self._adjust_sp(n, cb)
|
self.check_loops(getfield_gc=1, setfield_gc=1, everywhere=True)
|
self.check_loops(getfield_gc=0, setfield_gc=1) self.check_loops(getfield_gc=1, setfield_gc=2, everywhere=True)
|
def f(n): xy = self.setup() xy.inst_x = 10 other = self.setup() other.inst_x = 15 while n > 0: myjitdriver.can_enter_jit(xy=xy, n=n, other=other) myjitdriver.jit_merge_point(xy=xy, n=n, other=other) promote_virtualizable(other, 'inst_x') value = other.inst_x # getfield_gc other.inst_x = value + 1 # setfield_gc promote_virtualizable(xy, 'inst_x') xy.inst_x = value + 100 # virtualized away n -= 1 promote_virtualizable(xy, 'inst_x') return xy.inst_x
|
imm_a0 = isinstance(a0, ConstInt) and (a0.getint() <= 0xFF or -1 * a0.getint() <= 0xFF) imm_a1 = isinstance(a1, ConstInt) and (a1.getint() <= 0xFF or -1 * a1.getint() <= 0xFF) l0 = regalloc.make_sure_var_in_reg(a0, imm_fine=imm_a0) l1 = regalloc.make_sure_var_in_reg(a1, [a0], imm_fine=imm_a1) res = regalloc.force_allocate_reg(op.result, [a0, a1]) if imm_a0:
|
boxes = [a0, a1] imm_a0 = self._check_imm_arg(a0) imm_a1 = self._check_imm_arg(a1) if not imm_a0 and imm_a1: l0, box = self._ensure_value_is_boxed(a0, regalloc) l1 = regalloc.make_sure_var_in_reg(a1, [a0]) boxes.append(box) elif imm_a0 and not imm_a1: l0 = regalloc.make_sure_var_in_reg(a0) l1, box = self._ensure_value_is_boxed(a1, regalloc) boxes.append(box) else: l0, box = self._ensure_value_is_boxed(a0, regalloc) boxes.append(box) l1, box = self._ensure_value_is_boxed(a1, regalloc) boxes.append(box) res = regalloc.force_allocate_reg(op.result, boxes) if l0.is_imm():
|
def emit_op_int_sub(self, op, regalloc, fcond): # assuming only one argument is constant a0 = op.getarg(0) a1 = op.getarg(1) imm_a0 = isinstance(a0, ConstInt) and (a0.getint() <= 0xFF or -1 * a0.getint() <= 0xFF) imm_a1 = isinstance(a1, ConstInt) and (a1.getint() <= 0xFF or -1 * a1.getint() <= 0xFF) l0 = regalloc.make_sure_var_in_reg(a0, imm_fine=imm_a0) l1 = regalloc.make_sure_var_in_reg(a1, [a0], imm_fine=imm_a1) res = regalloc.force_allocate_reg(op.result, [a0, a1]) if imm_a0: value = l0.getint() if value < 0: # XXX needs a test self.mc.ADD_ri(res.value, l1.value, -1 * value, s=1) self.mc.MVN_rr(res.value, l1.value, s=1) else: # reverse substract ftw self.mc.RSB_ri(res.value, l1.value, value, s=1) elif imm_a1: value = l1.getint() if value < 0: self.mc.ADD_ri(res.value, l0.value, -1 * value, s=1) else: self.mc.SUB_ri(res.value, l0.value, value, s=1) else: self.mc.SUB_rr(res.value, l0.value, l1.value, s=1)
|
if value < 0: self.mc.ADD_ri(res.value, l1.value, -1 * value, s=1) self.mc.MVN_rr(res.value, l1.value, s=1) else: self.mc.RSB_ri(res.value, l1.value, value, s=1) elif imm_a1:
|
assert value >= 0 self.mc.RSB_ri(res.value, l1.value, value, s=1) elif l1.is_imm():
|
def emit_op_int_sub(self, op, regalloc, fcond): # assuming only one argument is constant a0 = op.getarg(0) a1 = op.getarg(1) imm_a0 = isinstance(a0, ConstInt) and (a0.getint() <= 0xFF or -1 * a0.getint() <= 0xFF) imm_a1 = isinstance(a1, ConstInt) and (a1.getint() <= 0xFF or -1 * a1.getint() <= 0xFF) l0 = regalloc.make_sure_var_in_reg(a0, imm_fine=imm_a0) l1 = regalloc.make_sure_var_in_reg(a1, [a0], imm_fine=imm_a1) res = regalloc.force_allocate_reg(op.result, [a0, a1]) if imm_a0: value = l0.getint() if value < 0: # XXX needs a test self.mc.ADD_ri(res.value, l1.value, -1 * value, s=1) self.mc.MVN_rr(res.value, l1.value, s=1) else: # reverse substract ftw self.mc.RSB_ri(res.value, l1.value, value, s=1) elif imm_a1: value = l1.getint() if value < 0: self.mc.ADD_ri(res.value, l0.value, -1 * value, s=1) else: self.mc.SUB_ri(res.value, l0.value, value, s=1) else: self.mc.SUB_rr(res.value, l0.value, l1.value, s=1)
|
if value < 0: self.mc.ADD_ri(res.value, l0.value, -1 * value, s=1) else: self.mc.SUB_ri(res.value, l0.value, value, s=1)
|
assert value >= 0 self.mc.SUB_ri(res.value, l0.value, value, s=1)
|
def emit_op_int_sub(self, op, regalloc, fcond): # assuming only one argument is constant a0 = op.getarg(0) a1 = op.getarg(1) imm_a0 = isinstance(a0, ConstInt) and (a0.getint() <= 0xFF or -1 * a0.getint() <= 0xFF) imm_a1 = isinstance(a1, ConstInt) and (a1.getint() <= 0xFF or -1 * a1.getint() <= 0xFF) l0 = regalloc.make_sure_var_in_reg(a0, imm_fine=imm_a0) l1 = regalloc.make_sure_var_in_reg(a1, [a0], imm_fine=imm_a1) res = regalloc.force_allocate_reg(op.result, [a0, a1]) if imm_a0: value = l0.getint() if value < 0: # XXX needs a test self.mc.ADD_ri(res.value, l1.value, -1 * value, s=1) self.mc.MVN_rr(res.value, l1.value, s=1) else: # reverse substract ftw self.mc.RSB_ri(res.value, l1.value, value, s=1) elif imm_a1: value = l1.getint() if value < 0: self.mc.ADD_ri(res.value, l0.value, -1 * value, s=1) else: self.mc.SUB_ri(res.value, l0.value, value, s=1) else: self.mc.SUB_rr(res.value, l0.value, l1.value, s=1)
|
regalloc.possibly_free_var(a0) regalloc.possibly_free_var(a1)
|
regalloc.possibly_free_vars(boxes)
|
def emit_op_int_sub(self, op, regalloc, fcond): # assuming only one argument is constant a0 = op.getarg(0) a1 = op.getarg(1) imm_a0 = isinstance(a0, ConstInt) and (a0.getint() <= 0xFF or -1 * a0.getint() <= 0xFF) imm_a1 = isinstance(a1, ConstInt) and (a1.getint() <= 0xFF or -1 * a1.getint() <= 0xFF) l0 = regalloc.make_sure_var_in_reg(a0, imm_fine=imm_a0) l1 = regalloc.make_sure_var_in_reg(a1, [a0], imm_fine=imm_a1) res = regalloc.force_allocate_reg(op.result, [a0, a1]) if imm_a0: value = l0.getint() if value < 0: # XXX needs a test self.mc.ADD_ri(res.value, l1.value, -1 * value, s=1) self.mc.MVN_rr(res.value, l1.value, s=1) else: # reverse substract ftw self.mc.RSB_ri(res.value, l1.value, value, s=1) elif imm_a1: value = l1.getint() if value < 0: self.mc.ADD_ri(res.value, l0.value, -1 * value, s=1) else: self.mc.SUB_ri(res.value, l0.value, value, s=1) else: self.mc.SUB_rr(res.value, l0.value, l1.value, s=1)
|
l1 = regalloc.make_sure_var_in_reg(ConstInt(-1), [arg], imm_fine=False)
|
self.mc.MVN_ri(r.ip.value, imm=~-1)
|
def emit_op_int_neg(self, op, regalloc, fcond): arg = op.getarg(0) resbox = op.result l0 = regalloc.make_sure_var_in_reg(arg) l1 = regalloc.make_sure_var_in_reg(ConstInt(-1), [arg], imm_fine=False) resloc = regalloc.force_allocate_reg(resbox, [arg]) self.mc.MUL(resloc.value, l0.value, l1.value) regalloc.possibly_free_vars([arg, resbox]) return fcond
|
self.mc.MUL(resloc.value, l0.value, l1.value)
|
self.mc.MUL(resloc.value, l0.value, r.ip.value)
|
def emit_op_int_neg(self, op, regalloc, fcond): arg = op.getarg(0) resbox = op.result l0 = regalloc.make_sure_var_in_reg(arg) l1 = regalloc.make_sure_var_in_reg(ConstInt(-1), [arg], imm_fine=False) resloc = regalloc.force_allocate_reg(resbox, [arg]) self.mc.MUL(resloc.value, l0.value, l1.value) regalloc.possibly_free_vars([arg, resbox]) return fcond
|
if isinstance(res, BorrowedPair):
|
if res is None: return res elif isinstance(res, BorrowedPair):
|
def unwrapper(space, *args): from pypy.module.cpyext.pyobject import Py_DecRef from pypy.module.cpyext.pyobject import make_ref, from_ref from pypy.module.cpyext.pyobject import BorrowedPair newargs = () to_decref = [] assert len(args) == len(api_function.argtypes) for i, (ARG, is_wrapped) in types_names_enum_ui: input_arg = args[i] if is_PyObject(ARG) and not is_wrapped: # build a reference if input_arg is None: arg = lltype.nullptr(PyObject.TO) elif isinstance(input_arg, W_Root): ref = make_ref(space, input_arg) to_decref.append(ref) arg = rffi.cast(ARG, ref) else: arg = input_arg elif is_PyObject(ARG) and is_wrapped: # convert to a wrapped object if input_arg is None: arg = input_arg elif isinstance(input_arg, W_Root): arg = input_arg else: arg = from_ref(space, input_arg) else: arg = input_arg newargs += (arg, ) try: try: res = func(space, *newargs) except OperationError, e: if not catch_exception: raise if not hasattr(api_function, "error_value"): raise state = space.fromcache(State) state.set_exception(e) if restype is PyObject: return None else: return api_function.error_value if isinstance(res, BorrowedPair): return res.w_borrowed else: return res finally: for arg in to_decref: Py_DecRef(space, arg)
|
T_KEY_MASK = 0xFF000000 T_KEY_VALUE = 0x7A000000
|
T_KEY_MASK = intmask(0xFF000000) T_KEY_VALUE = intmask(0x7A000000)
|
def set_query_functions(self, gc): gc.set_query_functions( self.q_is_varsize, self.q_has_gcptr_in_varsize, self.q_is_gcarrayofgcptr, self.q_finalizer, self.q_offsets_to_gc_pointers, self.q_fixed_size, self.q_varsize_item_sizes, self.q_varsize_offset_to_variable_part, self.q_varsize_offset_to_length, self.q_varsize_offsets_to_gcpointers_in_var_part, self.q_weakpointer_offset, self.q_member_index)
|
while n > 0:
|
action.reset_ticker(n) while True:
|
def f(n): x = X() while n > 0: myjitdriver.can_enter_jit(n=n, x=x) myjitdriver.jit_merge_point(n=n, x=x) x.foo = n n -= 1 if action.get() != 0: break action.set(0) return 42
|
if action.get() != 0:
|
if action.decrement_ticker(1) < 0:
|
def f(n): x = X() while n > 0: myjitdriver.can_enter_jit(n=n, x=x) myjitdriver.jit_merge_point(n=n, x=x) x.foo = n n -= 1 if action.get() != 0: break action.set(0) return 42
|
action.set(0)
|
def f(n): x = X() while n > 0: myjitdriver.can_enter_jit(n=n, x=x) myjitdriver.jit_merge_point(n=n, x=x) x.foo = n n -= 1 if action.get() != 0: break action.set(0) return 42
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.