code
stringlengths
1
1.72M
language
stringclasses
1 value
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>, limodou <limodou@gmail.com> and srackham <srackham@gmail.com>. License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) """ import os import sys import code import logging import types import re import optparse import glob import fileutils import settings from utils import web2py_uuid from compileapp import build_environment, read_pyc, run_models_in from restricted import RestrictedError from globals import Request, Response, Session from storage import Storage from admin import w2p_unpack logger = logging.getLogger("web2py") def exec_environment( pyfile='', request=None, response=None, session=None, ): """ .. function:: gluon.shell.exec_environment([pyfile=''[, request=Request() [, response=Response[, session=Session()]]]]) Environment builder and module loader. Builds a web2py environment and optionally executes a Python file into the environment. A Storage dictionary containing the resulting environment is returned. The working directory must be web2py root -- this is the web2py default. """ if request==None: request = Request() if response==None: response = Response() if session==None: session = Session() if request.folder is None: mo = re.match(r'(|.*/)applications/(?P<appname>[^/]+)', pyfile) if mo: appname = mo.group('appname') request.folder = os.path.join('applications', appname) else: request.folder = '' env = build_environment(request, response, session, store_current=False) if pyfile: pycfile = pyfile + 'c' if os.path.isfile(pycfile): exec read_pyc(pycfile) in env else: execfile(pyfile, env) return Storage(env) def env( a, import_models=False, c=None, f=None, dir='', extra_request={}, ): """ Return web2py execution environment for application (a), controller (c), function (f). If import_models is True the exec all application models into the environment. extra_request allows you to pass along any extra variables to the request object before your models get executed. This was mainly done to support web2py_utils.test_runner, however you can use it with any wrapper scripts that need access to the web2py environment. """ request = Request() response = Response() session = Session() request.application = a # Populate the dummy environment with sensible defaults. if not dir: request.folder = os.path.join('applications', a) else: request.folder = dir request.controller = c or 'default' request.function = f or 'index' response.view = '%s/%s.html' % (request.controller, request.function) request.env.path_info = '/%s/%s/%s' % (a, c, f) request.env.http_host = '127.0.0.1:8000' request.env.remote_addr = '127.0.0.1' request.env.web2py_runtime_gae = settings.global_settings.web2py_runtime_gae for k,v in extra_request.items(): request[k] = v # Monkey patch so credentials checks pass. def check_credentials(request, other_application='admin'): return True fileutils.check_credentials = check_credentials environment = build_environment(request, response, session) if import_models: try: run_models_in(environment) except RestrictedError, e: sys.stderr.write(e.traceback+'\n') sys.exit(1) environment['__name__'] = '__main__' return environment def exec_pythonrc(): pythonrc = os.environ.get('PYTHONSTARTUP') if pythonrc and os.path.isfile(pythonrc): try: execfile(pythonrc) except NameError: pass def run( appname, plain=False, import_models=False, startfile=None, bpython=False ): """ Start interactive shell or run Python script (startfile) in web2py controller environment. appname is formatted like: a web2py application name a/c exec the controller c into the application environment """ (a, c, f) = parse_path_info(appname) errmsg = 'invalid application name: %s' % appname if not a: die(errmsg) adir = os.path.join('applications', a) if not os.path.exists(adir): if raw_input('application %s does not exist, create (y/n)?' % a).lower() in ['y', 'yes']: os.mkdir(adir) w2p_unpack('welcome.w2p', adir) for subfolder in ['models','views','controllers', 'databases', 'modules','cron','errors','sessions', 'languages','static','private','uploads']: subpath = os.path.join(adir,subfolder) if not os.path.exists(subpath): os.mkdir(subpath) db = os.path.join(adir,'models/db.py') if os.path.exists(db): data = fileutils.read_file(db) data = data.replace('<your secret key>','sha512:'+web2py_uuid()) fileutils.write_file(db, data) if c: import_models = True _env = env(a, c=c, import_models=import_models) if c: cfile = os.path.join('applications', a, 'controllers', c + '.py') if not os.path.isfile(cfile): cfile = os.path.join('applications', a, 'compiled', "controllers_%s_%s.pyc" % (c,f)) if not os.path.isfile(cfile): die(errmsg) else: exec read_pyc(cfile) in _env else: execfile(cfile, _env) if f: exec ('print %s()' % f, _env) elif startfile: exec_pythonrc() try: execfile(startfile, _env) except RestrictedError, e: print e.traceback else: if not plain: if bpython: try: import bpython bpython.embed(locals_=_env) return except: logger.warning( 'import bpython error; trying ipython...') else: try: import IPython # following 2 lines fix a problem with IPython; thanks Michael Toomim if '__builtins__' in _env: del _env['__builtins__'] shell = IPython.Shell.IPShell(argv=[], user_ns=_env) shell.mainloop() return except: logger.warning( 'import IPython error; use default python shell') try: import readline import rlcompleter except ImportError: pass else: readline.set_completer(rlcompleter.Completer(_env).complete) readline.parse_and_bind('tab:complete') exec_pythonrc() code.interact(local=_env) def parse_path_info(path_info): """ Parse path info formatted like a/c/f where c and f are optional and a leading / accepted. Return tuple (a, c, f). If invalid path_info a is set to None. If c or f are omitted they are set to None. """ mo = re.match(r'^/?(?P<a>\w+)(/(?P<c>\w+)(/(?P<f>\w+))?)?$', path_info) if mo: return (mo.group('a'), mo.group('c'), mo.group('f')) else: return (None, None, None) def die(msg): print >> sys.stderr, msg sys.exit(1) def test(testpath, import_models=True, verbose=False): """ Run doctests in web2py environment. testpath is formatted like: a tests all controllers in application a a/c tests controller c in application a a/c/f test function f in controller c, application a Where a, c and f are application, controller and function names respectively. If the testpath is a file name the file is tested. If a controller is specified models are executed by default. """ import doctest if os.path.isfile(testpath): mo = re.match(r'(|.*/)applications/(?P<a>[^/]+)', testpath) if not mo: die('test file is not in application directory: %s' % testpath) a = mo.group('a') c = f = None files = [testpath] else: (a, c, f) = parse_path_info(testpath) errmsg = 'invalid test path: %s' % testpath if not a: die(errmsg) cdir = os.path.join('applications', a, 'controllers') if not os.path.isdir(cdir): die(errmsg) if c: cfile = os.path.join(cdir, c + '.py') if not os.path.isfile(cfile): die(errmsg) files = [cfile] else: files = glob.glob(os.path.join(cdir, '*.py')) for testfile in files: globs = env(a, import_models) ignores = globs.keys() execfile(testfile, globs) def doctest_object(name, obj): """doctest obj and enclosed methods and classes.""" if type(obj) in (types.FunctionType, types.TypeType, types.ClassType, types.MethodType, types.UnboundMethodType): # Reload environment before each test. globs = env(a, c=c, f=f, import_models=import_models) execfile(testfile, globs) doctest.run_docstring_examples(obj, globs=globs, name='%s: %s' % (os.path.basename(testfile), name), verbose=verbose) if type(obj) in (types.TypeType, types.ClassType): for attr_name in dir(obj): # Execute . operator so decorators are executed. o = eval('%s.%s' % (name, attr_name), globs) doctest_object(attr_name, o) for (name, obj) in globs.items(): if name not in ignores and (f is None or f == name): doctest_object(name, obj) def get_usage(): usage = """ %prog [options] pythonfile """ return usage def execute_from_command_line(argv=None): if argv is None: argv = sys.argv parser = optparse.OptionParser(usage=get_usage()) parser.add_option('-S', '--shell', dest='shell', metavar='APPNAME', help='run web2py in interactive shell or IPython(if installed) ' + \ 'with specified appname') msg = 'run web2py in interactive shell or bpython (if installed) with' msg += ' specified appname (if app does not exist it will be created).' msg += '\n Use combined with --shell' parser.add_option( '-B', '--bpython', action='store_true', default=False, dest='bpython', help=msg, ) parser.add_option( '-P', '--plain', action='store_true', default=False, dest='plain', help='only use plain python shell, should be used with --shell option', ) parser.add_option( '-M', '--import_models', action='store_true', default=False, dest='import_models', help='auto import model files, default is False, ' + \ ' should be used with --shell option', ) parser.add_option( '-R', '--run', dest='run', metavar='PYTHON_FILE', default='', help='run PYTHON_FILE in web2py environment, ' + \ 'should be used with --shell option', ) (options, args) = parser.parse_args(argv[1:]) if len(sys.argv) == 1: parser.print_help() sys.exit(0) if len(args) > 0: startfile = args[0] else: startfile = '' run(options.shell, options.plain, startfile=startfile, bpython=options.bpython) if __name__ == '__main__': execute_from_command_line()
Python
# -*- coding: utf-8 -*- # This file is part of the Rocket Web Server # Copyright (c) 2010 Timothy Farrell # Import System Modules import sys import errno import socket import logging import platform # Define Constants VERSION = '1.2.2' SERVER_NAME = socket.gethostname() SERVER_SOFTWARE = 'Rocket %s' % VERSION HTTP_SERVER_SOFTWARE = '%s Python/%s' % (SERVER_SOFTWARE, sys.version.split(' ')[0]) BUF_SIZE = 16384 SOCKET_TIMEOUT = 1 # in secs THREAD_STOP_CHECK_INTERVAL = 1 # in secs, How often should threads check for a server stop message? IS_JYTHON = platform.system() == 'Java' # Handle special cases for Jython IGNORE_ERRORS_ON_CLOSE = set([errno.ECONNABORTED, errno.ECONNRESET]) DEFAULT_LISTEN_QUEUE_SIZE = 5 DEFAULT_MIN_THREADS = 10 DEFAULT_MAX_THREADS = 0 DEFAULTS = dict(LISTEN_QUEUE_SIZE = DEFAULT_LISTEN_QUEUE_SIZE, MIN_THREADS = DEFAULT_MIN_THREADS, MAX_THREADS = DEFAULT_MAX_THREADS) PY3K = sys.version_info[0] > 2 class NullHandler(logging.Handler): "A Logging handler to prevent library errors." def emit(self, record): pass if PY3K: def b(val): """ Convert string/unicode/bytes literals into bytes. This allows for the same code to run on Python 2.x and 3.x. """ if isinstance(val, str): return val.encode() else: return val def u(val, encoding="us-ascii"): """ Convert bytes into string/unicode. This allows for the same code to run on Python 2.x and 3.x. """ if isinstance(val, bytes): return val.decode(encoding) else: return val else: def b(val): """ Convert string/unicode/bytes literals into bytes. This allows for the same code to run on Python 2.x and 3.x. """ if isinstance(val, unicode): return val.encode() else: return val def u(val, encoding="us-ascii"): """ Convert bytes into string/unicode. This allows for the same code to run on Python 2.x and 3.x. """ if isinstance(val, str): return val.decode(encoding) else: return val # Import Package Modules # package imports removed in monolithic build __all__ = ['VERSION', 'SERVER_SOFTWARE', 'HTTP_SERVER_SOFTWARE', 'BUF_SIZE', 'IS_JYTHON', 'IGNORE_ERRORS_ON_CLOSE', 'DEFAULTS', 'PY3K', 'b', 'u', 'Rocket', 'CherryPyWSGIServer', 'SERVER_NAME', 'NullHandler'] # Monolithic build...end of module: rocket\__init__.py # Monolithic build...start of module: rocket\connection.py # Import System Modules import sys import time import socket try: import ssl has_ssl = True except ImportError: has_ssl = False # package imports removed in monolithic build class Connection(object): __slots__ = [ 'setblocking', 'sendall', 'shutdown', 'makefile', 'fileno', 'client_addr', 'client_port', 'server_port', 'socket', 'start_time', 'ssl', 'secure' ] def __init__(self, sock_tuple, port, secure=False): self.client_addr, self.client_port = sock_tuple[1] self.server_port = port self.socket = sock_tuple[0] self.start_time = time.time() self.ssl = has_ssl and isinstance(self.socket, ssl.SSLSocket) self.secure = secure if IS_JYTHON: # In Jython we must set TCP_NODELAY here since it does not # inherit from the listening socket. # See: http://bugs.jython.org/issue1309 self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) self.socket.settimeout(SOCKET_TIMEOUT) self.sendall = self.socket.sendall self.shutdown = self.socket.shutdown self.fileno = self.socket.fileno self.makefile = self.socket.makefile self.setblocking = self.socket.setblocking def close(self): if hasattr(self.socket, '_sock'): try: self.socket._sock.close() except socket.error: info = sys.exc_info() if info[1].errno != socket.EBADF: raise info[1] else: pass self.socket.close() # Monolithic build...end of module: rocket\connection.py # Monolithic build...start of module: rocket\listener.py # Import System Modules import os import socket import logging import traceback from threading import Thread try: import ssl from ssl import SSLError has_ssl = True except ImportError: has_ssl = False class SSLError(socket.error): pass # Import Package Modules # package imports removed in monolithic build class Listener(Thread): """The Listener class is a class responsible for accepting connections and queuing them to be processed by a worker thread.""" def __init__(self, interface, queue_size, active_queue, *args, **kwargs): Thread.__init__(self, *args, **kwargs) # Instance variables self.active_queue = active_queue self.interface = interface self.addr = interface[0] self.port = interface[1] self.secure = len(interface) == 4 and \ os.path.exists(interface[2]) and \ os.path.exists(interface[3]) self.ready = False # Error Log self.err_log = logging.getLogger('Rocket.Errors.Port%i' % self.port) self.err_log.addHandler(NullHandler()) # Build the socket listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if not listener: self.err_log.error("Failed to get socket.") return if self.secure: if not has_ssl: self.err_log.error("ssl module required to serve HTTPS.") return elif not os.path.exists(interface[2]): data = (interface[2], interface[0], interface[1]) self.err_log.error("Cannot find key file " "'%s'. Cannot bind to %s:%s" % data) return elif not os.path.exists(interface[3]): data = (interface[3], interface[0], interface[1]) self.err_log.error("Cannot find certificate file " "'%s'. Cannot bind to %s:%s" % data) return # Set socket options try: listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) except: msg = "Cannot share socket. Using %s:%i exclusively." self.err_log.warning(msg % (self.addr, self.port)) try: if not IS_JYTHON: listener.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) except: msg = "Cannot set TCP_NODELAY, things might run a little slower" self.err_log.warning(msg) try: listener.bind((self.addr, self.port)) except: msg = "Socket %s:%i in use by other process and it won't share." self.err_log.error(msg % (self.addr, self.port)) else: # We want socket operations to timeout periodically so we can # check if the server is shutting down listener.settimeout(THREAD_STOP_CHECK_INTERVAL) # Listen for new connections allowing queue_size number of # connections to wait before rejecting a connection. listener.listen(queue_size) self.listener = listener self.ready = True def wrap_socket(self, sock): try: sock = ssl.wrap_socket(sock, keyfile = self.interface[2], certfile = self.interface[3], server_side = True, ssl_version = ssl.PROTOCOL_SSLv23) except SSLError: # Generally this happens when an HTTP request is received on a # secure socket. We don't do anything because it will be detected # by Worker and dealt with appropriately. pass return sock def run(self): if not self.ready: self.err_log.warning('Listener started when not ready.') return if __debug__: self.err_log.debug('Entering main loop.') while True: try: sock, addr = self.listener.accept() if self.secure: sock = self.wrap_socket(sock) self.active_queue.put(((sock, addr), self.interface[1], self.secure)) except socket.timeout: # socket.timeout will be raised every THREAD_STOP_CHECK_INTERVAL # seconds. When that happens, we check if it's time to die. if not self.ready: if __debug__: self.err_log.debug('Listener exiting.') return else: continue except: self.err_log.error(str(traceback.format_exc())) # Monolithic build...end of module: rocket\listener.py # Monolithic build...start of module: rocket\main.py # Import System Modules import sys import time import socket import logging import traceback try: from queue import Queue except ImportError: from Queue import Queue # Import Package Modules # package imports removed in monolithic build # Setup Logging log = logging.getLogger('Rocket') log.addHandler(NullHandler()) class Rocket(object): """The Rocket class is responsible for handling threads and accepting and dispatching connections.""" def __init__(self, interfaces = ('127.0.0.1', 8000), method = 'wsgi', app_info = None, min_threads = None, max_threads = None, queue_size = None, timeout = 600, handle_signals = True): self.handle_signals = handle_signals if not isinstance(interfaces, list): self.interfaces = [interfaces] else: self.interfaces = interfaces if min_threads is None: min_threads = DEFAULTS['MIN_THREADS'] if max_threads is None: max_threads = DEFAULTS['MAX_THREADS'] if not queue_size: if hasattr(socket, 'SOMAXCONN'): queue_size = socket.SOMAXCONN else: queue_size = DEFAULTS['LISTEN_QUEUE_SIZE'] if max_threads and queue_size > max_threads: queue_size = max_threads if isinstance(app_info, dict): app_info['server_software'] = SERVER_SOFTWARE monitor_queue = Queue() active_queue = Queue() self._monitor = Monitor(monitor_queue, active_queue, timeout) self._threadpool = ThreadPool(get_method(method), app_info = app_info, active_queue=active_queue, monitor_queue = monitor_queue, min_threads=min_threads, max_threads=max_threads) # Build our socket listeners self.listeners = [Listener(i, queue_size, active_queue) for i in self.interfaces] for ndx in range(len(self.listeners)-1, 0, -1): if not self.listeners[ndx].ready: del self.listeners[ndx] if not self.listeners: log.critical("No interfaces to listen on...closing.") sys.exit(1) def _sigterm(self, signum, frame): log.info('Received SIGTERM') self.stop() def _sighup(self, signum, frame): log.info('Received SIGHUP') self.restart() def start(self): log.info('Starting %s' % SERVER_SOFTWARE) # Set up our shutdown signals if self.handle_signals: try: import signal signal.signal(signal.SIGTERM, self._sigterm) signal.signal(signal.SIGUSR1, self._sighup) except: log.debug('This platform does not support signals.') # Start our worker threads self._threadpool.start() # Start our monitor thread self._monitor.setDaemon(True) self._monitor.start() # I know that EXPR and A or B is bad but I'm keeping it for Py2.4 # compatibility. str_extract = lambda l: (l.addr, l.port, l.secure and '*' or '') msg = 'Listening on sockets: ' msg += ', '.join(['%s:%i%s' % str_extract(l) for l in self.listeners]) log.info(msg) for l in self.listeners: l.start() tp = self._threadpool dynamic_resize = tp.dynamic_resize while not tp.stop_server: try: dynamic_resize() time.sleep(THREAD_STOP_CHECK_INTERVAL) except KeyboardInterrupt: # Capture a keyboard interrupt when running from a console break except: if not tp.stop_server: log.error(str(traceback.format_exc())) continue return self.stop() def stop(self, stoplogging = True): log.info("Stopping Server") # Stop listeners for l in self.listeners: l.ready = False if l.isAlive(): l.join() # Stop Worker threads self._threadpool.stop() # Stop Monitor self._monitor.stop() if self._monitor.isAlive(): self._monitor.join() if stoplogging: logging.shutdown() def restart(self): self.stop(False) self.start() def CherryPyWSGIServer(bind_addr, wsgi_app, numthreads = 10, server_name = None, max = -1, request_queue_size = 5, timeout = 10, shutdown_timeout = 5): """ A Cherrypy wsgiserver-compatible wrapper. """ max_threads = max if max_threads < 0: max_threads = 0 return Rocket(bind_addr, 'wsgi', {'wsgi_app': wsgi_app}, min_threads = numthreads, max_threads = max_threads, queue_size = request_queue_size, timeout = timeout) # Monolithic build...end of module: rocket\main.py # Monolithic build...start of module: rocket\monitor.py # Import System Modules import time import logging import select from threading import Thread # Import Package Modules # package imports removed in monolithic build class Monitor(Thread): # Monitor worker class. def __init__(self, monitor_queue, active_queue, timeout, *args, **kwargs): Thread.__init__(self, *args, **kwargs) # Instance Variables self.monitor_queue = monitor_queue self.active_queue = active_queue self.timeout = timeout self.connections = set() self.active = False def run(self): self.name = self.getName() self.log = logging.getLogger('Rocket.Monitor') self.log.addHandler(NullHandler()) self.active = True conn_list = list() list_changed = False if __debug__: self.log.debug('Entering monitor loop.') # Enter thread main loop while self.active: # Move the queued connections to the selection pool while not self.monitor_queue.empty() or not len(self.connections): if __debug__: self.log.debug('In "receive timed-out connections" loop.') c = self.monitor_queue.get() if c is None: # A non-client is a signal to die if __debug__: self.log.debug('Received a death threat.') return self.log.debug('Received a timed out connection.') if __debug__: assert(c not in self.connections) if IS_JYTHON: # Jython requires a socket to be in Non-blocking mode in # order to select on it. c.setblocking(False) if __debug__: self.log.debug('Adding connection to monitor list.') self.connections.add(c) list_changed = True # Wait on those connections self.log.debug('Blocking on connections') if list_changed: conn_list = list(self.connections) list_changed = False try: readable = select.select(conn_list, [], [], THREAD_STOP_CHECK_INTERVAL)[0] except: if self.active: raise else: break # If we have any readable connections, put them back for r in readable: if __debug__: self.log.debug('Restoring readable connection') if IS_JYTHON: # Jython requires a socket to be in Non-blocking mode in # order to select on it, but the rest of the code requires # that it be in blocking mode. r.setblocking(True) r.start_time = time.time() self.active_queue.put(r) self.connections.remove(r) list_changed = True # If we have any stale connections, kill them off. if self.timeout: now = time.time() stale = set() for c in self.connections: if (now - c.start_time) >= self.timeout: stale.add(c) for c in stale: if __debug__: # "EXPR and A or B" kept for Py2.4 compatibility data = (c.client_addr, c.server_port, c.ssl and '*' or '') self.log.debug('Flushing stale connection: %s:%i%s' % data) self.connections.remove(c) list_changed = True try: c.close() finally: del c def stop(self): self.active = False if __debug__: self.log.debug('Flushing waiting connections') for c in self.connections: try: c.close() finally: del c if __debug__: self.log.debug('Flushing queued connections') while not self.monitor_queue.empty(): c = self.monitor_queue.get() if c is None: continue try: c.close() finally: del c # Place a None sentry value to cause the monitor to die. self.monitor_queue.put(None) # Monolithic build...end of module: rocket\monitor.py # Monolithic build...start of module: rocket\threadpool.py # Import System Modules import logging # Import Package Modules # package imports removed in monolithic build # Setup Logging log = logging.getLogger('Rocket.Errors.ThreadPool') log.addHandler(NullHandler()) class ThreadPool: """The ThreadPool class is a container class for all the worker threads. It manages the number of actively running threads.""" def __init__(self, method, app_info, active_queue, monitor_queue, min_threads=DEFAULTS['MIN_THREADS'], max_threads=DEFAULTS['MAX_THREADS'], ): if __debug__: log.debug("Initializing ThreadPool.") self.check_for_dead_threads = 0 self.active_queue = active_queue self.worker_class = method self.min_threads = min_threads self.max_threads = max_threads self.monitor_queue = monitor_queue self.stop_server = False # TODO - Optimize this based on some real-world usage data self.grow_threshold = int(max_threads/10) + 2 if not isinstance(app_info, dict): app_info = dict() app_info.update(max_threads=max_threads, min_threads=min_threads) self.app_info = app_info self.threads = set() for x in range(min_threads): worker = self.worker_class(app_info, self.active_queue, self.monitor_queue) self.threads.add(worker) def start(self): self.stop_server = False if __debug__: log.debug("Starting threads.") for thread in self.threads: thread.setDaemon(True) thread.start() def stop(self): if __debug__: log.debug("Stopping threads.") self.stop_server = True # Prompt the threads to die for t in self.threads: self.active_queue.put(None) # Give them the gun for t in self.threads: t.kill() # Wait until they pull the trigger for t in self.threads: t.join() # Clean up the mess self.bring_out_your_dead() def bring_out_your_dead(self): # Remove dead threads from the pool dead_threads = [t for t in self.threads if not t.isAlive()] for t in dead_threads: if __debug__: log.debug("Removing dead thread: %s." % t.getName()) try: # Py2.4 complains here so we put it in a try block self.threads.remove(t) except: pass self.check_for_dead_threads -= len(dead_threads) def grow(self, amount=None): if self.stop_server: return if not amount: amount = self.max_threads amount = min([amount, self.max_threads - len(self.threads)]) if __debug__: log.debug("Growing by %i." % amount) for x in range(amount): worker = self.worker_class(self.app_info, self.active_queue, self.monitor_queue) worker.setDaemon(True) self.threads.add(worker) worker.start() def shrink(self, amount=1): if __debug__: log.debug("Shrinking by %i." % amount) self.check_for_dead_threads += amount for x in range(amount): self.active_queue.put(None) def dynamic_resize(self): if (self.max_threads > self.min_threads or self.max_threads == 0): if self.check_for_dead_threads > 0: self.bring_out_your_dead() queueSize = self.active_queue.qsize() threadCount = len(self.threads) if __debug__: log.debug("Examining ThreadPool. %i threads and %i Q'd conxions" % (threadCount, queueSize)) if queueSize == 0 and threadCount > self.min_threads: self.shrink() elif queueSize > self.grow_threshold: self.grow(queueSize) # Monolithic build...end of module: rocket\threadpool.py # Monolithic build...start of module: rocket\worker.py # Import System Modules import re import sys import socket import logging import traceback #from wsgiref.headers import Headers from threading import Thread from datetime import datetime try: from urllib import unquote except ImportError: from urllib.parse import unquote try: from io import StringIO except ImportError: try: from cStringIO import StringIO except ImportError: from StringIO import StringIO try: from ssl import SSLError except ImportError: class SSLError(socket.error): pass # Import Package Modules # package imports removed in monolithic build # Define Constants re_SLASH = re.compile('%2F', re.IGNORECASE) re_REQUEST_LINE = re.compile(r"""^ (?P<method>OPTIONS|GET|HEAD|POST|PUT|DELETE|TRACE|CONNECT) # Request Method \ # (single space) ( (?P<scheme>[^:/]+) # Scheme (://) # (?P<host>[^/]+) # Host )? # (?P<path>(\*|/[^ \?]*)) # Path (\? (?P<query_string>[^ ]+))? # Query String \ # (single space) (?P<protocol>HTTPS?/1\.[01]) # Protocol $ """, re.X) LOG_LINE = '%(client_ip)s - "%(request_line)s" - %(status)s %(size)s' RESPONSE = '''\ HTTP/1.1 %s Content-Length: %i Content-Type: %s %s ''' if IS_JYTHON: HTTP_METHODS = set(['OPTIONS', 'GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'TRACE', 'CONNECT']) ### # The Headers and FileWrapper classes are ripped straight from the Python # Standard Library. I've removed some docstrings and integrated my BUF_SIZE. # See the Python License here: http://docs.python.org/license.html ### # Regular expression that matches `special' characters in parameters, the # existance of which force quoting of the parameter value. import re _tspecials = re.compile(r'[ \(\)<>@,;:\\"/\[\]\?=]') def _formatparam(param, value=None, quote=1): """Convenience function to format and return a key=value pair. This will quote the value if needed or if quote is true. """ if value is not None and len(value) > 0: if quote or _tspecials.search(value): value = value.replace('\\', '\\\\').replace('"', r'\"') return '%s="%s"' % (param, value) else: return '%s=%s' % (param, value) else: return param class Headers: def __init__(self,headers): if type(headers) is not type([]): raise TypeError("Headers must be a list of name/value tuples") self._headers = headers def __len__(self): return len(self._headers) def __setitem__(self, name, val): del self[name] self._headers.append((name, val)) def __delitem__(self,name): name = name.lower() self._headers[:] = [kv for kv in self._headers if kv[0].lower() != name] def __getitem__(self,name): return self.get(name) def has_key(self, name): return self.get(name) is not None __contains__ = has_key def get_all(self, name): name = name.lower() return [kv[1] for kv in self._headers if kv[0].lower()==name] def get(self,name,default=None): name = name.lower() for k,v in self._headers: if k.lower()==name: return v return default def keys(self): return [k for k, v in self._headers] def values(self): return [v for k, v in self._headers] def items(self): return self._headers[:] def __repr__(self): return "Headers(%r)" % self._headers def __str__(self): return '\r\n'.join(["%s: %s" % kv for kv in self._headers]+['','']) def setdefault(self,name,value): result = self.get(name) if result is None: self._headers.append((name,value)) return value else: return result def add_header(self, _name, _value, **_params): parts = [] if _value is not None: parts.append(_value) for k, v in _params.items(): if v is None: parts.append(k.replace('_', '-')) else: parts.append(_formatparam(k.replace('_', '-'), v)) self._headers.append((_name, "; ".join(parts))) class FileWrapper: """Wrapper to convert file-like objects to iterables""" def __init__(self, filelike, blksize=BUF_SIZE): self.filelike = filelike self.blksize = blksize if hasattr(filelike,'close'): self.close = filelike.close def __getitem__(self,key): data = self.filelike.read(self.blksize) if data: return data raise IndexError def __iter__(self): return self def next(self): data = self.filelike.read(self.blksize) if data: return data raise StopIteration class Worker(Thread): """The Worker class is a base class responsible for receiving connections and (a subclass) will run an application to process the the connection """ def __init__(self, app_info, active_queue, monitor_queue, *args, **kwargs): Thread.__init__(self, *args, **kwargs) # Instance Variables self.app_info = app_info self.active_queue = active_queue self.monitor_queue = monitor_queue self.size = 0 self.status = "200 OK" self.closeConnection = True # Request Log self.req_log = logging.getLogger('Rocket.Requests') self.req_log.addHandler(NullHandler()) # Error Log self.err_log = logging.getLogger('Rocket.Errors.'+self.getName()) self.err_log.addHandler(NullHandler()) def _handleError(self, typ, val, tb): if typ == SSLError: if 'timed out' in val.args[0]: typ = SocketTimeout if typ == SocketTimeout: if __debug__: self.err_log.debug('Socket timed out') self.monitor_queue.put(self.conn) return True if typ == SocketClosed: self.closeConnection = True if __debug__: self.err_log.debug('Client closed socket') return False if typ == BadRequest: self.closeConnection = True if __debug__: self.err_log.debug('Client sent a bad request') return True if typ == socket.error: self.closeConnection = True if val.args[0] in IGNORE_ERRORS_ON_CLOSE: if __debug__: self.err_log.debug('Ignorable socket Error received...' 'closing connection.') return False else: self.status = "999 Utter Server Failure" tb_fmt = traceback.format_exception(typ, val, tb) self.err_log.error('Unhandled Error when serving ' 'connection:\n' + '\n'.join(tb_fmt)) return False self.closeConnection = True tb_fmt = traceback.format_exception(typ, val, tb) self.err_log.error('\n'.join(tb_fmt)) self.send_response('500 Server Error') return False def run(self): if __debug__: self.err_log.debug('Entering main loop.') # Enter thread main loop while True: conn = self.active_queue.get() if not conn: # A non-client is a signal to die if __debug__: self.err_log.debug('Received a death threat.') return conn if isinstance(conn, tuple): conn = Connection(*conn) self.conn = conn if conn.ssl != conn.secure: self.err_log.info('Received HTTP connection on HTTPS port.') self.send_response('400 Bad Request') self.closeConnection = True conn.close() continue else: if __debug__: self.err_log.debug('Received a connection.') self.closeConnection = False # Enter connection serve loop while True: if __debug__: self.err_log.debug('Serving a request') try: self.run_app(conn) log_info = dict(client_ip = conn.client_addr, time = datetime.now().strftime('%c'), status = self.status.split(' ')[0], size = self.size, request_line = self.request_line) self.req_log.info(LOG_LINE % log_info) except: exc = sys.exc_info() handled = self._handleError(*exc) if handled: break else: if self.request_line: log_info = dict(client_ip = conn.client_addr, time = datetime.now().strftime('%c'), status = self.status.split(' ')[0], size = self.size, request_line = self.request_line + ' - not stopping') self.req_log.info(LOG_LINE % log_info) if self.closeConnection: try: conn.close() except: self.err_log.error(str(traceback.format_exc())) break def run_app(self, conn): # Must be overridden with a method reads the request from the socket # and sends a response. self.closeConnection = True raise NotImplementedError('Overload this method!') def send_response(self, status): stat_msg = status.split(' ', 1)[1] msg = RESPONSE % (status, len(stat_msg), 'text/plain', stat_msg) try: self.conn.sendall(b(msg)) except socket.error: self.closeConnection = True self.err_log.error('Tried to send "%s" to client but received socket' ' error' % status) def kill(self): if self.isAlive() and hasattr(self, 'conn'): try: self.conn.shutdown(socket.SHUT_RDWR) except socket.error: info = sys.exc_info() if info[1].args[0] != socket.EBADF: self.err_log.debug('Error on shutdown: '+str(info)) def read_request_line(self, sock_file): self.request_line = '' try: # Grab the request line d = sock_file.readline() if PY3K: d = d.decode('ISO-8859-1') if d == '\r\n': # Allow an extra NEWLINE at the beginning per HTTP 1.1 spec if __debug__: self.err_log.debug('Client sent newline') d = sock_file.readline() if PY3K: d = d.decode('ISO-8859-1') except socket.timeout: raise SocketTimeout("Socket timed out before request.") d = d.strip() if not d: if __debug__: self.err_log.debug('Client did not send a recognizable request.') raise SocketClosed('Client closed socket.') self.request_line = d # NOTE: I've replaced the traditional method of procedurally breaking # apart the request line with a (rather unsightly) regular expression. # However, Java's regexp support sucks so bad that it actually takes # longer in Jython to process the regexp than procedurally. So I've # left the old code here for Jython's sake...for now. if IS_JYTHON: return self._read_request_line_jython(d) match = re_REQUEST_LINE.match(d) if not match: self.send_response('400 Bad Request') raise BadRequest req = match.groupdict() for k,v in req.items(): if not v: req[k] = "" if k == 'path': req['path'] = r'%2F'.join([unquote(x) for x in re_SLASH.split(v)]) return req def _read_request_line_jython(self, d): d = d.strip() try: method, uri, proto = d.split(' ') if not proto.startswith('HTTP') or \ proto[-3:] not in ('1.0', '1.1') or \ method not in HTTP_METHODS: self.send_response('400 Bad Request') raise BadRequest except ValueError: self.send_response('400 Bad Request') raise BadRequest req = dict(method=method, protocol = proto) scheme = '' host = '' if uri == '*' or uri.startswith('/'): path = uri elif '://' in uri: scheme, rest = uri.split('://') host, path = rest.split('/', 1) path = '/' + path else: self.send_response('400 Bad Request') raise BadRequest query_string = '' if '?' in path: path, query_string = path.split('?', 1) path = r'%2F'.join([unquote(x) for x in re_SLASH.split(path)]) req.update(path=path, query_string=query_string, scheme=scheme.lower(), host=host) return req def read_headers(self, sock_file): headers = dict() l = sock_file.readline() lname = None lval = None while True: if PY3K: try: l = str(l, 'ISO-8859-1') except UnicodeDecodeError: self.err_log.warning('Client sent invalid header: ' + repr(l)) if l == '\r\n': break if l[0] in ' \t' and lname: # Some headers take more than one line lval += ',' + l.strip() else: # HTTP header values are latin-1 encoded l = l.split(':', 1) # HTTP header names are us-ascii encoded lname = l[0].strip().upper().replace('-', '_') lval = l[-1].strip() headers[str(lname)] = str(lval) l = sock_file.readline() return headers class SocketTimeout(Exception): "Exception for when a socket times out between requests." pass class BadRequest(Exception): "Exception for when a client sends an incomprehensible request." pass class SocketClosed(Exception): "Exception for when a socket is closed by the client." pass class ChunkedReader(object): def __init__(self, sock_file): self.stream = sock_file self.chunk_size = 0 def _read_header(self): chunk_len = "" try: while "" == chunk_len: chunk_len = self.stream.readline().strip() return int(chunk_len, 16) except ValueError: return 0 def read(self, size): data = b('') chunk_size = self.chunk_size while size: if not chunk_size: chunk_size = self._read_header() if size < chunk_size: data += self.stream.read(size) chunk_size -= size break else: if not chunk_size: break data += self.stream.read(chunk_size) size -= chunk_size chunk_size = 0 self.chunk_size = chunk_size return data def readline(self): data = b('') c = self.read(1) while c and c != b('\n'): data += c c = self.read(1) data += c return data def readlines(self): yield self.readline() def get_method(method): methods = dict(wsgi=WSGIWorker) return methods[method.lower()] # Monolithic build...end of module: rocket\worker.py # Monolithic build...start of module: rocket\methods\__init__.py # Monolithic build...end of module: rocket\methods\__init__.py # Monolithic build...start of module: rocket\methods\wsgi.py # Import System Modules import sys import socket #from wsgiref.headers import Headers #from wsgiref.util import FileWrapper # Import Package Modules # package imports removed in monolithic build if PY3K: from email.utils import formatdate else: # Caps Utils for Py2.4 compatibility from email.Utils import formatdate # Define Constants NEWLINE = b('\r\n') HEADER_RESPONSE = '''HTTP/1.1 %s\r\n%s''' BASE_ENV = {'SERVER_NAME': SERVER_NAME, 'SCRIPT_NAME': '', # Direct call WSGI does not need a name 'wsgi.errors': sys.stderr, 'wsgi.version': (1, 0), 'wsgi.multiprocess': False, 'wsgi.run_once': False, 'wsgi.file_wrapper': FileWrapper } class WSGIWorker(Worker): def __init__(self, *args, **kwargs): """Builds some instance variables that will last the life of the thread.""" Worker.__init__(self, *args, **kwargs) if isinstance(self.app_info, dict): multithreaded = self.app_info.get('max_threads') != 1 else: multithreaded = False self.base_environ = dict({'SERVER_SOFTWARE': self.app_info['server_software'], 'wsgi.multithread': multithreaded, }) self.base_environ.update(BASE_ENV) # Grab our application self.app = self.app_info.get('wsgi_app') if not hasattr(self.app, "__call__"): raise TypeError("The wsgi_app specified (%s) is not a valid WSGI application." % repr(self.app)) def build_environ(self, sock_file, conn): """ Build the execution environment. """ # Grab the request line request = self.read_request_line(sock_file) # Copy the Base Environment environ = self.base_environ.copy() # Grab the headers for k, v in self.read_headers(sock_file).items(): environ[str('HTTP_'+k)] = v # Add CGI Variables environ['REQUEST_METHOD'] = request['method'] environ['PATH_INFO'] = request['path'] environ['SERVER_PROTOCOL'] = request['protocol'] environ['SERVER_PORT'] = str(conn.server_port) environ['REMOTE_PORT'] = str(conn.client_port) environ['REMOTE_ADDR'] = str(conn.client_addr) environ['QUERY_STRING'] = request['query_string'] if 'HTTP_CONTENT_LENGTH' in environ: environ['CONTENT_LENGTH'] = environ['HTTP_CONTENT_LENGTH'] if 'HTTP_CONTENT_TYPE' in environ: environ['CONTENT_TYPE'] = environ['HTTP_CONTENT_TYPE'] # Save the request method for later self.request_method = environ['REQUEST_METHOD'] # Add Dynamic WSGI Variables if conn.ssl: environ['wsgi.url_scheme'] = 'https' environ['HTTPS'] = 'on' else: environ['wsgi.url_scheme'] = 'http' if environ.get('HTTP_TRANSFER_ENCODING', '') == 'chunked': environ['wsgi.input'] = ChunkedReader(sock_file) else: environ['wsgi.input'] = sock_file return environ def send_headers(self, data, sections): h_set = self.header_set # Does the app want us to send output chunked? self.chunked = h_set.get('transfer-encoding', '').lower() == 'chunked' # Add a Date header if it's not there already if not 'date' in h_set: h_set['Date'] = formatdate(usegmt=True) # Add a Server header if it's not there already if not 'server' in h_set: h_set['Server'] = HTTP_SERVER_SOFTWARE if 'content-length' in h_set: self.size = int(h_set['content-length']) else: s = int(self.status.split(' ')[0]) if s < 200 or s not in (204, 205, 304): if not self.chunked: if sections == 1: # Add a Content-Length header if it's not there already h_set['Content-Length'] = str(len(data)) self.size = len(data) else: # If they sent us more than one section, we blow chunks h_set['Transfer-Encoding'] = 'Chunked' self.chunked = True if __debug__: self.err_log.debug('Adding header...' 'Transfer-Encoding: Chunked') if 'connection' not in h_set: # If the application did not provide a connection header, fill it in client_conn = self.environ.get('HTTP_CONNECTION', '').lower() if self.environ['SERVER_PROTOCOL'] == 'HTTP/1.1': # HTTP = 1.1 defaults to keep-alive connections if client_conn: h_set['Connection'] = client_conn else: h_set['Connection'] = 'keep-alive' else: # HTTP < 1.1 supports keep-alive but it's quirky so we don't support it h_set['Connection'] = 'close' # Close our connection if we need to. self.closeConnection = h_set.get('connection', '').lower() == 'close' # Build our output headers header_data = HEADER_RESPONSE % (self.status, str(h_set)) # Send the headers if __debug__: self.err_log.debug('Sending Headers: %s' % repr(header_data)) self.conn.sendall(b(header_data)) self.headers_sent = True def write_warning(self, data, sections=None): self.err_log.warning('WSGI app called write method directly. This is ' 'deprecated behavior. Please update your app.') return self.write(data, sections) def write(self, data, sections=None): """ Write the data to the output socket. """ if self.error[0]: self.status = self.error[0] data = b(self.error[1]) if not self.headers_sent: self.send_headers(data, sections) if self.request_method != 'HEAD': try: if self.chunked: self.conn.sendall(b('%x\r\n%s\r\n' % (len(data), data))) else: self.conn.sendall(data) except socket.error: # But some clients will close the connection before that # resulting in a socket error. self.closeConnection = True def start_response(self, status, response_headers, exc_info=None): """ Store the HTTP status and headers to be sent when self.write is called. """ if exc_info: try: if self.headers_sent: # Re-raise original exception if headers sent # because this violates WSGI specification. raise finally: exc_info = None elif self.header_set: raise AssertionError("Headers already set!") if PY3K and not isinstance(status, str): self.status = str(status, 'ISO-8859-1') else: self.status = status # Make sure headers are bytes objects try: self.header_set = Headers(response_headers) except UnicodeDecodeError: self.error = ('500 Internal Server Error', 'HTTP Headers should be bytes') self.err_log.error('Received HTTP Headers from client that contain' ' invalid characters for Latin-1 encoding.') return self.write_warning def run_app(self, conn): self.size = 0 self.header_set = Headers([]) self.headers_sent = False self.error = (None, None) self.chunked = False sections = None output = None if __debug__: self.err_log.debug('Getting sock_file') # Build our file-like object sock_file = conn.makefile('rb',BUF_SIZE) try: # Read the headers and build our WSGI environment self.environ = environ = self.build_environ(sock_file, conn) # Handle 100 Continue if environ.get('HTTP_EXPECT', '') == '100-continue': res = environ['SERVER_PROTOCOL'] + ' 100 Continue\r\n\r\n' conn.sendall(b(res)) # Send it to our WSGI application output = self.app(environ, self.start_response) if not hasattr(output, '__len__') and not hasattr(output, '__iter__'): self.error = ('500 Internal Server Error', 'WSGI applications must return a list or ' 'generator type.') if hasattr(output, '__len__'): sections = len(output) for data in output: # Don't send headers until body appears if data: self.write(data, sections) if self.chunked: # If chunked, send our final chunk length self.conn.sendall(b('0\r\n\r\n')) elif not self.headers_sent: # Send headers if the body was empty self.send_headers('', sections) # Don't capture exceptions here. The Worker class handles # them appropriately. finally: if __debug__: self.err_log.debug('Finally closing output and sock_file') if hasattr(output,'close'): output.close() sock_file.close() # Monolithic build...end of module: rocket\methods\wsgi.py # # the following code is not part of Rocket but was added in web2py for testing purposes # def demo_app(environ, start_response): global static_folder import os types = {'htm': 'text/html','html': 'text/html','gif': 'image/gif', 'jpg': 'image/jpeg','png': 'image/png','pdf': 'applications/pdf'} if static_folder: if not static_folder.startswith('/'): static_folder = os.path.join(os.getcwd(),static_folder) path = os.path.join(static_folder, environ['PATH_INFO'][1:] or 'index.html') type = types.get(path.split('.')[-1],'text') if os.path.exists(path): try: pathfile = open(path,'rb') try: data = pathfile.read() finally: pathfile.close() start_response('200 OK', [('Content-Type', type)]) except IOError: start_response('404 NOT FOUND', []) data = '404 NOT FOUND' else: start_response('500 INTERNAL SERVER ERROR', []) data = '500 INTERNAL SERVER ERROR' else: start_response('200 OK', [('Content-Type', 'text/html')]) data = '<html><body><h1>Hello from Rocket Web Server</h1></body></html>' return [data] def demo(): from optparse import OptionParser parser = OptionParser() parser.add_option("-i", "--ip", dest="ip",default="127.0.0.1", help="ip address of the network interface") parser.add_option("-p", "--port", dest="port",default="8000", help="post where to run web server") parser.add_option("-s", "--static", dest="static",default=None, help="folder containing static files") (options, args) = parser.parse_args() global static_folder static_folder = options.static print 'Rocket running on %s:%s' % (options.ip, options.port) r=Rocket((options.ip,int(options.port)),'wsgi', {'wsgi_app':demo_app}) r.start() if __name__=='__main__': demo()
Python
#!/bin/python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) """ import base64 import cPickle import datetime import thread import logging import sys import os import re import time import copy import smtplib import urllib import urllib2 import Cookie import cStringIO from email import MIMEBase, MIMEMultipart, MIMEText, Encoders, Header, message_from_string from contenttype import contenttype from storage import Storage, StorageList, Settings, Messages from utils import web2py_uuid from gluon import * from fileutils import read_file import serializers import contrib.simplejson as simplejson __all__ = ['Mail', 'Auth', 'Recaptcha', 'Crud', 'Service', 'PluginManager', 'fetch', 'geocode', 'prettydate'] logger = logging.getLogger("web2py") DEFAULT = lambda: None def callback(actions,form,tablename=None): if actions: if tablename and isinstance(actions,dict): actions = actions.get(tablename, []) if not isinstance(actions,(list, tuple)): actions = [actions] [action(form) for action in actions] def validators(*a): b = [] for item in a: if isinstance(item, (list, tuple)): b = b + list(item) else: b.append(item) return b def call_or_redirect(f,*args): if callable(f): redirect(f(*args)) else: redirect(f) class Mail(object): """ Class for configuring and sending emails with alternative text / html body, multiple attachments and encryption support Works with SMTP and Google App Engine. """ class Attachment(MIMEBase.MIMEBase): """ Email attachment Arguments:: payload: path to file or file-like object with read() method filename: name of the attachment stored in message; if set to None, it will be fetched from payload path; file-like object payload must have explicit filename specified content_id: id of the attachment; automatically contained within < and > content_type: content type of the attachment; if set to None, it will be fetched from filename using gluon.contenttype module encoding: encoding of all strings passed to this function (except attachment body) Content ID is used to identify attachments within the html body; in example, attached image with content ID 'photo' may be used in html message as a source of img tag <img src="cid:photo" />. Examples:: #Create attachment from text file: attachment = Mail.Attachment('/path/to/file.txt') Content-Type: text/plain MIME-Version: 1.0 Content-Disposition: attachment; filename="file.txt" Content-Transfer-Encoding: base64 SOMEBASE64CONTENT= #Create attachment from image file with custom filename and cid: attachment = Mail.Attachment('/path/to/file.png', filename='photo.png', content_id='photo') Content-Type: image/png MIME-Version: 1.0 Content-Disposition: attachment; filename="photo.png" Content-Id: <photo> Content-Transfer-Encoding: base64 SOMEOTHERBASE64CONTENT= """ def __init__( self, payload, filename=None, content_id=None, content_type=None, encoding='utf-8'): if isinstance(payload, str): if filename == None: filename = os.path.basename(payload) payload = read_file(payload, 'rb') else: if filename == None: raise Exception('Missing attachment name') payload = payload.read() filename = filename.encode(encoding) if content_type == None: content_type = contenttype(filename) self.my_filename = filename self.my_payload = payload MIMEBase.MIMEBase.__init__(self, *content_type.split('/', 1)) self.set_payload(payload) self['Content-Disposition'] = 'attachment; filename="%s"' % filename if content_id != None: self['Content-Id'] = '<%s>' % content_id.encode(encoding) Encoders.encode_base64(self) def __init__(self, server=None, sender=None, login=None, tls=True): """ Main Mail object Arguments:: server: SMTP server address in address:port notation sender: sender email address login: sender login name and password in login:password notation or None if no authentication is required tls: enables/disables encryption (True by default) In Google App Engine use:: server='gae' For sake of backward compatibility all fields are optional and default to None, however, to be able to send emails at least server and sender must be specified. They are available under following fields: mail.settings.server mail.settings.sender mail.settings.login When server is 'logging', email is logged but not sent (debug mode) Optionally you can use PGP encryption or X509: mail.settings.cipher_type = None mail.settings.sign = True mail.settings.sign_passphrase = None mail.settings.encrypt = True mail.settings.x509_sign_keyfile = None mail.settings.x509_sign_certfile = None mail.settings.x509_crypt_certfiles = None cipher_type : None gpg - need a python-pyme package and gpgme lib x509 - smime sign : sign the message (True or False) sign_passphrase : passphrase for key signing encrypt : encrypt the message ... x509 only ... x509_sign_keyfile : the signers private key filename (PEM format) x509_sign_certfile: the signers certificate filename (PEM format) x509_crypt_certfiles: the certificates file to encrypt the messages with can be a file name or a list of file names (PEM format) Examples:: #Create Mail object with authentication data for remote server: mail = Mail('example.com:25', 'me@example.com', 'me:password') """ settings = self.settings = Settings() settings.server = server settings.sender = sender settings.login = login settings.tls = tls settings.ssl = False settings.cipher_type = None settings.sign = True settings.sign_passphrase = None settings.encrypt = True settings.x509_sign_keyfile = None settings.x509_sign_certfile = None settings.x509_crypt_certfiles = None settings.debug = False settings.lock_keys = True self.result = {} self.error = None def send( self, to, subject='None', message='None', attachments=None, cc=None, bcc=None, reply_to=None, encoding='utf-8', ): """ Sends an email using data specified in constructor Arguments:: to: list or tuple of receiver addresses; will also accept single object subject: subject of the email message: email body text; depends on type of passed object: if 2-list or 2-tuple is passed: first element will be source of plain text while second of html text; otherwise: object will be the only source of plain text and html source will be set to None; If text or html source is: None: content part will be ignored, string: content part will be set to it, file-like object: content part will be fetched from it using it's read() method attachments: list or tuple of Mail.Attachment objects; will also accept single object cc: list or tuple of carbon copy receiver addresses; will also accept single object bcc: list or tuple of blind carbon copy receiver addresses; will also accept single object reply_to: address to which reply should be composed encoding: encoding of all strings passed to this method (including message bodies) Examples:: #Send plain text message to single address: mail.send('you@example.com', 'Message subject', 'Plain text body of the message') #Send html message to single address: mail.send('you@example.com', 'Message subject', '<html>Plain text body of the message</html>') #Send text and html message to three addresses (two in cc): mail.send('you@example.com', 'Message subject', ('Plain text body', '<html>html body</html>'), cc=['other1@example.com', 'other2@example.com']) #Send html only message with image attachment available from the message by 'photo' content id: mail.send('you@example.com', 'Message subject', (None, '<html><img src="cid:photo" /></html>'), Mail.Attachment('/path/to/photo.jpg' content_id='photo')) #Send email with two attachments and no body text mail.send('you@example.com, 'Message subject', None, [Mail.Attachment('/path/to/fist.file'), Mail.Attachment('/path/to/second.file')]) Returns True on success, False on failure. Before return, method updates two object's fields: self.result: return value of smtplib.SMTP.sendmail() or GAE's mail.send_mail() method self.error: Exception message or None if above was successful """ def encode_header(key): if [c for c in key if 32>ord(c) or ord(c)>127]: return Header.Header(key.encode('utf-8'),'utf-8') else: return key if not isinstance(self.settings.server, str): raise Exception('Server address not specified') if not isinstance(self.settings.sender, str): raise Exception('Sender address not specified') payload_in = MIMEMultipart.MIMEMultipart('mixed') if to: if not isinstance(to, (list,tuple)): to = [to] else: raise Exception('Target receiver address not specified') if cc: if not isinstance(cc, (list, tuple)): cc = [cc] if bcc: if not isinstance(bcc, (list, tuple)): bcc = [bcc] if message == None: text = html = None elif isinstance(message, (list, tuple)): text, html = message elif message.strip().startswith('<html') and message.strip().endswith('</html>'): text = self.settings.server=='gae' and message or None html = message else: text = message html = None if text != None or html != None: attachment = MIMEMultipart.MIMEMultipart('alternative') if text != None: if isinstance(text, basestring): text = text.decode(encoding).encode('utf-8') else: text = text.read().decode(encoding).encode('utf-8') attachment.attach(MIMEText.MIMEText(text,_charset='utf-8')) if html != None: if isinstance(html, basestring): html = html.decode(encoding).encode('utf-8') else: html = html.read().decode(encoding).encode('utf-8') attachment.attach(MIMEText.MIMEText(html, 'html',_charset='utf-8')) payload_in.attach(attachment) if attachments == None: pass elif isinstance(attachments, (list, tuple)): for attachment in attachments: payload_in.attach(attachment) else: payload_in.attach(attachments) ####################################################### # CIPHER # ####################################################### cipher_type = self.settings.cipher_type sign = self.settings.sign sign_passphrase = self.settings.sign_passphrase encrypt = self.settings.encrypt ####################################################### # GPGME # ####################################################### if cipher_type == 'gpg': if not sign and not encrypt: self.error="No sign and no encrypt is set but cipher type to gpg" return False # need a python-pyme package and gpgme lib from pyme import core, errors from pyme.constants.sig import mode ############################################ # sign # ############################################ if sign: import string core.check_version(None) pin=string.replace(payload_in.as_string(),'\n','\r\n') plain = core.Data(pin) sig = core.Data() c = core.Context() c.set_armor(1) c.signers_clear() # search for signing key for From: for sigkey in c.op_keylist_all(self.settings.sender, 1): if sigkey.can_sign: c.signers_add(sigkey) if not c.signers_enum(0): self.error='No key for signing [%s]' % self.settings.sender return False c.set_passphrase_cb(lambda x,y,z: sign_passphrase) try: # make a signature c.op_sign(plain,sig,mode.DETACH) sig.seek(0,0) # make it part of the email payload=MIMEMultipart.MIMEMultipart('signed', boundary=None, _subparts=None, **dict(micalg="pgp-sha1", protocol="application/pgp-signature")) # insert the origin payload payload.attach(payload_in) # insert the detached signature p=MIMEBase.MIMEBase("application",'pgp-signature') p.set_payload(sig.read()) payload.attach(p) # it's just a trick to handle the no encryption case payload_in=payload except errors.GPGMEError, ex: self.error="GPG error: %s" % ex.getstring() return False ############################################ # encrypt # ############################################ if encrypt: core.check_version(None) plain = core.Data(payload_in.as_string()) cipher = core.Data() c = core.Context() c.set_armor(1) # collect the public keys for encryption recipients=[] rec=to[:] if cc: rec.extend(cc) if bcc: rec.extend(bcc) for addr in rec: c.op_keylist_start(addr,0) r = c.op_keylist_next() if r == None: self.error='No key for [%s]' % addr return False recipients.append(r) try: # make the encryption c.op_encrypt(recipients, 1, plain, cipher) cipher.seek(0,0) # make it a part of the email payload=MIMEMultipart.MIMEMultipart('encrypted', boundary=None, _subparts=None, **dict(protocol="application/pgp-encrypted")) p=MIMEBase.MIMEBase("application",'pgp-encrypted') p.set_payload("Version: 1\r\n") payload.attach(p) p=MIMEBase.MIMEBase("application",'octet-stream') p.set_payload(cipher.read()) payload.attach(p) except errors.GPGMEError, ex: self.error="GPG error: %s" % ex.getstring() return False ####################################################### # X.509 # ####################################################### elif cipher_type == 'x509': if not sign and not encrypt: self.error="No sign and no encrypt is set but cipher type to x509" return False x509_sign_keyfile=self.settings.x509_sign_keyfile if self.settings.x509_sign_certfile: x509_sign_certfile=self.settings.x509_sign_certfile else: # if there is no sign certfile we'll assume the # cert is in keyfile x509_sign_certfile=self.settings.x509_sign_keyfile # crypt certfiles could be a string or a list x509_crypt_certfiles=self.settings.x509_crypt_certfiles # need m2crypto from M2Crypto import BIO, SMIME, X509 msg_bio = BIO.MemoryBuffer(payload_in.as_string()) s = SMIME.SMIME() # SIGN if sign: #key for signing try: s.load_key(x509_sign_keyfile, x509_sign_certfile, callback=lambda x: sign_passphrase) if encrypt: p7 = s.sign(msg_bio) else: p7 = s.sign(msg_bio,flags=SMIME.PKCS7_DETACHED) msg_bio = BIO.MemoryBuffer(payload_in.as_string()) # Recreate coz sign() has consumed it. except Exception,e: self.error="Something went wrong on signing: <%s>" %str(e) return False # ENCRYPT if encrypt: try: sk = X509.X509_Stack() if not isinstance(x509_crypt_certfiles, (list, tuple)): x509_crypt_certfiles = [x509_crypt_certfiles] # make an encryption cert's stack for x in x509_crypt_certfiles: sk.push(X509.load_cert(x)) s.set_x509_stack(sk) s.set_cipher(SMIME.Cipher('des_ede3_cbc')) tmp_bio = BIO.MemoryBuffer() if sign: s.write(tmp_bio, p7) else: tmp_bio.write(payload_in.as_string()) p7 = s.encrypt(tmp_bio) except Exception,e: self.error="Something went wrong on encrypting: <%s>" %str(e) return False # Final stage in sign and encryption out = BIO.MemoryBuffer() if encrypt: s.write(out, p7) else: if sign: s.write(out, p7, msg_bio, SMIME.PKCS7_DETACHED) else: out.write('\r\n') out.write(payload_in.as_string()) out.close() st=str(out.read()) payload=message_from_string(st) else: # no cryptography process as usual payload=payload_in payload['From'] = encode_header(self.settings.sender.decode(encoding)) origTo = to[:] if to: payload['To'] = encode_header(', '.join(to).decode(encoding)) if reply_to: payload['Reply-To'] = encode_header(reply_to.decode(encoding)) if cc: payload['Cc'] = encode_header(', '.join(cc).decode(encoding)) to.extend(cc) if bcc: to.extend(bcc) payload['Subject'] = encode_header(subject.decode(encoding)) payload['Date'] = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()) result = {} try: if self.settings.server == 'logging': logger.warn('email not sent\n%s\nFrom: %s\nTo: %s\n\n%s\n%s\n' % \ ('-'*40,self.settings.sender, ', '.join(to),text or html,'-'*40)) elif self.settings.server == 'gae': xcc = dict() if cc: xcc['cc'] = cc if bcc: xcc['bcc'] = bcc from google.appengine.api import mail attachments = attachments and [(a.my_filename,a.my_payload) for a in attachments] if attachments: result = mail.send_mail(sender=self.settings.sender, to=origTo, subject=subject, body=text, html=html, attachments=attachments, **xcc) elif html: result = mail.send_mail(sender=self.settings.sender, to=origTo, subject=subject, body=text, html=html, **xcc) else: result = mail.send_mail(sender=self.settings.sender, to=origTo, subject=subject, body=text, **xcc) else: smtp_args = self.settings.server.split(':') if self.settings.ssl: server = smtplib.SMTP_SSL(*smtp_args) else: server = smtplib.SMTP(*smtp_args) if self.settings.tls and not self.settings.ssl: server.ehlo() server.starttls() server.ehlo() if self.settings.login != None: server.login(*self.settings.login.split(':',1)) result = server.sendmail(self.settings.sender, to, payload.as_string()) server.quit() except Exception, e: logger.warn('Mail.send failure:%s' % e) self.result = result self.error = e return False self.result = result self.error = None return True class Recaptcha(DIV): API_SSL_SERVER = 'https://www.google.com/recaptcha/api' API_SERVER = 'http://www.google.com/recaptcha/api' VERIFY_SERVER = 'http://www.google.com/recaptcha/api/verify' def __init__( self, request, public_key='', private_key='', use_ssl=False, error=None, error_message='invalid', label = 'Verify:', options = '' ): self.remote_addr = request.env.remote_addr self.public_key = public_key self.private_key = private_key self.use_ssl = use_ssl self.error = error self.errors = Storage() self.error_message = error_message self.components = [] self.attributes = {} self.label = label self.options = options self.comment = '' def _validate(self): # for local testing: recaptcha_challenge_field = \ self.request_vars.recaptcha_challenge_field recaptcha_response_field = \ self.request_vars.recaptcha_response_field private_key = self.private_key remoteip = self.remote_addr if not (recaptcha_response_field and recaptcha_challenge_field and len(recaptcha_response_field) and len(recaptcha_challenge_field)): self.errors['captcha'] = self.error_message return False params = urllib.urlencode({ 'privatekey': private_key, 'remoteip': remoteip, 'challenge': recaptcha_challenge_field, 'response': recaptcha_response_field, }) request = urllib2.Request( url=self.VERIFY_SERVER, data=params, headers={'Content-type': 'application/x-www-form-urlencoded', 'User-agent': 'reCAPTCHA Python'}) httpresp = urllib2.urlopen(request) return_values = httpresp.read().splitlines() httpresp.close() return_code = return_values[0] if return_code == 'true': del self.request_vars.recaptcha_challenge_field del self.request_vars.recaptcha_response_field self.request_vars.captcha = '' return True self.errors['captcha'] = self.error_message return False def xml(self): public_key = self.public_key use_ssl = self.use_ssl error_param = '' if self.error: error_param = '&error=%s' % self.error if use_ssl: server = self.API_SSL_SERVER else: server = self.API_SERVER captcha = DIV( SCRIPT("var RecaptchaOptions = {%s};" % self.options), SCRIPT(_type="text/javascript", _src="%s/challenge?k=%s%s" % (server,public_key,error_param)), TAG.noscript(IFRAME(_src="%s/noscript?k=%s%s" % (server,public_key,error_param), _height="300",_width="500",_frameborder="0"), BR(), INPUT(_type='hidden', _name='recaptcha_response_field', _value='manual_challenge')), _id='recaptcha') if not self.errors.captcha: return XML(captcha).xml() else: captcha.append(DIV(self.errors['captcha'], _class='error')) return XML(captcha).xml() def addrow(form,a,b,c,style,_id,position=-1): if style == "divs": form[0].insert(position, DIV(DIV(LABEL(a),_class='w2p_fl'), DIV(b, _class='w2p_fw'), DIV(c, _class='w2p_fc'), _id = _id)) elif style == "table2cols": form[0].insert(position, TR(LABEL(a),'')) form[0].insert(position+1, TR(b, _colspan=2, _id = _id)) elif style == "ul": form[0].insert(position, LI(DIV(LABEL(a),_class='w2p_fl'), DIV(b, _class='w2p_fw'), DIV(c, _class='w2p_fc'), _id = _id)) else: form[0].insert(position, TR(LABEL(a),b,c,_id = _id)) class Auth(object): """ Class for authentication, authorization, role based access control. Includes: - registration and profile - login and logout - username and password retrieval - event logging - role creation and assignment - user defined group/role based permission Authentication Example:: from contrib.utils import * mail=Mail() mail.settings.server='smtp.gmail.com:587' mail.settings.sender='you@somewhere.com' mail.settings.login='username:password' auth=Auth(globals(), db) auth.settings.mailer=mail # auth.settings....=... auth.define_tables() def authentication(): return dict(form=auth()) exposes: - http://.../{application}/{controller}/authentication/login - http://.../{application}/{controller}/authentication/logout - http://.../{application}/{controller}/authentication/register - http://.../{application}/{controller}/authentication/verify_email - http://.../{application}/{controller}/authentication/retrieve_username - http://.../{application}/{controller}/authentication/retrieve_password - http://.../{application}/{controller}/authentication/reset_password - http://.../{application}/{controller}/authentication/profile - http://.../{application}/{controller}/authentication/change_password On registration a group with role=new_user.id is created and user is given membership of this group. You can create a group with:: group_id=auth.add_group('Manager', 'can access the manage action') auth.add_permission(group_id, 'access to manage') Here \"access to manage\" is just a user defined string. You can give access to a user:: auth.add_membership(group_id, user_id) If user id is omitted, the logged in user is assumed Then you can decorate any action:: @auth.requires_permission('access to manage') def manage(): return dict() You can restrict a permission to a specific table:: auth.add_permission(group_id, 'edit', db.sometable) @auth.requires_permission('edit', db.sometable) Or to a specific record:: auth.add_permission(group_id, 'edit', db.sometable, 45) @auth.requires_permission('edit', db.sometable, 45) If authorization is not granted calls:: auth.settings.on_failed_authorization Other options:: auth.settings.mailer=None auth.settings.expiration=3600 # seconds ... ### these are messages that can be customized ... """ def url(self, f=None, args=[], vars={}): return URL(c=self.settings.controller,f=f,args=args,vars=vars) def __init__(self, environment=None, db=None, controller='default', cas_provider = None): """ auth=Auth(globals(), db) - environment is there for legacy but unused (awful) - db has to be the database where to create tables for authentication """ ## next two lines for backward compatibility if not db and environment and isinstance(environment,DAL): db = environment self.db = db self.environment = current request = current.request session = current.session auth = session.auth if auth and auth.last_visit and auth.last_visit + \ datetime.timedelta(days=0, seconds=auth.expiration) > request.now: self.user = auth.user # this is a trick to speed up sessions if (request.now - auth.last_visit).seconds > (auth.expiration/10): auth.last_visit = request.now else: self.user = None session.auth = None settings = self.settings = Settings() # ## what happens after login? # ## what happens after registration? settings.hideerror = False settings.cas_domains = [request.env.http_host] settings.cas_provider = cas_provider settings.extra_fields = {} settings.actions_disabled = [] settings.reset_password_requires_verification = False settings.registration_requires_verification = False settings.registration_requires_approval = False settings.alternate_requires_registration = False settings.create_user_groups = True settings.controller = controller settings.login_url = self.url('user', args='login') settings.logged_url = self.url('user', args='profile') settings.download_url = self.url('download') settings.mailer = None settings.login_captcha = None settings.register_captcha = None settings.retrieve_username_captcha = None settings.retrieve_password_captcha = None settings.captcha = None settings.expiration = 3600 # one hour settings.long_expiration = 3600*30*24 # one month settings.remember_me_form = True settings.allow_basic_login = False settings.allow_basic_login_only = False settings.on_failed_authorization = \ self.url('user',args='not_authorized') settings.on_failed_authentication = lambda x: redirect(x) settings.formstyle = 'table3cols' settings.label_separator = ': ' # ## table names to be used settings.password_field = 'password' settings.table_user_name = 'auth_user' settings.table_group_name = 'auth_group' settings.table_membership_name = 'auth_membership' settings.table_permission_name = 'auth_permission' settings.table_event_name = 'auth_event' settings.table_cas_name = 'auth_cas' # ## if none, they will be created settings.table_user = None settings.table_group = None settings.table_membership = None settings.table_permission = None settings.table_event = None settings.table_cas = None # ## settings.showid = False # ## these should be functions or lambdas settings.login_next = self.url('index') settings.login_onvalidation = [] settings.login_onaccept = [] settings.login_methods = [self] settings.login_form = self settings.login_email_validate = True settings.login_userfield = None settings.logout_next = self.url('index') settings.logout_onlogout = None settings.register_next = self.url('index') settings.register_onvalidation = [] settings.register_onaccept = [] settings.register_fields = None settings.verify_email_next = self.url('user', args='login') settings.verify_email_onaccept = [] settings.profile_next = self.url('index') settings.profile_onvalidation = [] settings.profile_onaccept = [] settings.profile_fields = None settings.retrieve_username_next = self.url('index') settings.retrieve_password_next = self.url('index') settings.request_reset_password_next = self.url('user', args='login') settings.reset_password_next = self.url('user', args='login') settings.change_password_next = self.url('index') settings.change_password_onvalidation = [] settings.change_password_onaccept = [] settings.retrieve_password_onvalidation = [] settings.reset_password_onvalidation = [] settings.hmac_key = None settings.lock_keys = True # ## these are messages that can be customized messages = self.messages = Messages(current.T) messages.login_button = 'Login' messages.register_button = 'Register' messages.password_reset_button = 'Request reset password' messages.password_change_button = 'Change password' messages.profile_save_button = 'Save profile' messages.submit_button = 'Submit' messages.verify_password = 'Verify Password' messages.delete_label = 'Check to delete:' messages.function_disabled = 'Function disabled' messages.access_denied = 'Insufficient privileges' messages.registration_verifying = 'Registration needs verification' messages.registration_pending = 'Registration is pending approval' messages.login_disabled = 'Login disabled by administrator' messages.logged_in = 'Logged in' messages.email_sent = 'Email sent' messages.unable_to_send_email = 'Unable to send email' messages.email_verified = 'Email verified' messages.logged_out = 'Logged out' messages.registration_successful = 'Registration successful' messages.invalid_email = 'Invalid email' messages.unable_send_email = 'Unable to send email' messages.invalid_login = 'Invalid login' messages.invalid_user = 'Invalid user' messages.invalid_password = 'Invalid password' messages.is_empty = "Cannot be empty" messages.mismatched_password = "Password fields don't match" messages.verify_email = \ 'Click on the link http://...verify_email/%(key)s to verify your email' messages.verify_email_subject = 'Email verification' messages.username_sent = 'Your username was emailed to you' messages.new_password_sent = 'A new password was emailed to you' messages.password_changed = 'Password changed' messages.retrieve_username = 'Your username is: %(username)s' messages.retrieve_username_subject = 'Username retrieve' messages.retrieve_password = 'Your password is: %(password)s' messages.retrieve_password_subject = 'Password retrieve' messages.reset_password = \ 'Click on the link http://...reset_password/%(key)s to reset your password' messages.reset_password_subject = 'Password reset' messages.invalid_reset_password = 'Invalid reset password' messages.profile_updated = 'Profile updated' messages.new_password = 'New password' messages.old_password = 'Old password' messages.group_description = \ 'Group uniquely assigned to user %(id)s' messages.register_log = 'User %(id)s Registered' messages.login_log = 'User %(id)s Logged-in' messages.login_failed_log = None messages.logout_log = 'User %(id)s Logged-out' messages.profile_log = 'User %(id)s Profile updated' messages.verify_email_log = 'User %(id)s Verification email sent' messages.retrieve_username_log = 'User %(id)s Username retrieved' messages.retrieve_password_log = 'User %(id)s Password retrieved' messages.reset_password_log = 'User %(id)s Password reset' messages.change_password_log = 'User %(id)s Password changed' messages.add_group_log = 'Group %(group_id)s created' messages.del_group_log = 'Group %(group_id)s deleted' messages.add_membership_log = None messages.del_membership_log = None messages.has_membership_log = None messages.add_permission_log = None messages.del_permission_log = None messages.has_permission_log = None messages.impersonate_log = 'User %(id)s is impersonating %(other_id)s' messages.label_first_name = 'First name' messages.label_last_name = 'Last name' messages.label_username = 'Username' messages.label_email = 'E-mail' messages.label_password = 'Password' messages.label_registration_key = 'Registration key' messages.label_reset_password_key = 'Reset Password key' messages.label_registration_id = 'Registration identifier' messages.label_role = 'Role' messages.label_description = 'Description' messages.label_user_id = 'User ID' messages.label_group_id = 'Group ID' messages.label_name = 'Name' messages.label_table_name = 'Table name' messages.label_record_id = 'Record ID' messages.label_time_stamp = 'Timestamp' messages.label_client_ip = 'Client IP' messages.label_origin = 'Origin' messages.label_remember_me = "Remember me (for 30 days)" messages['T'] = current.T messages.verify_password_comment = 'please input your password again' messages.lock_keys = True # for "remember me" option response = current.response if auth and auth.remember: #when user wants to be logged in for longer response.cookies[response.session_id_name]["expires"] = \ auth.expiration def lazy_user (auth = self): return auth.user_id reference_user = 'reference %s' % settings.table_user_name def represent(id,record=None,s=settings): try: user = s.table_user(id) return '%(first_name)s %(last_name)s' % user except: return id self.signature = db.Table(self.db,'auth_signature', Field('is_active','boolean',default=True), Field('created_on','datetime', default=request.now, writable=False,readable=False), Field('created_by', reference_user, default=lazy_user,represent=represent, writable=False,readable=False, ), Field('modified_on','datetime', update=request.now,default=request.now, writable=False,readable=False), Field('modified_by', reference_user,represent=represent, default=lazy_user,update=lazy_user, writable=False,readable=False)) def _get_user_id(self): "accessor for auth.user_id" return self.user and self.user.id or None user_id = property(_get_user_id, doc="user.id or None") def _HTTP(self, *a, **b): """ only used in lambda: self._HTTP(404) """ raise HTTP(*a, **b) def __call__(self): """ usage: def authentication(): return dict(form=auth()) """ request = current.request args = request.args if not args: redirect(self.url(args='login',vars=request.vars)) elif args[0] in self.settings.actions_disabled: raise HTTP(404) if args[0] in ('login','logout','register','verify_email', 'retrieve_username','retrieve_password', 'reset_password','request_reset_password', 'change_password','profile','groups', 'impersonate','not_authorized'): return getattr(self,args[0])() elif args[0]=='cas' and not self.settings.cas_provider: if args(1) == 'login': return self.cas_login(version=2) if args(1) == 'validate': return self.cas_validate(version=2) if args(1) == 'logout': return self.logout() else: raise HTTP(404) def navbar(self,prefix='Welcome',action=None): request = current.request T = current.T if isinstance(prefix,str): prefix = T(prefix) if not action: action=URL(request.application,request.controller,'user') if prefix: prefix = prefix.strip()+' ' if self.user_id: logout=A(T('logout'),_href=action+'/logout') profile=A(T('profile'),_href=action+'/profile') password=A(T('password'),_href=action+'/change_password') bar = SPAN(prefix,self.user.first_name,' [ ', logout, ']',_class='auth_navbar') if not 'profile' in self.settings.actions_disabled: bar.insert(4, ' | ') bar.insert(5, profile) if not 'change_password' in self.settings.actions_disabled: bar.insert(-1, ' | ') bar.insert(-1, password) else: login=A(T('login'),_href=action+'/login') register=A(T('register'),_href=action+'/register') retrieve_username=A(T('forgot username?'), _href=action+'/retrieve_username') lost_password=A(T('lost password?'), _href=action+'/request_reset_password') bar = SPAN('[ ',login,' ]',_class='auth_navbar') if not 'register' in self.settings.actions_disabled: bar.insert(2, ' | ') bar.insert(3, register) if 'username' in self.settings.table_user.fields() and \ not 'retrieve_username' in self.settings.actions_disabled: bar.insert(-1, ' | ') bar.insert(-1, retrieve_username) if not 'request_reset_password' in self.settings.actions_disabled: bar.insert(-1, ' | ') bar.insert(-1, lost_password) return bar def __get_migrate(self, tablename, migrate=True): if type(migrate).__name__ == 'str': return (migrate + tablename + '.table') elif migrate == False: return False else: return True def define_tables(self, username=False, migrate=True, fake_migrate=False): """ to be called unless tables are defined manually usages:: # defines all needed tables and table files # 'myprefix_auth_user.table', ... auth.define_tables(migrate='myprefix_') # defines all needed tables without migration/table files auth.define_tables(migrate=False) """ db = self.db settings = self.settings if not settings.table_user_name in db.tables: passfield = settings.password_field if username or settings.cas_provider: table = db.define_table( settings.table_user_name, Field('first_name', length=128, default='', label=self.messages.label_first_name), Field('last_name', length=128, default='', label=self.messages.label_last_name), Field('username', length=128, default='', label=self.messages.label_username), Field('email', length=512, default='', label=self.messages.label_email), Field(passfield, 'password', length=512, readable=False, label=self.messages.label_password), Field('registration_key', length=512, writable=False, readable=False, default='', label=self.messages.label_registration_key), Field('reset_password_key', length=512, writable=False, readable=False, default='', label=self.messages.label_reset_password_key), Field('registration_id', length=512, writable=False, readable=False, default='', label=self.messages.label_registration_id), *settings.extra_fields.get(settings.table_user_name,[]), **dict( migrate=self.__get_migrate(settings.table_user_name, migrate), fake_migrate=fake_migrate, format='%(username)s')) table.username.requires = (IS_MATCH('[\w\.\-]+'), IS_NOT_IN_DB(db, table.username)) else: table = db.define_table( settings.table_user_name, Field('first_name', length=128, default='', label=self.messages.label_first_name), Field('last_name', length=128, default='', label=self.messages.label_last_name), Field('email', length=512, default='', label=self.messages.label_email), Field(passfield, 'password', length=512, readable=False, label=self.messages.label_password), Field('registration_key', length=512, writable=False, readable=False, default='', label=self.messages.label_registration_key), Field('reset_password_key', length=512, writable=False, readable=False, default='', label=self.messages.label_reset_password_key), *settings.extra_fields.get(settings.table_user_name,[]), **dict( migrate=self.__get_migrate(settings.table_user_name, migrate), fake_migrate=fake_migrate, format='%(first_name)s %(last_name)s (%(id)s)')) table.first_name.requires = \ IS_NOT_EMPTY(error_message=self.messages.is_empty) table.last_name.requires = \ IS_NOT_EMPTY(error_message=self.messages.is_empty) table[passfield].requires = [CRYPT(key=settings.hmac_key)] table.email.requires = \ [IS_EMAIL(error_message=self.messages.invalid_email), IS_NOT_IN_DB(db, table.email)] table.registration_key.default = '' settings.table_user = db[settings.table_user_name] if not settings.table_group_name in db.tables: table = db.define_table( settings.table_group_name, Field('role', length=512, default='', label=self.messages.label_role), Field('description', 'text', label=self.messages.label_description), *settings.extra_fields.get(settings.table_group_name,[]), **dict( migrate=self.__get_migrate( settings.table_group_name, migrate), fake_migrate=fake_migrate, format = '%(role)s (%(id)s)')) table.role.requires = IS_NOT_IN_DB(db, '%s.role' % settings.table_group_name) settings.table_group = db[settings.table_group_name] if not settings.table_membership_name in db.tables: table = db.define_table( settings.table_membership_name, Field('user_id', settings.table_user, label=self.messages.label_user_id), Field('group_id', settings.table_group, label=self.messages.label_group_id), *settings.extra_fields.get(settings.table_membership_name,[]), **dict( migrate=self.__get_migrate( settings.table_membership_name, migrate), fake_migrate=fake_migrate)) table.user_id.requires = IS_IN_DB(db, '%s.id' % settings.table_user_name, '%(first_name)s %(last_name)s (%(id)s)') table.group_id.requires = IS_IN_DB(db, '%s.id' % settings.table_group_name, '%(role)s (%(id)s)') settings.table_membership = db[settings.table_membership_name] if not settings.table_permission_name in db.tables: table = db.define_table( settings.table_permission_name, Field('group_id', settings.table_group, label=self.messages.label_group_id), Field('name', default='default', length=512, label=self.messages.label_name), Field('table_name', length=512, label=self.messages.label_table_name), Field('record_id', 'integer',default=0, label=self.messages.label_record_id), *settings.extra_fields.get(settings.table_permission_name,[]), **dict( migrate=self.__get_migrate( settings.table_permission_name, migrate), fake_migrate=fake_migrate)) table.group_id.requires = IS_IN_DB(db, '%s.id' % settings.table_group_name, '%(role)s (%(id)s)') table.name.requires = IS_NOT_EMPTY(error_message=self.messages.is_empty) table.table_name.requires = IS_EMPTY_OR(IS_IN_SET(self.db.tables)) table.record_id.requires = IS_INT_IN_RANGE(0, 10 ** 9) settings.table_permission = db[settings.table_permission_name] if not settings.table_event_name in db.tables: table = db.define_table( settings.table_event_name, Field('time_stamp', 'datetime', default=current.request.now, label=self.messages.label_time_stamp), Field('client_ip', default=current.request.client, label=self.messages.label_client_ip), Field('user_id', settings.table_user, default=None, label=self.messages.label_user_id), Field('origin', default='auth', length=512, label=self.messages.label_origin), Field('description', 'text', default='', label=self.messages.label_description), *settings.extra_fields.get(settings.table_event_name,[]), **dict( migrate=self.__get_migrate( settings.table_event_name, migrate), fake_migrate=fake_migrate)) table.user_id.requires = IS_IN_DB(db, '%s.id' % settings.table_user_name, '%(first_name)s %(last_name)s (%(id)s)') table.origin.requires = IS_NOT_EMPTY(error_message=self.messages.is_empty) table.description.requires = IS_NOT_EMPTY(error_message=self.messages.is_empty) settings.table_event = db[settings.table_event_name] now = current.request.now if settings.cas_domains: if not settings.table_cas_name in db.tables: table = db.define_table( settings.table_cas_name, Field('user_id', settings.table_user, default=None, label=self.messages.label_user_id), Field('created_on','datetime',default=now), Field('url',requires=IS_URL()), Field('uuid'), *settings.extra_fields.get(settings.table_cas_name,[]), **dict( migrate=self.__get_migrate( settings.table_event_name, migrate), fake_migrate=fake_migrate)) table.user_id.requires = IS_IN_DB(db, '%s.id' % \ settings.table_user_name, '%(first_name)s %(last_name)s (%(id)s)') settings.table_cas = db[settings.table_cas_name] if settings.cas_provider: settings.actions_disabled = \ ['profile','register','change_password','request_reset_password'] from gluon.contrib.login_methods.cas_auth import CasAuth maps = dict((name,lambda v,n=name:v.get(n,None)) for name in \ settings.table_user.fields if name!='id' \ and settings.table_user[name].readable) maps['registration_id'] = \ lambda v,p=settings.cas_provider:'%s/%s' % (p,v['user']) settings.login_form = CasAuth( casversion = 2, urlbase = settings.cas_provider, actions=['login','validate','logout'], maps=maps) def log_event(self, description, origin='auth'): """ usage:: auth.log_event(description='this happened', origin='auth') """ if self.is_logged_in(): user_id = self.user.id else: user_id = None # user unknown self.settings.table_event.insert(description=description, origin=origin, user_id=user_id) def get_or_create_user(self, keys): """ Used for alternate login methods: If the user exists already then password is updated. If the user doesn't yet exist, then they are created. """ table_user = self.settings.table_user if 'registration_id' in table_user.fields() and \ 'registration_id' in keys: username = 'registration_id' elif 'username' in table_user.fields(): username = 'username' elif 'email' in table_user.fields(): username = 'email' else: raise SyntaxError, "user must have username or email" passfield = self.settings.password_field user = self.db(table_user[username] == keys[username]).select().first() keys['registration_key']='' if user: user.update_record(**table_user._filter_fields(keys)) else: if not 'first_name' in keys and 'first_name' in table_user.fields: keys['first_name'] = keys[username] user_id = table_user.insert(**table_user._filter_fields(keys)) user = self.user = table_user[user_id] if self.settings.create_user_groups: group_id = self.add_group("user_%s" % user_id) self.add_membership(group_id, user_id) return user def basic(self): if not self.settings.allow_basic_login: return False basic = current.request.env.http_authorization if not basic or not basic[:6].lower() == 'basic ': return False (username, password) = base64.b64decode(basic[6:]).split(':') return self.login_bare(username, password) def login_bare(self, username, password): """ logins user """ request = current.request session = current.session table_user = self.settings.table_user if self.settings.login_userfield: userfield = self.settings.login_userfield elif 'username' in table_user.fields: userfield = 'username' else: userfield = 'email' passfield = self.settings.password_field user = self.db(table_user[userfield] == username).select().first() password = table_user[passfield].validate(password)[0] if user: if not user.registration_key and user[passfield] == password: user = Storage(table_user._filter_fields(user, id=True)) session.auth = Storage(user=user, last_visit=request.now, expiration=self.settings.expiration, hmac_key = web2py_uuid()) self.user = user return user return False def cas_login( self, next=DEFAULT, onvalidation=DEFAULT, onaccept=DEFAULT, log=DEFAULT, version=2, ): request, session = current.request, current.session db, table = self.db, self.settings.table_cas session._cas_service = request.vars.service or session._cas_service if not request.env.http_host in self.settings.cas_domains or \ not session._cas_service: raise HTTP(403,'not authorized') def allow_access(): row = table(url=session._cas_service,user_id=self.user.id) if row: row.update_record(created_on=request.now) uuid = row.uuid else: uuid = web2py_uuid() table.insert(url=session._cas_service, user_id=self.user.id, uuid=uuid, created_on=request.now) url = session._cas_service del session._cas_service redirect(url+"?ticket="+uuid) if self.is_logged_in(): allow_access() def cas_onaccept(form, onaccept=onaccept): if onaccept!=DEFAULT: onaccept(form) allow_access() return self.login(next,onvalidation,cas_onaccept,log) def cas_validate(self,version=2): request = current.request db, table = self.db, self.settings.table_cas current.response.headers['Content-Type']='text' ticket = table(uuid=request.vars.ticket) url = request.env.path_info.rsplit('/',1)[0] if ticket: # and ticket.created_on>request.now-datetime.timedelta(60): user = self.settings.table_user(ticket.user_id) fullname = user.first_name+' '+user.last_name if version==1: raise HTTP(200,'yes\n%s:%s:%s'%(user.id,user.email,fullname)) # assume version 2 username = user.get('username',user.email) raise HTTP(200,'<?xml version="1.0" encoding="UTF-8"?>\n'+\ TAG['cas:serviceResponse']( TAG['cas:authenticationSuccess']( TAG['cas:user'](username), *[TAG['cas:'+field.name](user[field.name]) \ for field in self.settings.table_user \ if field.readable]), **{'_xmlns:cas':'http://www.yale.edu/tp/cas'}).xml()) if version==1: raise HTTP(200,'no\n') # assume version 2 raise HTTP(200,'<?xml version="1.0" encoding="UTF-8"?>\n'+\ TAG['cas:serviceResponse']( TAG['cas:authenticationFailure']( 'Ticket %s not recognized' % ticket, _code='INVALID TICKET'), **{'_xmlns:cas':'http://www.yale.edu/tp/cas'}).xml()) def login( self, next=DEFAULT, onvalidation=DEFAULT, onaccept=DEFAULT, log=DEFAULT, ): """ returns a login form .. method:: Auth.login([next=DEFAULT [, onvalidation=DEFAULT [, onaccept=DEFAULT [, log=DEFAULT]]]]) """ table_user = self.settings.table_user if self.settings.login_userfield: username = self.settings.login_userfield elif 'username' in table_user.fields: username = 'username' else: username = 'email' if 'username' in table_user.fields or not self.settings.login_email_validate: tmpvalidator = IS_NOT_EMPTY(error_message=self.messages.is_empty) else: tmpvalidator = IS_EMAIL(error_message=self.messages.invalid_email) old_requires = table_user[username].requires table_user[username].requires = tmpvalidator request = current.request response = current.response session = current.session passfield = self.settings.password_field if next == DEFAULT: next = request.get_vars._next \ or request.post_vars._next \ or self.settings.login_next if onvalidation == DEFAULT: onvalidation = self.settings.login_onvalidation if onaccept == DEFAULT: onaccept = self.settings.login_onaccept if log == DEFAULT: log = self.messages.login_log user = None # default # do we use our own login form, or from a central source? if self.settings.login_form == self: form = SQLFORM( table_user, fields=[username, passfield], hidden=dict(_next=next), showid=self.settings.showid, submit_button=self.messages.login_button, delete_label=self.messages.delete_label, formstyle=self.settings.formstyle, separator=self.settings.label_separator ) if self.settings.remember_me_form: ## adds a new input checkbox "remember me for longer" addrow(form,XML("&nbsp;"), DIV(XML("&nbsp;"), INPUT(_type='checkbox', _class='checkbox', _id="auth_user_remember", _name="remember", ), XML("&nbsp;&nbsp;"), LABEL( self.messages.label_remember_me, _for="auth_user_remember", )),"", self.settings.formstyle, 'auth_user_remember__row') captcha = self.settings.login_captcha or \ (self.settings.login_captcha!=False and self.settings.captcha) if captcha: addrow(form, captcha.label, captcha, captcha.comment, self.settings.formstyle,'captcha__row') accepted_form = False if form.accepts(request, session, formname='login', dbio=False, onvalidation=onvalidation, hideerror=self.settings.hideerror): accepted_form = True # check for username in db user = self.db(table_user[username] == form.vars[username]).select().first() if user: # user in db, check if registration pending or disabled temp_user = user if temp_user.registration_key == 'pending': response.flash = self.messages.registration_pending return form elif temp_user.registration_key in ('disabled','blocked'): response.flash = self.messages.login_disabled return form elif temp_user.registration_key!=None and \ temp_user.registration_key.strip(): response.flash = \ self.messages.registration_verifying return form # try alternate logins 1st as these have the # current version of the password user = None for login_method in self.settings.login_methods: if login_method != self and \ login_method(request.vars[username], request.vars[passfield]): if not self in self.settings.login_methods: # do not store password in db form.vars[passfield] = None user = self.get_or_create_user(form.vars) break if not user: # alternates have failed, maybe because service inaccessible if self.settings.login_methods[0] == self: # try logging in locally using cached credentials if temp_user[passfield] == form.vars.get(passfield, ''): # success user = temp_user else: # user not in db if not self.settings.alternate_requires_registration: # we're allowed to auto-register users from external systems for login_method in self.settings.login_methods: if login_method != self and \ login_method(request.vars[username], request.vars[passfield]): if not self in self.settings.login_methods: # do not store password in db form.vars[passfield] = None user = self.get_or_create_user(form.vars) break if not user: if self.settings.login_failed_log: self.log_event(self.settings.login_failed_log % request.post_vars) # invalid login session.flash = self.messages.invalid_login redirect(self.url(args=request.args,vars=request.get_vars)) else: # use a central authentication server cas = self.settings.login_form cas_user = cas.get_user() if cas_user: cas_user[passfield] = None user = self.get_or_create_user(table_user._filter_fields(cas_user)) elif hasattr(cas,'login_form'): return cas.login_form() else: # we need to pass through login again before going on next = self.url('user',args='login',vars=dict(_next=next)) redirect(cas.login_url(next)) # process authenticated users if user: user = Storage(table_user._filter_fields(user, id=True)) if log: self.log_event(log % user) # process authenticated users # user wants to be logged in for longer session.auth = Storage( user = user, last_visit = request.now, expiration = self.settings.long_expiration, remember = request.vars.has_key("remember"), hmac_key = web2py_uuid() ) self.user = user session.flash = self.messages.logged_in # how to continue if self.settings.login_form == self: if accepted_form: callback(onaccept,form) if isinstance(next, (list, tuple)): # fix issue with 2.6 next = next[0] if next and not next[0] == '/' and next[:4] != 'http': next = self.url(next.replace('[id]', str(form.vars.id))) redirect(next) table_user[username].requires = old_requires return form elif user: callback(onaccept,None) redirect(next) def logout(self, next=DEFAULT, onlogout=DEFAULT, log=DEFAULT): """ logout and redirects to login .. method:: Auth.logout ([next=DEFAULT[, onlogout=DEFAULT[, log=DEFAULT]]]) """ if next == DEFAULT: next = self.settings.logout_next if onlogout == DEFAULT: onlogout = self.settings.logout_onlogout if onlogout: onlogout(self.user) if log == DEFAULT: log = self.messages.logout_log if log and self.user: self.log_event(log % self.user) if self.settings.login_form != self: cas = self.settings.login_form cas_user = cas.get_user() if cas_user: next = cas.logout_url(next) current.session.auth = None current.session.flash = self.messages.logged_out if next: redirect(next) def register( self, next=DEFAULT, onvalidation=DEFAULT, onaccept=DEFAULT, log=DEFAULT, ): """ returns a registration form .. method:: Auth.register([next=DEFAULT [, onvalidation=DEFAULT [, onaccept=DEFAULT [, log=DEFAULT]]]]) """ table_user = self.settings.table_user request = current.request response = current.response session = current.session if self.is_logged_in(): redirect(self.settings.logged_url) if next == DEFAULT: next = request.get_vars._next \ or request.post_vars._next \ or self.settings.register_next if onvalidation == DEFAULT: onvalidation = self.settings.register_onvalidation if onaccept == DEFAULT: onaccept = self.settings.register_onaccept if log == DEFAULT: log = self.messages.register_log passfield = self.settings.password_field formstyle = self.settings.formstyle form = SQLFORM(table_user, fields = self.settings.register_fields, hidden=dict(_next=next), showid=self.settings.showid, submit_button=self.messages.register_button, delete_label=self.messages.delete_label, formstyle=formstyle, separator=self.settings.label_separator ) for i, row in enumerate(form[0].components): item = row.element('input',_name=passfield) if item: form.custom.widget.password_two = \ INPUT(_name="password_two", _type="password", requires=IS_EXPR('value==%s' % \ repr(request.vars.get(passfield, None)), error_message=self.messages.mismatched_password)) addrow(form, self.messages.verify_password + ':', form.custom.widget.password_two, self.messages.verify_password_comment, formstyle, '%s_%s__row' % (table_user, 'password_two'), position=i+1) break captcha = self.settings.register_captcha or self.settings.captcha if captcha: addrow(form, captcha.label, captcha, captcha.comment,self.settings.formstyle, 'captcha__row') table_user.registration_key.default = key = web2py_uuid() if form.accepts(request, session, formname='register', onvalidation=onvalidation,hideerror=self.settings.hideerror): description = self.messages.group_description % form.vars if self.settings.create_user_groups: group_id = self.add_group("user_%s" % form.vars.id, description) self.add_membership(group_id, form.vars.id) if self.settings.registration_requires_verification: if not self.settings.mailer or \ not self.settings.mailer.send(to=form.vars.email, subject=self.messages.verify_email_subject, message=self.messages.verify_email % dict(key=key)): self.db.rollback() response.flash = self.messages.unable_send_email return form session.flash = self.messages.email_sent elif self.settings.registration_requires_approval: table_user[form.vars.id] = dict(registration_key='pending') session.flash = self.messages.registration_pending else: table_user[form.vars.id] = dict(registration_key='') session.flash = self.messages.registration_successful table_user = self.settings.table_user if 'username' in table_user.fields: username = 'username' else: username = 'email' user = self.db(table_user[username] == form.vars[username]).select().first() user = Storage(table_user._filter_fields(user, id=True)) session.auth = Storage(user=user, last_visit=request.now, expiration=self.settings.expiration, hmac_key = web2py_uuid()) self.user = user session.flash = self.messages.logged_in if log: self.log_event(log % form.vars) callback(onaccept,form) if not next: next = self.url(args = request.args) elif isinstance(next, (list, tuple)): ### fix issue with 2.6 next = next[0] elif next and not next[0] == '/' and next[:4] != 'http': next = self.url(next.replace('[id]', str(form.vars.id))) redirect(next) return form def is_logged_in(self): """ checks if the user is logged in and returns True/False. if so user is in auth.user as well as in session.auth.user """ if self.user: return True return False def verify_email( self, next=DEFAULT, onaccept=DEFAULT, log=DEFAULT, ): """ action user to verify the registration email, XXXXXXXXXXXXXXXX .. method:: Auth.verify_email([next=DEFAULT [, onvalidation=DEFAULT [, onaccept=DEFAULT [, log=DEFAULT]]]]) """ key = current.request.args[-1] table_user = self.settings.table_user user = self.db(table_user.registration_key == key).select().first() if not user: redirect(self.settings.login_url) if self.settings.registration_requires_approval: user.update_record(registration_key = 'pending') current.session.flash = self.messages.registration_pending else: user.update_record(registration_key = '') current.session.flash = self.messages.email_verified if log == DEFAULT: log = self.messages.verify_email_log if next == DEFAULT: next = self.settings.verify_email_next if onaccept == DEFAULT: onaccept = self.settings.verify_email_onaccept if log: self.log_event(log % user) callback(onaccept,user) redirect(next) def retrieve_username( self, next=DEFAULT, onvalidation=DEFAULT, onaccept=DEFAULT, log=DEFAULT, ): """ returns a form to retrieve the user username (only if there is a username field) .. method:: Auth.retrieve_username([next=DEFAULT [, onvalidation=DEFAULT [, onaccept=DEFAULT [, log=DEFAULT]]]]) """ table_user = self.settings.table_user if not 'username' in table_user.fields: raise HTTP(404) request = current.request response = current.response session = current.session captcha = self.settings.retrieve_username_captcha or \ (self.settings.retrieve_username_captcha!=False and self.settings.captcha) if not self.settings.mailer: response.flash = self.messages.function_disabled return '' if next == DEFAULT: next = request.get_vars._next \ or request.post_vars._next \ or self.settings.retrieve_username_next if onvalidation == DEFAULT: onvalidation = self.settings.retrieve_username_onvalidation if onaccept == DEFAULT: onaccept = self.settings.retrieve_username_onaccept if log == DEFAULT: log = self.messages.retrieve_username_log old_requires = table_user.email.requires table_user.email.requires = [IS_IN_DB(self.db, table_user.email, error_message=self.messages.invalid_email)] form = SQLFORM(table_user, fields=['email'], hidden=dict(_next=next), showid=self.settings.showid, submit_button=self.messages.submit_button, delete_label=self.messages.delete_label, formstyle=self.settings.formstyle, separator=self.settings.label_separator ) if captcha: addrow(form, captcha.label, captcha, captcha.comment,self.settings.formstyle, 'captcha__row') if form.accepts(request, session, formname='retrieve_username', dbio=False, onvalidation=onvalidation,hideerror=self.settings.hideerror): user = self.db(table_user.email == form.vars.email).select().first() if not user: current.session.flash = \ self.messages.invalid_email redirect(self.url(args=request.args)) username = user.username self.settings.mailer.send(to=form.vars.email, subject=self.messages.retrieve_username_subject, message=self.messages.retrieve_username % dict(username=username)) session.flash = self.messages.email_sent if log: self.log_event(log % user) callback(onaccept,form) if not next: next = self.url(args = request.args) elif isinstance(next, (list, tuple)): ### fix issue with 2.6 next = next[0] elif next and not next[0] == '/' and next[:4] != 'http': next = self.url(next.replace('[id]', str(form.vars.id))) redirect(next) table_user.email.requires = old_requires return form def random_password(self): import string import random password = '' specials=r'!#$*' for i in range(0,3): password += random.choice(string.lowercase) password += random.choice(string.uppercase) password += random.choice(string.digits) password += random.choice(specials) return ''.join(random.sample(password,len(password))) def reset_password_deprecated( self, next=DEFAULT, onvalidation=DEFAULT, onaccept=DEFAULT, log=DEFAULT, ): """ returns a form to reset the user password (deprecated) .. method:: Auth.reset_password_deprecated([next=DEFAULT [, onvalidation=DEFAULT [, onaccept=DEFAULT [, log=DEFAULT]]]]) """ table_user = self.settings.table_user request = current.request response = current.response session = current.session if not self.settings.mailer: response.flash = self.messages.function_disabled return '' if next == DEFAULT: next = request.get_vars._next \ or request.post_vars._next \ or self.settings.retrieve_password_next if onvalidation == DEFAULT: onvalidation = self.settings.retrieve_password_onvalidation if onaccept == DEFAULT: onaccept = self.settings.retrieve_password_onaccept if log == DEFAULT: log = self.messages.retrieve_password_log old_requires = table_user.email.requires table_user.email.requires = [IS_IN_DB(self.db, table_user.email, error_message=self.messages.invalid_email)] form = SQLFORM(table_user, fields=['email'], hidden=dict(_next=next), showid=self.settings.showid, submit_button=self.messages.submit_button, delete_label=self.messages.delete_label, formstyle=self.settings.formstyle, separator=self.settings.label_separator ) if form.accepts(request, session, formname='retrieve_password', dbio=False, onvalidation=onvalidation,hideerror=self.settings.hideerror): user = self.db(table_user.email == form.vars.email).select().first() if not user: current.session.flash = \ self.messages.invalid_email redirect(self.url(args=request.args)) elif user.registration_key in ('pending','disabled','blocked'): current.session.flash = \ self.messages.registration_pending redirect(self.url(args=request.args)) password = self.random_password() passfield = self.settings.password_field d = {passfield: table_user[passfield].validate(password)[0], 'registration_key': ''} user.update_record(**d) if self.settings.mailer and \ self.settings.mailer.send(to=form.vars.email, subject=self.messages.retrieve_password_subject, message=self.messages.retrieve_password \ % dict(password=password)): session.flash = self.messages.email_sent else: session.flash = self.messages.unable_to_send_email if log: self.log_event(log % user) callback(onaccept,form) if not next: next = self.url(args = request.args) elif isinstance(next, (list, tuple)): ### fix issue with 2.6 next = next[0] elif next and not next[0] == '/' and next[:4] != 'http': next = self.url(next.replace('[id]', str(form.vars.id))) redirect(next) table_user.email.requires = old_requires return form def reset_password( self, next=DEFAULT, onvalidation=DEFAULT, onaccept=DEFAULT, log=DEFAULT, ): """ returns a form to reset the user password .. method:: Auth.reset_password([next=DEFAULT [, onvalidation=DEFAULT [, onaccept=DEFAULT [, log=DEFAULT]]]]) """ table_user = self.settings.table_user request = current.request # response = current.response session = current.session if next == DEFAULT: next = request.get_vars._next \ or request.post_vars._next \ or self.settings.reset_password_next try: key = request.vars.key or request.args[-1] t0 = int(key.split('-')[0]) if time.time()-t0 > 60*60*24: raise Exception user = self.db(table_user.reset_password_key == key).select().first() if not user: raise Exception except Exception: session.flash = self.messages.invalid_reset_password redirect(next) passfield = self.settings.password_field form = SQLFORM.factory( Field('new_password', 'password', label=self.messages.new_password, requires=self.settings.table_user[passfield].requires), Field('new_password2', 'password', label=self.messages.verify_password, requires=[IS_EXPR('value==%s' % repr(request.vars.new_password), self.messages.mismatched_password)]), submit_button=self.messages.password_reset_button, formstyle=self.settings.formstyle, separator=self.settings.label_separator ) if form.accepts(request,session,hideerror=self.settings.hideerror): user.update_record(**{passfield:form.vars.new_password, 'registration_key':'', 'reset_password_key':''}) session.flash = self.messages.password_changed redirect(next) return form def request_reset_password( self, next=DEFAULT, onvalidation=DEFAULT, onaccept=DEFAULT, log=DEFAULT, ): """ returns a form to reset the user password .. method:: Auth.reset_password([next=DEFAULT [, onvalidation=DEFAULT [, onaccept=DEFAULT [, log=DEFAULT]]]]) """ table_user = self.settings.table_user request = current.request response = current.response session = current.session captcha = self.settings.retrieve_password_captcha or \ (self.settings.retrieve_password_captcha!=False and self.settings.captcha) if next == DEFAULT: next = request.get_vars._next \ or request.post_vars._next \ or self.settings.request_reset_password_next if not self.settings.mailer: response.flash = self.messages.function_disabled return '' if onvalidation == DEFAULT: onvalidation = self.settings.reset_password_onvalidation if onaccept == DEFAULT: onaccept = self.settings.reset_password_onaccept if log == DEFAULT: log = self.messages.reset_password_log # old_requires = table_user.email.requires <<< perhaps should be restored table_user.email.requires = [ IS_EMAIL(error_message=self.messages.invalid_email), IS_IN_DB(self.db, table_user.email, error_message=self.messages.invalid_email)] form = SQLFORM(table_user, fields=['email'], hidden=dict(_next=next), showid=self.settings.showid, submit_button=self.messages.password_reset_button, delete_label=self.messages.delete_label, formstyle=self.settings.formstyle, separator=self.settings.label_separator ) if captcha: addrow(form, captcha.label, captcha, captcha.comment, self.settings.formstyle,'captcha__row') if form.accepts(request, session, formname='reset_password', dbio=False, onvalidation=onvalidation, hideerror=self.settings.hideerror): user = self.db(table_user.email == form.vars.email).select().first() if not user: session.flash = self.messages.invalid_email redirect(self.url(args=request.args)) elif user.registration_key in ('pending','disabled','blocked'): session.flash = self.messages.registration_pending redirect(self.url(args=request.args)) reset_password_key = str(int(time.time()))+'-' + web2py_uuid() if self.settings.mailer.send(to=form.vars.email, subject=self.messages.reset_password_subject, message=self.messages.reset_password % \ dict(key=reset_password_key)): session.flash = self.messages.email_sent user.update_record(reset_password_key=reset_password_key) else: session.flash = self.messages.unable_to_send_email if log: self.log_event(log % user) callback(onaccept,form) if not next: next = self.url(args = request.args) elif isinstance(next, (list, tuple)): ### fix issue with 2.6 next = next[0] elif next and not next[0] == '/' and next[:4] != 'http': next = self.url(next.replace('[id]', str(form.vars.id))) redirect(next) # old_requires = table_user.email.requires return form def retrieve_password( self, next=DEFAULT, onvalidation=DEFAULT, onaccept=DEFAULT, log=DEFAULT, ): if self.settings.reset_password_requires_verification: return self.request_reset_password(next,onvalidation,onaccept,log) else: return self.reset_password_deprecated(next,onvalidation,onaccept,log) def change_password( self, next=DEFAULT, onvalidation=DEFAULT, onaccept=DEFAULT, log=DEFAULT, ): """ returns a form that lets the user change password .. method:: Auth.change_password([next=DEFAULT[, onvalidation=DEFAULT[, onaccept=DEFAULT[, log=DEFAULT]]]]) """ if not self.is_logged_in(): redirect(self.settings.login_url) db = self.db table_user = self.settings.table_user usern = self.settings.table_user_name s = db(table_user.id == self.user.id) request = current.request session = current.session if next == DEFAULT: next = request.get_vars._next \ or request.post_vars._next \ or self.settings.change_password_next if onvalidation == DEFAULT: onvalidation = self.settings.change_password_onvalidation if onaccept == DEFAULT: onaccept = self.settings.change_password_onaccept if log == DEFAULT: log = self.messages.change_password_log passfield = self.settings.password_field form = SQLFORM.factory( Field('old_password', 'password', label=self.messages.old_password, requires=validators( table_user[passfield].requires, IS_IN_DB(s, '%s.%s' % (usern, passfield), error_message=self.messages.invalid_password))), Field('new_password', 'password', label=self.messages.new_password, requires=table_user[passfield].requires), Field('new_password2', 'password', label=self.messages.verify_password, requires=[IS_EXPR('value==%s' % repr(request.vars.new_password), self.messages.mismatched_password)]), submit_button=self.messages.password_change_button, formstyle = self.settings.formstyle, separator=self.settings.label_separator ) if form.accepts(request, session, formname='change_password', onvalidation=onvalidation, hideerror=self.settings.hideerror): d = {passfield: form.vars.new_password} s.update(**d) session.flash = self.messages.password_changed if log: self.log_event(log % self.user) callback(onaccept,form) if not next: next = self.url(args=request.args) elif isinstance(next, (list, tuple)): ### fix issue with 2.6 next = next[0] elif next and not next[0] == '/' and next[:4] != 'http': next = self.url(next.replace('[id]', str(form.vars.id))) redirect(next) return form def profile( self, next=DEFAULT, onvalidation=DEFAULT, onaccept=DEFAULT, log=DEFAULT, ): """ returns a form that lets the user change his/her profile .. method:: Auth.profile([next=DEFAULT [, onvalidation=DEFAULT [, onaccept=DEFAULT [, log=DEFAULT]]]]) """ table_user = self.settings.table_user if not self.is_logged_in(): redirect(self.settings.login_url) passfield = self.settings.password_field self.settings.table_user[passfield].writable = False request = current.request session = current.session if next == DEFAULT: next = request.get_vars._next \ or request.post_vars._next \ or self.settings.profile_next if onvalidation == DEFAULT: onvalidation = self.settings.profile_onvalidation if onaccept == DEFAULT: onaccept = self.settings.profile_onaccept if log == DEFAULT: log = self.messages.profile_log form = SQLFORM( table_user, self.user.id, fields = self.settings.profile_fields, hidden = dict(_next=next), showid = self.settings.showid, submit_button = self.messages.profile_save_button, delete_label = self.messages.delete_label, upload = self.settings.download_url, formstyle = self.settings.formstyle, separator=self.settings.label_separator ) if form.accepts(request, session, formname='profile', onvalidation=onvalidation,hideerror=self.settings.hideerror): self.user.update(table_user._filter_fields(form.vars)) session.flash = self.messages.profile_updated if log: self.log_event(log % self.user) callback(onaccept,form) if not next: next = self.url(args=request.args) elif isinstance(next, (list, tuple)): ### fix issue with 2.6 next = next[0] elif next and not next[0] == '/' and next[:4] != 'http': next = self.url(next.replace('[id]', str(form.vars.id))) redirect(next) return form def is_impersonating(self): return current.session.auth.impersonator def impersonate(self, user_id=DEFAULT): """ usage: POST TO http://..../impersonate request.post_vars.user_id=<id> set request.post_vars.user_id to 0 to restore original user. requires impersonator is logged in and has_permission('impersonate', 'auth_user', user_id) """ request = current.request session = current.session auth = session.auth if not self.is_logged_in(): raise HTTP(401, "Not Authorized") current_id = auth.user.id requested_id = user_id if user_id == DEFAULT: user_id = current.request.post_vars.user_id if user_id and user_id != self.user.id and user_id != '0': if not self.has_permission('impersonate', self.settings.table_user_name, user_id): raise HTTP(403, "Forbidden") user = self.settings.table_user(user_id) if not user: raise HTTP(401, "Not Authorized") auth.impersonator = cPickle.dumps(session) auth.user.update( self.settings.table_user._filter_fields(user, True)) self.user = auth.user if self.settings.login_onaccept: form = Storage(dict(vars=self.user)) self.settings.login_onaccept(form) log = self.messages.impersonate_log if log: self.log_event(log % dict(id=current_id,other_id=auth.user.id)) elif user_id in (0, '0') and self.is_impersonating(): session.clear() session.update(cPickle.loads(auth.impersonator)) self.user = session.auth.user if requested_id == DEFAULT and not request.post_vars: return SQLFORM.factory(Field('user_id','integer')) return self.user def groups(self): """ displays the groups and their roles for the logged in user """ if not self.is_logged_in(): redirect(self.settings.login_url) memberships = self.db(self.settings.table_membership.user_id == self.user.id).select() table = TABLE() for membership in memberships: groups = self.db(self.settings.table_group.id == membership.group_id).select() if groups: group = groups[0] table.append(TR(H3(group.role, '(%s)' % group.id))) table.append(TR(P(group.description))) if not memberships: return None return table def not_authorized(self): """ you can change the view for this page to make it look as you like """ return 'ACCESS DENIED' def requires(self, condition): """ decorator that prevents access to action if not logged in """ def decorator(action): def f(*a, **b): if self.settings.allow_basic_login_only and not self.basic(): if current.request.is_restful: raise HTTP(403,"Not authorized") return call_or_redirect(self.settings.on_failed_authorization) if not condition: if current.request.is_restful: raise HTTP(403,"Not authorized") if not self.basic() and not self.is_logged_in(): request = current.request next = URL(r=request,args=request.args, vars=request.get_vars) current.session.flash = current.response.flash return call_or_redirect( self.settings.on_failed_authentication, self.settings.login_url + '?_next='+urllib.quote(next)) else: current.session.flash = self.messages.access_denied return call_or_redirect(self.settings.on_failed_authorization) return action(*a, **b) f.__doc__ = action.__doc__ f.__name__ = action.__name__ f.__dict__.update(action.__dict__) return f return decorator def requires_login(self): """ decorator that prevents access to action if not logged in """ def decorator(action): def f(*a, **b): if self.settings.allow_basic_login_only and not self.basic(): if current.request.is_restful: raise HTTP(403,"Not authorized") return call_or_redirect(self.settings.on_failed_authorization) if not self.basic() and not self.is_logged_in(): if current.request.is_restful: raise HTTP(403,"Not authorized") request = current.request next = URL(r=request,args=request.args, vars=request.get_vars) current.session.flash = current.response.flash return call_or_redirect( self.settings.on_failed_authentication, self.settings.login_url + '?_next='+urllib.quote(next) ) return action(*a, **b) f.__doc__ = action.__doc__ f.__name__ = action.__name__ f.__dict__.update(action.__dict__) return f return decorator def requires_membership(self, role=None, group_id=None): """ decorator that prevents access to action if not logged in or if user logged in is not a member of group_id. If role is provided instead of group_id then the group_id is calculated. """ def decorator(action): def f(*a, **b): if self.settings.allow_basic_login_only and not self.basic(): if current.request.is_restful: raise HTTP(403,"Not authorized") return call_or_redirect(self.settings.on_failed_authorization) if not self.basic() and not self.is_logged_in(): if current.request.is_restful: raise HTTP(403,"Not authorized") request = current.request next = URL(r=request,args=request.args, vars=request.get_vars) current.session.flash = current.response.flash return call_or_redirect( self.settings.on_failed_authentication, self.settings.login_url + '?_next='+urllib.quote(next) ) if not self.has_membership(group_id=group_id, role=role): current.session.flash = self.messages.access_denied return call_or_redirect(self.settings.on_failed_authorization) return action(*a, **b) f.__doc__ = action.__doc__ f.__name__ = action.__name__ f.__dict__.update(action.__dict__) return f return decorator def requires_permission( self, name, table_name='', record_id=0, ): """ decorator that prevents access to action if not logged in or if user logged in is not a member of any group (role) that has 'name' access to 'table_name', 'record_id'. """ def decorator(action): def f(*a, **b): if self.settings.allow_basic_login_only and not self.basic(): if current.request.is_restful: raise HTTP(403,"Not authorized") return call_or_redirect(self.settings.on_failed_authorization) if not self.basic() and not self.is_logged_in(): if current.request.is_restful: raise HTTP(403,"Not authorized") request = current.request next = URL(r=request,args=request.args, vars=request.get_vars) current.session.flash = current.response.flash return call_or_redirect( self.settings.on_failed_authentication, self.settings.login_url + '?_next='+urllib.quote(next) ) if not self.has_permission(name, table_name, record_id): current.session.flash = self.messages.access_denied return call_or_redirect(self.settings.on_failed_authorization) return action(*a, **b) f.__doc__ = action.__doc__ f.__name__ = action.__name__ f.__dict__.update(action.__dict__) return f return decorator def requires_signature(self): """ decorator that prevents access to action if not logged in or if user logged in is not a member of group_id. If role is provided instead of group_id then the group_id is calculated. """ def decorator(action): def f(*a, **b): if self.settings.allow_basic_login_only and not self.basic(): if current.request.is_restful: raise HTTP(403,"Not authorized") return call_or_redirect(self.settings.on_failed_authorization) if not self.basic() and not self.is_logged_in(): if current.request.is_restful: raise HTTP(403,"Not authorized") request = current.request next = URL(r=request,args=request.args, vars=request.get_vars) current.session.flash = current.response.flash return call_or_redirect( self.settings.on_failed_authentication, self.settings.login_url + '?_next='+urllib.quote(next) ) if not URL.verify(current.request,user_signature=True): current.session.flash = self.messages.access_denied return call_or_redirect(self.settings.on_failed_authorization) return action(*a, **b) f.__doc__ = action.__doc__ f.__name__ = action.__name__ f.__dict__.update(action.__dict__) return f return decorator def add_group(self, role, description=''): """ creates a group associated to a role """ group_id = self.settings.table_group.insert(role=role, description=description) log = self.messages.add_group_log if log: self.log_event(log % dict(group_id=group_id, role=role)) return group_id def del_group(self, group_id): """ deletes a group """ self.db(self.settings.table_group.id == group_id).delete() self.db(self.settings.table_membership.group_id == group_id).delete() self.db(self.settings.table_permission.group_id == group_id).delete() log = self.messages.del_group_log if log: self.log_event(log % dict(group_id=group_id)) def id_group(self, role): """ returns the group_id of the group specified by the role """ rows = self.db(self.settings.table_group.role == role).select() if not rows: return None return rows[0].id def user_group(self, user_id = None): """ returns the group_id of the group uniquely associated to this user i.e. role=user:[user_id] """ if not user_id and self.user: user_id = self.user.id role = 'user_%s' % user_id return self.id_group(role) def has_membership(self, group_id=None, user_id=None, role=None): """ checks if user is member of group_id or role """ group_id = group_id or self.id_group(role) try: group_id = int(group_id) except: group_id = self.id_group(group_id) # interpret group_id as a role if not user_id and self.user: user_id = self.user.id membership = self.settings.table_membership if self.db((membership.user_id == user_id) & (membership.group_id == group_id)).select(): r = True else: r = False log = self.messages.has_membership_log if log: self.log_event(log % dict(user_id=user_id, group_id=group_id, check=r)) return r def add_membership(self, group_id=None, user_id=None, role=None): """ gives user_id membership of group_id or role if user_id==None than user_id is that of current logged in user """ group_id = group_id or self.id_group(role) try: group_id = int(group_id) except: group_id = self.id_group(group_id) # interpret group_id as a role if not user_id and self.user: user_id = self.user.id membership = self.settings.table_membership record = membership(user_id = user_id,group_id = group_id) if record: return record.id else: id = membership.insert(group_id=group_id, user_id=user_id) log = self.messages.add_membership_log if log: self.log_event(log % dict(user_id=user_id, group_id=group_id)) return id def del_membership(self, group_id, user_id=None, role=None): """ revokes membership from group_id to user_id if user_id==None than user_id is that of current logged in user """ group_id = group_id or self.id_group(role) if not user_id and self.user: user_id = self.user.id membership = self.settings.table_membership log = self.messages.del_membership_log if log: self.log_event(log % dict(user_id=user_id, group_id=group_id)) return self.db(membership.user_id == user_id)(membership.group_id == group_id).delete() def has_permission( self, name='any', table_name='', record_id=0, user_id=None, group_id=None, ): """ checks if user_id or current logged in user is member of a group that has 'name' permission on 'table_name' and 'record_id' if group_id is passed, it checks whether the group has the permission """ if not user_id and not group_id and self.user: user_id = self.user.id if user_id: membership = self.settings.table_membership rows = self.db(membership.user_id == user_id).select(membership.group_id) groups = set([row.group_id for row in rows]) if group_id and not group_id in groups: return False else: groups = set([group_id]) permission = self.settings.table_permission rows = self.db(permission.name == name)(permission.table_name == str(table_name))(permission.record_id == record_id).select(permission.group_id) groups_required = set([row.group_id for row in rows]) if record_id: rows = self.db(permission.name == name)(permission.table_name == str(table_name))(permission.record_id == 0).select(permission.group_id) groups_required = groups_required.union(set([row.group_id for row in rows])) if groups.intersection(groups_required): r = True else: r = False log = self.messages.has_permission_log if log and user_id: self.log_event(log % dict(user_id=user_id, name=name, table_name=table_name, record_id=record_id)) return r def add_permission( self, group_id, name='any', table_name='', record_id=0, ): """ gives group_id 'name' access to 'table_name' and 'record_id' """ permission = self.settings.table_permission if group_id == 0: group_id = self.user_group() id = permission.insert(group_id=group_id, name=name, table_name=str(table_name), record_id=long(record_id)) log = self.messages.add_permission_log if log: self.log_event(log % dict(permission_id=id, group_id=group_id, name=name, table_name=table_name, record_id=record_id)) return id def del_permission( self, group_id, name='any', table_name='', record_id=0, ): """ revokes group_id 'name' access to 'table_name' and 'record_id' """ permission = self.settings.table_permission log = self.messages.del_permission_log if log: self.log_event(log % dict(group_id=group_id, name=name, table_name=table_name, record_id=record_id)) return self.db(permission.group_id == group_id)(permission.name == name)(permission.table_name == str(table_name))(permission.record_id == long(record_id)).delete() def accessible_query(self, name, table, user_id=None): """ returns a query with all accessible records for user_id or the current logged in user this method does not work on GAE because uses JOIN and IN example:: db(auth.accessible_query('read', db.mytable)).select(db.mytable.ALL) """ if not user_id: user_id = self.user.id if self.has_permission(name, table, 0, user_id): return table.id > 0 db = self.db membership = self.settings.table_membership permission = self.settings.table_permission return table.id.belongs(db(membership.user_id == user_id)\ (membership.group_id == permission.group_id)\ (permission.name == name)\ (permission.table_name == table)\ ._select(permission.record_id)) class Crud(object): def url(self, f=None, args=[], vars={}): """ this should point to the controller that exposes download and crud """ return URL(c=self.settings.controller,f=f,args=args,vars=vars) def __init__(self, environment, db=None, controller='default'): self.db = db if not db and environment and isinstance(environment,DAL): self.db = environment elif not db: raise SyntaxError, "must pass db as first or second argument" self.environment = current settings = self.settings = Settings() settings.auth = None settings.logger = None settings.create_next = None settings.update_next = None settings.controller = controller settings.delete_next = self.url() settings.download_url = self.url('download') settings.create_onvalidation = StorageList() settings.update_onvalidation = StorageList() settings.delete_onvalidation = StorageList() settings.create_onaccept = StorageList() settings.update_onaccept = StorageList() settings.update_ondelete = StorageList() settings.delete_onaccept = StorageList() settings.update_deletable = True settings.showid = False settings.keepvalues = False settings.create_captcha = None settings.update_captcha = None settings.captcha = None settings.formstyle = 'table3cols' settings.label_separator = ': ' settings.hideerror = False settings.detect_record_change = True settings.hmac_key = None settings.lock_keys = True messages = self.messages = Messages(current.T) messages.submit_button = 'Submit' messages.delete_label = 'Check to delete:' messages.record_created = 'Record Created' messages.record_updated = 'Record Updated' messages.record_deleted = 'Record Deleted' messages.update_log = 'Record %(id)s updated' messages.create_log = 'Record %(id)s created' messages.read_log = 'Record %(id)s read' messages.delete_log = 'Record %(id)s deleted' messages.lock_keys = True def __call__(self): args = current.request.args if len(args) < 1: raise HTTP(404) elif args[0] == 'tables': return self.tables() elif len(args) > 1 and not args(1) in self.db.tables: raise HTTP(404) table = self.db[args(1)] if args[0] == 'create': return self.create(table) elif args[0] == 'select': return self.select(table,linkto=self.url(args='read')) elif args[0] == 'search': form, rows = self.search(table,linkto=self.url(args='read')) return DIV(form,SQLTABLE(rows)) elif args[0] == 'read': return self.read(table, args(2)) elif args[0] == 'update': return self.update(table, args(2)) elif args[0] == 'delete': return self.delete(table, args(2)) else: raise HTTP(404) def log_event(self, message): if self.settings.logger: self.settings.logger.log_event(message, 'crud') def has_permission(self, name, table, record=0): if not self.settings.auth: return True try: record_id = record.id except: record_id = record return self.settings.auth.has_permission(name, str(table), record_id) def tables(self): return TABLE(*[TR(A(name, _href=self.url(args=('select',name)))) \ for name in self.db.tables]) @staticmethod def archive(form,archive_table=None,current_record='current_record'): """ If you have a table (db.mytable) that needs full revision history you can just do:: form=crud.update(db.mytable,myrecord,onaccept=crud.archive) crud.archive will define a new table "mytable_archive" and store the previous record in the newly created table including a reference to the current record. If you want to access such table you need to define it yourself in a model:: db.define_table('mytable_archive', Field('current_record',db.mytable), db.mytable) Notice such table includes all fields of db.mytable plus one: current_record. crud.archive does not timestamp the stored record unless your original table has a fields like:: db.define_table(..., Field('saved_on','datetime', default=request.now,update=request.now,writable=False), Field('saved_by',auth.user, default=auth.user_id,update=auth.user_id,writable=False), there is nothing special about these fields since they are filled before the record is archived. If you want to change the archive table name and the name of the reference field you can do, for example:: db.define_table('myhistory', Field('parent_record',db.mytable), db.mytable) and use it as:: form=crud.update(db.mytable,myrecord, onaccept=lambda form:crud.archive(form, archive_table=db.myhistory, current_record='parent_record')) """ old_record = form.record if not old_record: return None table = form.table if not archive_table: archive_table_name = '%s_archive' % table if archive_table_name in table._db: archive_table = table._db[archive_table_name] else: archive_table = table._db.define_table(archive_table_name, Field(current_record,table), table) new_record = {current_record:old_record.id} for fieldname in archive_table.fields: if not fieldname in ['id',current_record] and fieldname in old_record: new_record[fieldname]=old_record[fieldname] id = archive_table.insert(**new_record) return id def update( self, table, record, next=DEFAULT, onvalidation=DEFAULT, onaccept=DEFAULT, ondelete=DEFAULT, log=DEFAULT, message=DEFAULT, deletable=DEFAULT, formname=DEFAULT, ): """ .. method:: Crud.update(table, record, [next=DEFAULT [, onvalidation=DEFAULT [, onaccept=DEFAULT [, log=DEFAULT [, message=DEFAULT[, deletable=DEFAULT]]]]]]) """ if not (isinstance(table, self.db.Table) or table in self.db.tables) \ or (isinstance(record, str) and not str(record).isdigit()): raise HTTP(404) if not isinstance(table, self.db.Table): table = self.db[table] try: record_id = record.id except: record_id = record or 0 if record_id and not self.has_permission('update', table, record_id): redirect(self.settings.auth.settings.on_failed_authorization) if not record_id \ and not self.has_permission('create', table, record_id): redirect(self.settings.auth.settings.on_failed_authorization) request = current.request response = current.response session = current.session if request.extension == 'json' and request.vars.json: request.vars.update(simplejson.loads(request.vars.json)) if next == DEFAULT: next = request.get_vars._next \ or request.post_vars._next \ or self.settings.update_next if onvalidation == DEFAULT: onvalidation = self.settings.update_onvalidation if onaccept == DEFAULT: onaccept = self.settings.update_onaccept if ondelete == DEFAULT: ondelete = self.settings.update_ondelete if log == DEFAULT: log = self.messages.update_log if deletable == DEFAULT: deletable = self.settings.update_deletable if message == DEFAULT: message = self.messages.record_updated form = SQLFORM( table, record, hidden=dict(_next=next), showid=self.settings.showid, submit_button=self.messages.submit_button, delete_label=self.messages.delete_label, deletable=deletable, upload=self.settings.download_url, formstyle=self.settings.formstyle, separator=self.settings.label_separator ) self.accepted = False self.deleted = False captcha = self.settings.update_captcha or \ self.settings.captcha if record and captcha: addrow(form, captcha.label, captcha, captcha.comment, self.settings.formstyle,'captcha__row') captcha = self.settings.create_captcha or \ self.settings.captcha if not record and captcha: addrow(form, captcha.label, captcha, captcha.comment, self.settings.formstyle,'captcha__row') if not request.extension in ('html','load'): (_session, _formname) = (None, None) else: (_session, _formname) = \ (session, '%s/%s' % (table._tablename, form.record_id)) if formname!=DEFAULT: _formname = formname keepvalues = self.settings.keepvalues if request.vars.delete_this_record: keepvalues = False if isinstance(onvalidation,StorageList): onvalidation=onvalidation.get(table._tablename, []) if form.accepts(request, _session, formname=_formname, onvalidation=onvalidation, keepvalues=keepvalues, hideerror=self.settings.hideerror, detect_record_change = self.settings.detect_record_change): self.accepted = True response.flash = message if log: self.log_event(log % form.vars) if request.vars.delete_this_record: self.deleted = True message = self.messages.record_deleted callback(ondelete,form,table._tablename) response.flash = message callback(onaccept,form,table._tablename) if not request.extension in ('html','load'): raise HTTP(200, 'RECORD CREATED/UPDATED') if isinstance(next, (list, tuple)): ### fix issue with 2.6 next = next[0] if next: # Only redirect when explicit if next[0] != '/' and next[:4] != 'http': next = URL(r=request, f=next.replace('[id]', str(form.vars.id))) session.flash = response.flash redirect(next) elif not request.extension in ('html','load'): raise HTTP(401) return form def create( self, table, next=DEFAULT, onvalidation=DEFAULT, onaccept=DEFAULT, log=DEFAULT, message=DEFAULT, formname=DEFAULT, ): """ .. method:: Crud.create(table, [next=DEFAULT [, onvalidation=DEFAULT [, onaccept=DEFAULT [, log=DEFAULT[, message=DEFAULT]]]]]) """ if next == DEFAULT: next = self.settings.create_next if onvalidation == DEFAULT: onvalidation = self.settings.create_onvalidation if onaccept == DEFAULT: onaccept = self.settings.create_onaccept if log == DEFAULT: log = self.messages.create_log if message == DEFAULT: message = self.messages.record_created return self.update( table, None, next=next, onvalidation=onvalidation, onaccept=onaccept, log=log, message=message, deletable=False, formname=formname, ) def read(self, table, record): if not (isinstance(table, self.db.Table) or table in self.db.tables) \ or (isinstance(record, str) and not str(record).isdigit()): raise HTTP(404) if not isinstance(table, self.db.Table): table = self.db[table] if not self.has_permission('read', table, record): redirect(self.settings.auth.settings.on_failed_authorization) form = SQLFORM( table, record, readonly=True, comments=False, upload=self.settings.download_url, showid=self.settings.showid, formstyle=self.settings.formstyle, separator=self.settings.label_separator ) if not current.request.extension in ('html','load'): return table._filter_fields(form.record, id=True) return form def delete( self, table, record_id, next=DEFAULT, message=DEFAULT, ): """ .. method:: Crud.delete(table, record_id, [next=DEFAULT [, message=DEFAULT]]) """ if not (isinstance(table, self.db.Table) or table in self.db.tables) \ or not str(record_id).isdigit(): raise HTTP(404) if not isinstance(table, self.db.Table): table = self.db[table] if not self.has_permission('delete', table, record_id): redirect(self.settings.auth.settings.on_failed_authorization) request = current.request session = current.session if next == DEFAULT: next = request.get_vars._next \ or request.post_vars._next \ or self.settings.delete_next if message == DEFAULT: message = self.messages.record_deleted record = table[record_id] if record: callback(self.settings.delete_onvalidation,record) del table[record_id] callback(self.settings.delete_onaccept,record,table._tablename) session.flash = message if next: # Only redirect when explicit redirect(next) def rows( self, table, query=None, fields=None, orderby=None, limitby=None, ): request = current.request if not (isinstance(table, self.db.Table) or table in self.db.tables): raise HTTP(404) if not self.has_permission('select', table): redirect(self.settings.auth.settings.on_failed_authorization) #if record_id and not self.has_permission('select', table): # redirect(self.settings.auth.settings.on_failed_authorization) if not isinstance(table, self.db.Table): table = self.db[table] if not query: query = table.id > 0 if not fields: fields = [field for field in table if field.readable] rows = self.db(query).select(*fields,**dict(orderby=orderby, limitby=limitby)) return rows def select( self, table, query=None, fields=None, orderby=None, limitby=None, headers={}, **attr ): rows = self.rows(table,query,fields,orderby,limitby) if not rows: return None # Nicer than an empty table. if not 'upload' in attr: attr['upload'] = self.url('download') if not current.request.extension in ('html','load'): return rows.as_list() if not headers: if isinstance(table,str): table = self.db[table] headers = dict((str(k),k.label) for k in table) return SQLTABLE(rows,headers=headers,**attr) def get_format(self, field): rtable = field._db[field.type[10:]] format = rtable.get('_format', None) if format and isinstance(format, str): return format[2:-2] return field.name def get_query(self, field, op, value, refsearch=False): try: if refsearch: format = self.get_format(field) if op == 'equals': if not refsearch: return field == value else: return lambda row: row[field.name][format] == value elif op == 'not equal': if not refsearch: return field != value else: return lambda row: row[field.name][format] != value elif op == 'greater than': if not refsearch: return field > value else: return lambda row: row[field.name][format] > value elif op == 'less than': if not refsearch: return field < value else: return lambda row: row[field.name][format] < value elif op == 'starts with': if not refsearch: return field.like(value+'%') else: return lambda row: str(row[field.name][format]).startswith(value) elif op == 'ends with': if not refsearch: return field.like('%'+value) else: return lambda row: str(row[field.name][format]).endswith(value) elif op == 'contains': if not refsearch: return field.like('%'+value+'%') else: return lambda row: value in row[field.name][format] except: return None def search(self, *tables, **args): """ Creates a search form and its results for a table Example usage: form, results = crud.search(db.test, queries = ['equals', 'not equal', 'contains'], query_labels={'equals':'Equals', 'not equal':'Not equal'}, fields = ['id','children'], field_labels = {'id':'ID','children':'Children'}, zero='Please choose', query = (db.test.id > 0)&(db.test.id != 3) ) """ table = tables[0] fields = args.get('fields', table.fields) request = current.request db = self.db if not (isinstance(table, db.Table) or table in db.tables): raise HTTP(404) attributes = {} for key in ('orderby','groupby','left','distinct','limitby','cache'): if key in args: attributes[key]=args[key] tbl = TABLE() selected = []; refsearch = []; results = [] ops = args.get('queries', []) zero = args.get('zero', '') if not ops: ops = ['equals', 'not equal', 'greater than', 'less than', 'starts with', 'ends with', 'contains'] ops.insert(0,zero) query_labels = args.get('query_labels', {}) query = args.get('query',table.id > 0) field_labels = args.get('field_labels',{}) for field in fields: field = table[field] if not field.readable: continue fieldname = field.name chkval = request.vars.get('chk' + fieldname, None) txtval = request.vars.get('txt' + fieldname, None) opval = request.vars.get('op' + fieldname, None) row = TR(TD(INPUT(_type = "checkbox", _name = "chk" + fieldname, _disabled = (field.type == 'id'), value = (field.type == 'id' or chkval == 'on'))), TD(field_labels.get(fieldname,field.label)), TD(SELECT([OPTION(query_labels.get(op,op), _value=op) for op in ops], _name = "op" + fieldname, value = opval)), TD(INPUT(_type = "text", _name = "txt" + fieldname, _value = txtval, _id='txt' + fieldname, _class = str(field.type)))) tbl.append(row) if request.post_vars and (chkval or field.type=='id'): if txtval and opval != '': if field.type[0:10] == 'reference ': refsearch.append(self.get_query(field, opval, txtval, refsearch=True)) else: value, error = field.validate(txtval) if not error: ### TODO deal with 'starts with', 'ends with', 'contains' on GAE query &= self.get_query(field, opval, value) else: row[3].append(DIV(error,_class='error')) selected.append(field) form = FORM(tbl,INPUT(_type="submit")) if selected: try: results = db(query).select(*selected,**attributes) for r in refsearch: results = results.find(r) except: # hmmm, we should do better here results = None return form, results urllib2.install_opener(urllib2.build_opener(urllib2.HTTPCookieProcessor())) def fetch(url, data=None, headers={}, cookie=Cookie.SimpleCookie(), user_agent='Mozilla/5.0'): if data != None: data = urllib.urlencode(data) if user_agent: headers['User-agent'] = user_agent headers['Cookie'] = ' '.join(['%s=%s;'%(c.key,c.value) for c in cookie.values()]) try: from google.appengine.api import urlfetch except ImportError: req = urllib2.Request(url, data, headers) html = urllib2.urlopen(req).read() else: method = ((data==None) and urlfetch.GET) or urlfetch.POST while url is not None: response = urlfetch.fetch(url=url, payload=data, method=method, headers=headers, allow_truncated=False,follow_redirects=False, deadline=10) # next request will be a get, so no need to send the data again data = None method = urlfetch.GET # load cookies from the response cookie.load(response.headers.get('set-cookie', '')) url = response.headers.get('location') html = response.content return html regex_geocode = \ re.compile('\<coordinates\>(?P<la>[^,]*),(?P<lo>[^,]*).*?\</coordinates\>') def geocode(address): try: a = urllib.quote(address) txt = fetch('http://maps.google.com/maps/geo?q=%s&output=xml' % a) item = regex_geocode.search(txt) (la, lo) = (float(item.group('la')), float(item.group('lo'))) return (la, lo) except: return (0.0, 0.0) def universal_caller(f, *a, **b): c = f.func_code.co_argcount n = f.func_code.co_varnames[:c] defaults = f.func_defaults or [] pos_args = n[0:-len(defaults)] named_args = n[-len(defaults):] arg_dict = {} # Fill the arg_dict with name and value for the submitted, positional values for pos_index, pos_val in enumerate(a[:c]): arg_dict[n[pos_index]] = pos_val # n[pos_index] is the name of the argument # There might be pos_args left, that are sent as named_values. Gather them as well. # If a argument already is populated with values we simply replaces them. for arg_name in pos_args[len(arg_dict):]: if b.has_key(arg_name): arg_dict[arg_name] = b[arg_name] if len(arg_dict) >= len(pos_args): # All the positional arguments is found. The function may now be called. # However, we need to update the arg_dict with the values from the named arguments as well. for arg_name in named_args: if b.has_key(arg_name): arg_dict[arg_name] = b[arg_name] return f(**arg_dict) # Raise an error, the function cannot be called. raise HTTP(404, "Object does not exist") class Service(object): def __init__(self, environment=None): self.run_procedures = {} self.csv_procedures = {} self.xml_procedures = {} self.rss_procedures = {} self.json_procedures = {} self.jsonrpc_procedures = {} self.xmlrpc_procedures = {} self.amfrpc_procedures = {} self.amfrpc3_procedures = {} self.soap_procedures = {} def run(self, f): """ example:: service = Service(globals()) @service.run def myfunction(a, b): return a + b def call(): return service() Then call it with:: wget http://..../app/default/call/run/myfunction?a=3&b=4 """ self.run_procedures[f.__name__] = f return f def csv(self, f): """ example:: service = Service(globals()) @service.csv def myfunction(a, b): return a + b def call(): return service() Then call it with:: wget http://..../app/default/call/csv/myfunction?a=3&b=4 """ self.run_procedures[f.__name__] = f return f def xml(self, f): """ example:: service = Service(globals()) @service.xml def myfunction(a, b): return a + b def call(): return service() Then call it with:: wget http://..../app/default/call/xml/myfunction?a=3&b=4 """ self.run_procedures[f.__name__] = f return f def rss(self, f): """ example:: service = Service(globals()) @service.rss def myfunction(): return dict(title=..., link=..., description=..., created_on=..., entries=[dict(title=..., link=..., description=..., created_on=...]) def call(): return service() Then call it with:: wget http://..../app/default/call/rss/myfunction """ self.rss_procedures[f.__name__] = f return f def json(self, f): """ example:: service = Service(globals()) @service.json def myfunction(a, b): return [{a: b}] def call(): return service() Then call it with:: wget http://..../app/default/call/json/myfunction?a=hello&b=world """ self.json_procedures[f.__name__] = f return f def jsonrpc(self, f): """ example:: service = Service(globals()) @service.jsonrpc def myfunction(a, b): return a + b def call(): return service() Then call it with:: wget http://..../app/default/call/jsonrpc/myfunction?a=hello&b=world """ self.jsonrpc_procedures[f.__name__] = f return f def xmlrpc(self, f): """ example:: service = Service(globals()) @service.xmlrpc def myfunction(a, b): return a + b def call(): return service() The call it with:: wget http://..../app/default/call/xmlrpc/myfunction?a=hello&b=world """ self.xmlrpc_procedures[f.__name__] = f return f def amfrpc(self, f): """ example:: service = Service(globals()) @service.amfrpc def myfunction(a, b): return a + b def call(): return service() The call it with:: wget http://..../app/default/call/amfrpc/myfunction?a=hello&b=world """ self.amfrpc_procedures[f.__name__] = f return f def amfrpc3(self, domain='default'): """ example:: service = Service(globals()) @service.amfrpc3('domain') def myfunction(a, b): return a + b def call(): return service() The call it with:: wget http://..../app/default/call/amfrpc3/myfunction?a=hello&b=world """ if not isinstance(domain, str): raise SyntaxError, "AMF3 requires a domain for function" def _amfrpc3(f): if domain: self.amfrpc3_procedures[domain+'.'+f.__name__] = f else: self.amfrpc3_procedures[f.__name__] = f return f return _amfrpc3 def soap(self, name=None, returns=None, args=None,doc=None): """ example:: service = Service(globals()) @service.soap('MyFunction',returns={'result':int},args={'a':int,'b':int,}) def myfunction(a, b): return a + b def call(): return service() The call it with:: from gluon.contrib.pysimplesoap.client import SoapClient client = SoapClient(wsdl="http://..../app/default/call/soap?WSDL") response = client.MyFunction(a=1,b=2) return response['result'] Exposes online generated documentation and xml example messages at: - http://..../app/default/call/soap """ def _soap(f): self.soap_procedures[name or f.__name__] = f, returns, args, doc return f return _soap def serve_run(self, args=None): request = current.request if not args: args = request.args if args and args[0] in self.run_procedures: return str(universal_caller(self.run_procedures[args[0]], *args[1:], **dict(request.vars))) self.error() def serve_csv(self, args=None): request = current.request response = current.response response.headers['Content-Type'] = 'text/x-csv' if not args: args = request.args def none_exception(value): if isinstance(value, unicode): return value.encode('utf8') if hasattr(value, 'isoformat'): return value.isoformat()[:19].replace('T', ' ') if value == None: return '<NULL>' return value if args and args[0] in self.run_procedures: r = universal_caller(self.run_procedures[args[0]], *args[1:], **dict(request.vars)) s = cStringIO.StringIO() if hasattr(r, 'export_to_csv_file'): r.export_to_csv_file(s) elif r and isinstance(r[0], (dict, Storage)): import csv writer = csv.writer(s) writer.writerow(r[0].keys()) for line in r: writer.writerow([none_exception(v) \ for v in line.values()]) else: import csv writer = csv.writer(s) for line in r: writer.writerow(line) return s.getvalue() self.error() def serve_xml(self, args=None): request = current.request response = current.response response.headers['Content-Type'] = 'text/xml' if not args: args = request.args if args and args[0] in self.run_procedures: s = universal_caller(self.run_procedures[args[0]], *args[1:], **dict(request.vars)) if hasattr(s, 'as_list'): s = s.as_list() return serializers.xml(s) self.error() def serve_rss(self, args=None): request = current.request response = current.response if not args: args = request.args if args and args[0] in self.rss_procedures: feed = universal_caller(self.rss_procedures[args[0]], *args[1:], **dict(request.vars)) else: self.error() response.headers['Content-Type'] = 'application/rss+xml' return serializers.rss(feed) def serve_json(self, args=None): request = current.request response = current.response response.headers['Content-Type'] = 'text/x-json' if not args: args = request.args d = dict(request.vars) if args and args[0] in self.json_procedures: s = universal_caller(self.json_procedures[args[0]],*args[1:],**d) if hasattr(s, 'as_list'): s = s.as_list() return response.json(s) self.error() class JsonRpcException(Exception): def __init__(self,code,info): self.code,self.info = code,info def serve_jsonrpc(self): import contrib.simplejson as simplejson def return_response(id, result): return serializers.json({'version': '1.1', 'id': id, 'result': result, 'error': None}) def return_error(id, code, message): return serializers.json({'id': id, 'version': '1.1', 'error': {'name': 'JSONRPCError', 'code': code, 'message': message} }) request = current.request methods = self.jsonrpc_procedures data = simplejson.loads(request.body.read()) id, method, params = data['id'], data['method'], data.get('params','') if not method in methods: return return_error(id, 100, 'method "%s" does not exist' % method) try: s = methods[method](*params) if hasattr(s, 'as_list'): s = s.as_list() return return_response(id, s) except Service.JsonRpcException, e: return return_error(id, e.code, e.info) except BaseException: etype, eval, etb = sys.exc_info() return return_error(id, 100, '%s: %s' % (etype.__name__, eval)) except: etype, eval, etb = sys.exc_info() return return_error(id, 100, 'Exception %s: %s' % (etype, eval)) def serve_xmlrpc(self): request = current.request response = current.response services = self.xmlrpc_procedures.values() return response.xmlrpc(request, services) def serve_amfrpc(self, version=0): try: import pyamf import pyamf.remoting.gateway except: return "pyamf not installed or not in Python sys.path" request = current.request response = current.response if version == 3: services = self.amfrpc3_procedures base_gateway = pyamf.remoting.gateway.BaseGateway(services) pyamf_request = pyamf.remoting.decode(request.body) else: services = self.amfrpc_procedures base_gateway = pyamf.remoting.gateway.BaseGateway(services) context = pyamf.get_context(pyamf.AMF0) pyamf_request = pyamf.remoting.decode(request.body, context) pyamf_response = pyamf.remoting.Envelope(pyamf_request.amfVersion) for name, message in pyamf_request: pyamf_response[name] = base_gateway.getProcessor(message)(message) response.headers['Content-Type'] = pyamf.remoting.CONTENT_TYPE if version==3: return pyamf.remoting.encode(pyamf_response).getvalue() else: return pyamf.remoting.encode(pyamf_response, context).getvalue() def serve_soap(self, version="1.1"): try: from contrib.pysimplesoap.server import SoapDispatcher except: return "pysimplesoap not installed in contrib" request = current.request response = current.response procedures = self.soap_procedures location = "%s://%s%s" % ( request.env.wsgi_url_scheme, request.env.http_host, URL(r=request,f="call/soap",vars={})) namespace = 'namespace' in response and response.namespace or location documentation = response.description or '' dispatcher = SoapDispatcher( name = response.title, location = location, action = location, # SOAPAction namespace = namespace, prefix='pys', documentation = documentation, ns = True) for method, (function, returns, args, doc) in procedures.items(): dispatcher.register_function(method, function, returns, args, doc) if request.env.request_method == 'POST': # Process normal Soap Operation response.headers['Content-Type'] = 'text/xml' return dispatcher.dispatch(request.body.read()) elif 'WSDL' in request.vars: # Return Web Service Description response.headers['Content-Type'] = 'text/xml' return dispatcher.wsdl() elif 'op' in request.vars: # Return method help webpage response.headers['Content-Type'] = 'text/html' method = request.vars['op'] sample_req_xml, sample_res_xml, doc = dispatcher.help(method) body = [H1("Welcome to Web2Py SOAP webservice gateway"), A("See all webservice operations", _href=URL(r=request,f="call/soap",vars={})), H2(method), P(doc), UL(LI("Location: %s" % dispatcher.location), LI("Namespace: %s" % dispatcher.namespace), LI("SoapAction: %s" % dispatcher.action), ), H3("Sample SOAP XML Request Message:"), CODE(sample_req_xml,language="xml"), H3("Sample SOAP XML Response Message:"), CODE(sample_res_xml,language="xml"), ] return {'body': body} else: # Return general help and method list webpage response.headers['Content-Type'] = 'text/html' body = [H1("Welcome to Web2Py SOAP webservice gateway"), P(response.description), P("The following operations are available"), A("See WSDL for webservice description", _href=URL(r=request,f="call/soap",vars={"WSDL":None})), UL([LI(A("%s: %s" % (method, doc or ''), _href=URL(r=request,f="call/soap",vars={'op': method}))) for method, doc in dispatcher.list_methods()]), ] return {'body': body} def __call__(self): """ register services with: service = Service(globals()) @service.run @service.rss @service.json @service.jsonrpc @service.xmlrpc @service.jsonrpc @service.amfrpc @service.amfrpc3('domain') @service.soap('Method', returns={'Result':int}, args={'a':int,'b':int,}) expose services with def call(): return service() call services with http://..../app/default/call/run?[parameters] http://..../app/default/call/rss?[parameters] http://..../app/default/call/json?[parameters] http://..../app/default/call/jsonrpc http://..../app/default/call/xmlrpc http://..../app/default/call/amfrpc http://..../app/default/call/amfrpc3 http://..../app/default/call/soap """ request = current.request if len(request.args) < 1: raise HTTP(404, "Not Found") arg0 = request.args(0) if arg0 == 'run': return self.serve_run(request.args[1:]) elif arg0 == 'rss': return self.serve_rss(request.args[1:]) elif arg0 == 'csv': return self.serve_csv(request.args[1:]) elif arg0 == 'xml': return self.serve_xml(request.args[1:]) elif arg0 == 'json': return self.serve_json(request.args[1:]) elif arg0 == 'jsonrpc': return self.serve_jsonrpc() elif arg0 == 'xmlrpc': return self.serve_xmlrpc() elif arg0 == 'amfrpc': return self.serve_amfrpc() elif arg0 == 'amfrpc3': return self.serve_amfrpc(3) elif arg0 == 'soap': return self.serve_soap() else: self.error() def error(self): raise HTTP(404, "Object does not exist") def completion(callback): """ Executes a task on completion of the called action. For example: from gluon.tools import completion @completion(lambda d: logging.info(repr(d))) def index(): return dict(message='hello') It logs the output of the function every time input is called. The argument of completion is executed in a new thread. """ def _completion(f): def __completion(*a,**b): d = None try: d = f(*a,**b) return d finally: thread.start_new_thread(callback,(d,)) return __completion return _completion def prettydate(d,T=lambda x:x): try: dt = datetime.datetime.now() - d except: return '' if dt.days >= 2*365: return T('%d years ago') % int(dt.days / 365) elif dt.days >= 365: return T('1 year ago') elif dt.days >= 60: return T('%d months ago') % int(dt.days / 30) elif dt.days > 21: return T('1 month ago') elif dt.days >= 14: return T('%d weeks ago') % int(dt.days / 7) elif dt.days >= 7: return T('1 week ago') elif dt.days > 1: return T('%d days ago') % dt.days elif dt.days == 1: return T('1 day ago') elif dt.seconds >= 2*60*60: return T('%d hours ago') % int(dt.seconds / 3600) elif dt.seconds >= 60*60: return T('1 hour ago') elif dt.seconds >= 2*60: return T('%d minutes ago') % int(dt.seconds / 60) elif dt.seconds >= 60: return T('1 minute ago') elif dt.seconds > 1: return T('%d seconds ago') % dt.seconds elif dt.seconds == 1: return T('1 second ago') else: return T('now') def test_thread_separation(): def f(): c=PluginManager() lock1.acquire() lock2.acquire() c.x=7 lock1.release() lock2.release() lock1=thread.allocate_lock() lock2=thread.allocate_lock() lock1.acquire() thread.start_new_thread(f,()) a=PluginManager() a.x=5 lock1.release() lock2.acquire() return a.x class PluginManager(object): """ Plugin Manager is similar to a storage object but it is a single level singleton this means that multiple instances within the same thread share the same attributes Its constructor is also special. The first argument is the name of the plugin you are defining. The named arguments are parameters needed by the plugin with default values. If the parameters were previous defined, the old values are used. For example: ### in some general configuration file: >>> plugins = PluginManager() >>> plugins.me.param1=3 ### within the plugin model >>> _ = PluginManager('me',param1=5,param2=6,param3=7) ### where the plugin is used >>> print plugins.me.param1 3 >>> print plugins.me.param2 6 >>> plugins.me.param3 = 8 >>> print plugins.me.param3 8 Here are some tests: >>> a=PluginManager() >>> a.x=6 >>> b=PluginManager('check') >>> print b.x 6 >>> b=PluginManager() # reset settings >>> print b.x <Storage {}> >>> b.x=7 >>> print a.x 7 >>> a.y.z=8 >>> print b.y.z 8 >>> test_thread_separation() 5 >>> plugins=PluginManager('me',db='mydb') >>> print plugins.me.db mydb >>> print 'me' in plugins True >>> print plugins.me.installed True """ instances = {} def __new__(cls,*a,**b): id = thread.get_ident() lock = thread.allocate_lock() try: lock.acquire() try: return cls.instances[id] except KeyError: instance = object.__new__(cls,*a,**b) cls.instances[id] = instance return instance finally: lock.release() def __init__(self,plugin=None,**defaults): if not plugin: self.__dict__.clear() settings = self.__getattr__(plugin) settings.installed = True [settings.update({key:value}) for key,value in defaults.items() if not key in settings] def __getattr__(self, key): if not key in self.__dict__: self.__dict__[key] = Storage() return self.__dict__[key] def keys(self): return self.__dict__.keys() def __contains__(self,key): return key in self.__dict__ if __name__ == '__main__': import doctest doctest.testmod()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) Functions required to execute app components ============================================ FOR INTERNAL USE ONLY """ import os import stat import thread from fileutils import read_file cfs = {} # for speed-up cfs_lock = thread.allocate_lock() # and thread safety def getcfs(key, filename, filter=None): """ Caches the *filtered* file `filename` with `key` until the file is modified. :param key: the cache key :param filename: the file to cache :param filter: is the function used for filtering. Normally `filename` is a .py file and `filter` is a function that bytecode compiles the file. In this way the bytecode compiled file is cached. (Default = None) This is used on Google App Engine since pyc files cannot be saved. """ t = os.stat(filename)[stat.ST_MTIME] cfs_lock.acquire() item = cfs.get(key, None) cfs_lock.release() if item and item[0] == t: return item[1] if not filter: data = read_file(filename) else: data = filter() cfs_lock.acquire() cfs[key] = (t, data) cfs_lock.release() return data
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) CONTENT_TYPE dictionary created against freedesktop.org' shared mime info database version 0.70. """ __all__ = ['contenttype'] CONTENT_TYPE = { '.load': 'text/html', '.123': 'application/vnd.lotus-1-2-3', '.3ds': 'image/x-3ds', '.3g2': 'video/3gpp', '.3ga': 'video/3gpp', '.3gp': 'video/3gpp', '.3gpp': 'video/3gpp', '.602': 'application/x-t602', '.669': 'audio/x-mod', '.7z': 'application/x-7z-compressed', '.a': 'application/x-archive', '.aac': 'audio/mp4', '.abw': 'application/x-abiword', '.abw.crashed': 'application/x-abiword', '.abw.gz': 'application/x-abiword', '.ac3': 'audio/ac3', '.ace': 'application/x-ace', '.adb': 'text/x-adasrc', '.ads': 'text/x-adasrc', '.afm': 'application/x-font-afm', '.ag': 'image/x-applix-graphics', '.ai': 'application/illustrator', '.aif': 'audio/x-aiff', '.aifc': 'audio/x-aiff', '.aiff': 'audio/x-aiff', '.al': 'application/x-perl', '.alz': 'application/x-alz', '.amr': 'audio/amr', '.ani': 'application/x-navi-animation', '.anim[1-9j]': 'video/x-anim', '.anx': 'application/annodex', '.ape': 'audio/x-ape', '.arj': 'application/x-arj', '.arw': 'image/x-sony-arw', '.as': 'application/x-applix-spreadsheet', '.asc': 'text/plain', '.asf': 'video/x-ms-asf', '.asp': 'application/x-asp', '.ass': 'text/x-ssa', '.asx': 'audio/x-ms-asx', '.atom': 'application/atom+xml', '.au': 'audio/basic', '.avi': 'video/x-msvideo', '.aw': 'application/x-applix-word', '.awb': 'audio/amr-wb', '.awk': 'application/x-awk', '.axa': 'audio/annodex', '.axv': 'video/annodex', '.bak': 'application/x-trash', '.bcpio': 'application/x-bcpio', '.bdf': 'application/x-font-bdf', '.bib': 'text/x-bibtex', '.bin': 'application/octet-stream', '.blend': 'application/x-blender', '.blender': 'application/x-blender', '.bmp': 'image/bmp', '.bz': 'application/x-bzip', '.bz2': 'application/x-bzip', '.c': 'text/x-csrc', '.c++': 'text/x-c++src', '.cab': 'application/vnd.ms-cab-compressed', '.cb7': 'application/x-cb7', '.cbr': 'application/x-cbr', '.cbt': 'application/x-cbt', '.cbz': 'application/x-cbz', '.cc': 'text/x-c++src', '.cdf': 'application/x-netcdf', '.cdr': 'application/vnd.corel-draw', '.cer': 'application/x-x509-ca-cert', '.cert': 'application/x-x509-ca-cert', '.cgm': 'image/cgm', '.chm': 'application/x-chm', '.chrt': 'application/x-kchart', '.class': 'application/x-java', '.cls': 'text/x-tex', '.cmake': 'text/x-cmake', '.cpio': 'application/x-cpio', '.cpio.gz': 'application/x-cpio-compressed', '.cpp': 'text/x-c++src', '.cr2': 'image/x-canon-cr2', '.crt': 'application/x-x509-ca-cert', '.crw': 'image/x-canon-crw', '.cs': 'text/x-csharp', '.csh': 'application/x-csh', '.css': 'text/css', '.cssl': 'text/css', '.csv': 'text/csv', '.cue': 'application/x-cue', '.cur': 'image/x-win-bitmap', '.cxx': 'text/x-c++src', '.d': 'text/x-dsrc', '.dar': 'application/x-dar', '.dbf': 'application/x-dbf', '.dc': 'application/x-dc-rom', '.dcl': 'text/x-dcl', '.dcm': 'application/dicom', '.dcr': 'image/x-kodak-dcr', '.dds': 'image/x-dds', '.deb': 'application/x-deb', '.der': 'application/x-x509-ca-cert', '.desktop': 'application/x-desktop', '.dia': 'application/x-dia-diagram', '.diff': 'text/x-patch', '.divx': 'video/x-msvideo', '.djv': 'image/vnd.djvu', '.djvu': 'image/vnd.djvu', '.dng': 'image/x-adobe-dng', '.doc': 'application/msword', '.docbook': 'application/docbook+xml', '.docm': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', '.dot': 'text/vnd.graphviz', '.dsl': 'text/x-dsl', '.dtd': 'application/xml-dtd', '.dtx': 'text/x-tex', '.dv': 'video/dv', '.dvi': 'application/x-dvi', '.dvi.bz2': 'application/x-bzdvi', '.dvi.gz': 'application/x-gzdvi', '.dwg': 'image/vnd.dwg', '.dxf': 'image/vnd.dxf', '.e': 'text/x-eiffel', '.egon': 'application/x-egon', '.eif': 'text/x-eiffel', '.el': 'text/x-emacs-lisp', '.emf': 'image/x-emf', '.emp': 'application/vnd.emusic-emusic_package', '.ent': 'application/xml-external-parsed-entity', '.eps': 'image/x-eps', '.eps.bz2': 'image/x-bzeps', '.eps.gz': 'image/x-gzeps', '.epsf': 'image/x-eps', '.epsf.bz2': 'image/x-bzeps', '.epsf.gz': 'image/x-gzeps', '.epsi': 'image/x-eps', '.epsi.bz2': 'image/x-bzeps', '.epsi.gz': 'image/x-gzeps', '.epub': 'application/epub+zip', '.erl': 'text/x-erlang', '.es': 'application/ecmascript', '.etheme': 'application/x-e-theme', '.etx': 'text/x-setext', '.exe': 'application/x-ms-dos-executable', '.exr': 'image/x-exr', '.ez': 'application/andrew-inset', '.f': 'text/x-fortran', '.f90': 'text/x-fortran', '.f95': 'text/x-fortran', '.fb2': 'application/x-fictionbook+xml', '.fig': 'image/x-xfig', '.fits': 'image/fits', '.fl': 'application/x-fluid', '.flac': 'audio/x-flac', '.flc': 'video/x-flic', '.fli': 'video/x-flic', '.flv': 'video/x-flv', '.flw': 'application/x-kivio', '.fo': 'text/x-xslfo', '.for': 'text/x-fortran', '.g3': 'image/fax-g3', '.gb': 'application/x-gameboy-rom', '.gba': 'application/x-gba-rom', '.gcrd': 'text/directory', '.ged': 'application/x-gedcom', '.gedcom': 'application/x-gedcom', '.gen': 'application/x-genesis-rom', '.gf': 'application/x-tex-gf', '.gg': 'application/x-sms-rom', '.gif': 'image/gif', '.glade': 'application/x-glade', '.gmo': 'application/x-gettext-translation', '.gnc': 'application/x-gnucash', '.gnd': 'application/gnunet-directory', '.gnucash': 'application/x-gnucash', '.gnumeric': 'application/x-gnumeric', '.gnuplot': 'application/x-gnuplot', '.gp': 'application/x-gnuplot', '.gpg': 'application/pgp-encrypted', '.gplt': 'application/x-gnuplot', '.gra': 'application/x-graphite', '.gsf': 'application/x-font-type1', '.gsm': 'audio/x-gsm', '.gtar': 'application/x-tar', '.gv': 'text/vnd.graphviz', '.gvp': 'text/x-google-video-pointer', '.gz': 'application/x-gzip', '.h': 'text/x-chdr', '.h++': 'text/x-c++hdr', '.hdf': 'application/x-hdf', '.hh': 'text/x-c++hdr', '.hp': 'text/x-c++hdr', '.hpgl': 'application/vnd.hp-hpgl', '.hpp': 'text/x-c++hdr', '.hs': 'text/x-haskell', '.htm': 'text/html', '.html': 'text/html', '.hwp': 'application/x-hwp', '.hwt': 'application/x-hwt', '.hxx': 'text/x-c++hdr', '.ica': 'application/x-ica', '.icb': 'image/x-tga', '.icns': 'image/x-icns', '.ico': 'image/vnd.microsoft.icon', '.ics': 'text/calendar', '.idl': 'text/x-idl', '.ief': 'image/ief', '.iff': 'image/x-iff', '.ilbm': 'image/x-ilbm', '.ime': 'text/x-imelody', '.imy': 'text/x-imelody', '.ins': 'text/x-tex', '.iptables': 'text/x-iptables', '.iso': 'application/x-cd-image', '.iso9660': 'application/x-cd-image', '.it': 'audio/x-it', '.j2k': 'image/jp2', '.jad': 'text/vnd.sun.j2me.app-descriptor', '.jar': 'application/x-java-archive', '.java': 'text/x-java', '.jng': 'image/x-jng', '.jnlp': 'application/x-java-jnlp-file', '.jp2': 'image/jp2', '.jpc': 'image/jp2', '.jpe': 'image/jpeg', '.jpeg': 'image/jpeg', '.jpf': 'image/jp2', '.jpg': 'image/jpeg', '.jpr': 'application/x-jbuilder-project', '.jpx': 'image/jp2', '.js': 'application/javascript', '.json': 'application/json', '.k25': 'image/x-kodak-k25', '.kar': 'audio/midi', '.karbon': 'application/x-karbon', '.kdc': 'image/x-kodak-kdc', '.kdelnk': 'application/x-desktop', '.kexi': 'application/x-kexiproject-sqlite3', '.kexic': 'application/x-kexi-connectiondata', '.kexis': 'application/x-kexiproject-shortcut', '.kfo': 'application/x-kformula', '.kil': 'application/x-killustrator', '.kino': 'application/smil', '.kml': 'application/vnd.google-earth.kml+xml', '.kmz': 'application/vnd.google-earth.kmz', '.kon': 'application/x-kontour', '.kpm': 'application/x-kpovmodeler', '.kpr': 'application/x-kpresenter', '.kpt': 'application/x-kpresenter', '.kra': 'application/x-krita', '.ksp': 'application/x-kspread', '.kud': 'application/x-kugar', '.kwd': 'application/x-kword', '.kwt': 'application/x-kword', '.la': 'application/x-shared-library-la', '.latex': 'text/x-tex', '.ldif': 'text/x-ldif', '.lha': 'application/x-lha', '.lhs': 'text/x-literate-haskell', '.lhz': 'application/x-lhz', '.log': 'text/x-log', '.ltx': 'text/x-tex', '.lua': 'text/x-lua', '.lwo': 'image/x-lwo', '.lwob': 'image/x-lwo', '.lws': 'image/x-lws', '.ly': 'text/x-lilypond', '.lyx': 'application/x-lyx', '.lz': 'application/x-lzip', '.lzh': 'application/x-lha', '.lzma': 'application/x-lzma', '.lzo': 'application/x-lzop', '.m': 'text/x-matlab', '.m15': 'audio/x-mod', '.m2t': 'video/mpeg', '.m3u': 'audio/x-mpegurl', '.m3u8': 'audio/x-mpegurl', '.m4': 'application/x-m4', '.m4a': 'audio/mp4', '.m4b': 'audio/x-m4b', '.m4v': 'video/mp4', '.mab': 'application/x-markaby', '.man': 'application/x-troff-man', '.mbox': 'application/mbox', '.md': 'application/x-genesis-rom', '.mdb': 'application/vnd.ms-access', '.mdi': 'image/vnd.ms-modi', '.me': 'text/x-troff-me', '.med': 'audio/x-mod', '.metalink': 'application/metalink+xml', '.mgp': 'application/x-magicpoint', '.mid': 'audio/midi', '.midi': 'audio/midi', '.mif': 'application/x-mif', '.minipsf': 'audio/x-minipsf', '.mka': 'audio/x-matroska', '.mkv': 'video/x-matroska', '.ml': 'text/x-ocaml', '.mli': 'text/x-ocaml', '.mm': 'text/x-troff-mm', '.mmf': 'application/x-smaf', '.mml': 'text/mathml', '.mng': 'video/x-mng', '.mo': 'application/x-gettext-translation', '.mo3': 'audio/x-mo3', '.moc': 'text/x-moc', '.mod': 'audio/x-mod', '.mof': 'text/x-mof', '.moov': 'video/quicktime', '.mov': 'video/quicktime', '.movie': 'video/x-sgi-movie', '.mp+': 'audio/x-musepack', '.mp2': 'video/mpeg', '.mp3': 'audio/mpeg', '.mp4': 'video/mp4', '.mpc': 'audio/x-musepack', '.mpe': 'video/mpeg', '.mpeg': 'video/mpeg', '.mpg': 'video/mpeg', '.mpga': 'audio/mpeg', '.mpp': 'audio/x-musepack', '.mrl': 'text/x-mrml', '.mrml': 'text/x-mrml', '.mrw': 'image/x-minolta-mrw', '.ms': 'text/x-troff-ms', '.msi': 'application/x-msi', '.msod': 'image/x-msod', '.msx': 'application/x-msx-rom', '.mtm': 'audio/x-mod', '.mup': 'text/x-mup', '.mxf': 'application/mxf', '.n64': 'application/x-n64-rom', '.nb': 'application/mathematica', '.nc': 'application/x-netcdf', '.nds': 'application/x-nintendo-ds-rom', '.nef': 'image/x-nikon-nef', '.nes': 'application/x-nes-rom', '.nfo': 'text/x-nfo', '.not': 'text/x-mup', '.nsc': 'application/x-netshow-channel', '.nsv': 'video/x-nsv', '.o': 'application/x-object', '.obj': 'application/x-tgif', '.ocl': 'text/x-ocl', '.oda': 'application/oda', '.odb': 'application/vnd.oasis.opendocument.database', '.odc': 'application/vnd.oasis.opendocument.chart', '.odf': 'application/vnd.oasis.opendocument.formula', '.odg': 'application/vnd.oasis.opendocument.graphics', '.odi': 'application/vnd.oasis.opendocument.image', '.odm': 'application/vnd.oasis.opendocument.text-master', '.odp': 'application/vnd.oasis.opendocument.presentation', '.ods': 'application/vnd.oasis.opendocument.spreadsheet', '.odt': 'application/vnd.oasis.opendocument.text', '.oga': 'audio/ogg', '.ogg': 'video/x-theora+ogg', '.ogm': 'video/x-ogm+ogg', '.ogv': 'video/ogg', '.ogx': 'application/ogg', '.old': 'application/x-trash', '.oleo': 'application/x-oleo', '.opml': 'text/x-opml+xml', '.ora': 'image/openraster', '.orf': 'image/x-olympus-orf', '.otc': 'application/vnd.oasis.opendocument.chart-template', '.otf': 'application/x-font-otf', '.otg': 'application/vnd.oasis.opendocument.graphics-template', '.oth': 'application/vnd.oasis.opendocument.text-web', '.otp': 'application/vnd.oasis.opendocument.presentation-template', '.ots': 'application/vnd.oasis.opendocument.spreadsheet-template', '.ott': 'application/vnd.oasis.opendocument.text-template', '.owl': 'application/rdf+xml', '.oxt': 'application/vnd.openofficeorg.extension', '.p': 'text/x-pascal', '.p10': 'application/pkcs10', '.p12': 'application/x-pkcs12', '.p7b': 'application/x-pkcs7-certificates', '.p7s': 'application/pkcs7-signature', '.pack': 'application/x-java-pack200', '.pak': 'application/x-pak', '.par2': 'application/x-par2', '.pas': 'text/x-pascal', '.patch': 'text/x-patch', '.pbm': 'image/x-portable-bitmap', '.pcd': 'image/x-photo-cd', '.pcf': 'application/x-cisco-vpn-settings', '.pcf.gz': 'application/x-font-pcf', '.pcf.z': 'application/x-font-pcf', '.pcl': 'application/vnd.hp-pcl', '.pcx': 'image/x-pcx', '.pdb': 'chemical/x-pdb', '.pdc': 'application/x-aportisdoc', '.pdf': 'application/pdf', '.pdf.bz2': 'application/x-bzpdf', '.pdf.gz': 'application/x-gzpdf', '.pef': 'image/x-pentax-pef', '.pem': 'application/x-x509-ca-cert', '.perl': 'application/x-perl', '.pfa': 'application/x-font-type1', '.pfb': 'application/x-font-type1', '.pfx': 'application/x-pkcs12', '.pgm': 'image/x-portable-graymap', '.pgn': 'application/x-chess-pgn', '.pgp': 'application/pgp-encrypted', '.php': 'application/x-php', '.php3': 'application/x-php', '.php4': 'application/x-php', '.pict': 'image/x-pict', '.pict1': 'image/x-pict', '.pict2': 'image/x-pict', '.pickle': 'application/python-pickle', '.pk': 'application/x-tex-pk', '.pkipath': 'application/pkix-pkipath', '.pkr': 'application/pgp-keys', '.pl': 'application/x-perl', '.pla': 'audio/x-iriver-pla', '.pln': 'application/x-planperfect', '.pls': 'audio/x-scpls', '.pm': 'application/x-perl', '.png': 'image/png', '.pnm': 'image/x-portable-anymap', '.pntg': 'image/x-macpaint', '.po': 'text/x-gettext-translation', '.por': 'application/x-spss-por', '.pot': 'text/x-gettext-translation-template', '.ppm': 'image/x-portable-pixmap', '.pps': 'application/vnd.ms-powerpoint', '.ppt': 'application/vnd.ms-powerpoint', '.pptm': 'application/vnd.openxmlformats-officedocument.presentationml.presentation', '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation', '.ppz': 'application/vnd.ms-powerpoint', '.prc': 'application/x-palm-database', '.ps': 'application/postscript', '.ps.bz2': 'application/x-bzpostscript', '.ps.gz': 'application/x-gzpostscript', '.psd': 'image/vnd.adobe.photoshop', '.psf': 'audio/x-psf', '.psf.gz': 'application/x-gz-font-linux-psf', '.psflib': 'audio/x-psflib', '.psid': 'audio/prs.sid', '.psw': 'application/x-pocket-word', '.pw': 'application/x-pw', '.py': 'text/x-python', '.pyc': 'application/x-python-bytecode', '.pyo': 'application/x-python-bytecode', '.qif': 'image/x-quicktime', '.qt': 'video/quicktime', '.qtif': 'image/x-quicktime', '.qtl': 'application/x-quicktime-media-link', '.qtvr': 'video/quicktime', '.ra': 'audio/vnd.rn-realaudio', '.raf': 'image/x-fuji-raf', '.ram': 'application/ram', '.rar': 'application/x-rar', '.ras': 'image/x-cmu-raster', '.raw': 'image/x-panasonic-raw', '.rax': 'audio/vnd.rn-realaudio', '.rb': 'application/x-ruby', '.rdf': 'application/rdf+xml', '.rdfs': 'application/rdf+xml', '.reg': 'text/x-ms-regedit', '.rej': 'application/x-reject', '.rgb': 'image/x-rgb', '.rle': 'image/rle', '.rm': 'application/vnd.rn-realmedia', '.rmj': 'application/vnd.rn-realmedia', '.rmm': 'application/vnd.rn-realmedia', '.rms': 'application/vnd.rn-realmedia', '.rmvb': 'application/vnd.rn-realmedia', '.rmx': 'application/vnd.rn-realmedia', '.roff': 'text/troff', '.rp': 'image/vnd.rn-realpix', '.rpm': 'application/x-rpm', '.rss': 'application/rss+xml', '.rt': 'text/vnd.rn-realtext', '.rtf': 'application/rtf', '.rtx': 'text/richtext', '.rv': 'video/vnd.rn-realvideo', '.rvx': 'video/vnd.rn-realvideo', '.s3m': 'audio/x-s3m', '.sam': 'application/x-amipro', '.sami': 'application/x-sami', '.sav': 'application/x-spss-sav', '.scm': 'text/x-scheme', '.sda': 'application/vnd.stardivision.draw', '.sdc': 'application/vnd.stardivision.calc', '.sdd': 'application/vnd.stardivision.impress', '.sdp': 'application/sdp', '.sds': 'application/vnd.stardivision.chart', '.sdw': 'application/vnd.stardivision.writer', '.sgf': 'application/x-go-sgf', '.sgi': 'image/x-sgi', '.sgl': 'application/vnd.stardivision.writer', '.sgm': 'text/sgml', '.sgml': 'text/sgml', '.sh': 'application/x-shellscript', '.shar': 'application/x-shar', '.shn': 'application/x-shorten', '.siag': 'application/x-siag', '.sid': 'audio/prs.sid', '.sik': 'application/x-trash', '.sis': 'application/vnd.symbian.install', '.sisx': 'x-epoc/x-sisx-app', '.sit': 'application/x-stuffit', '.siv': 'application/sieve', '.sk': 'image/x-skencil', '.sk1': 'image/x-skencil', '.skr': 'application/pgp-keys', '.slk': 'text/spreadsheet', '.smaf': 'application/x-smaf', '.smc': 'application/x-snes-rom', '.smd': 'application/vnd.stardivision.mail', '.smf': 'application/vnd.stardivision.math', '.smi': 'application/x-sami', '.smil': 'application/smil', '.sml': 'application/smil', '.sms': 'application/x-sms-rom', '.snd': 'audio/basic', '.so': 'application/x-sharedlib', '.spc': 'application/x-pkcs7-certificates', '.spd': 'application/x-font-speedo', '.spec': 'text/x-rpm-spec', '.spl': 'application/x-shockwave-flash', '.spx': 'audio/x-speex', '.sql': 'text/x-sql', '.sr2': 'image/x-sony-sr2', '.src': 'application/x-wais-source', '.srf': 'image/x-sony-srf', '.srt': 'application/x-subrip', '.ssa': 'text/x-ssa', '.stc': 'application/vnd.sun.xml.calc.template', '.std': 'application/vnd.sun.xml.draw.template', '.sti': 'application/vnd.sun.xml.impress.template', '.stm': 'audio/x-stm', '.stw': 'application/vnd.sun.xml.writer.template', '.sty': 'text/x-tex', '.sub': 'text/x-subviewer', '.sun': 'image/x-sun-raster', '.sv4cpio': 'application/x-sv4cpio', '.sv4crc': 'application/x-sv4crc', '.svg': 'image/svg+xml', '.svgz': 'image/svg+xml-compressed', '.swf': 'application/x-shockwave-flash', '.sxc': 'application/vnd.sun.xml.calc', '.sxd': 'application/vnd.sun.xml.draw', '.sxg': 'application/vnd.sun.xml.writer.global', '.sxi': 'application/vnd.sun.xml.impress', '.sxm': 'application/vnd.sun.xml.math', '.sxw': 'application/vnd.sun.xml.writer', '.sylk': 'text/spreadsheet', '.t': 'text/troff', '.t2t': 'text/x-txt2tags', '.tar': 'application/x-tar', '.tar.bz': 'application/x-bzip-compressed-tar', '.tar.bz2': 'application/x-bzip-compressed-tar', '.tar.gz': 'application/x-compressed-tar', '.tar.lzma': 'application/x-lzma-compressed-tar', '.tar.lzo': 'application/x-tzo', '.tar.xz': 'application/x-xz-compressed-tar', '.tar.z': 'application/x-tarz', '.tbz': 'application/x-bzip-compressed-tar', '.tbz2': 'application/x-bzip-compressed-tar', '.tcl': 'text/x-tcl', '.tex': 'text/x-tex', '.texi': 'text/x-texinfo', '.texinfo': 'text/x-texinfo', '.tga': 'image/x-tga', '.tgz': 'application/x-compressed-tar', '.theme': 'application/x-theme', '.themepack': 'application/x-windows-themepack', '.tif': 'image/tiff', '.tiff': 'image/tiff', '.tk': 'text/x-tcl', '.tlz': 'application/x-lzma-compressed-tar', '.tnef': 'application/vnd.ms-tnef', '.tnf': 'application/vnd.ms-tnef', '.toc': 'application/x-cdrdao-toc', '.torrent': 'application/x-bittorrent', '.tpic': 'image/x-tga', '.tr': 'text/troff', '.ts': 'application/x-linguist', '.tsv': 'text/tab-separated-values', '.tta': 'audio/x-tta', '.ttc': 'application/x-font-ttf', '.ttf': 'application/x-font-ttf', '.ttx': 'application/x-font-ttx', '.txt': 'text/plain', '.txz': 'application/x-xz-compressed-tar', '.tzo': 'application/x-tzo', '.ufraw': 'application/x-ufraw', '.ui': 'application/x-designer', '.uil': 'text/x-uil', '.ult': 'audio/x-mod', '.uni': 'audio/x-mod', '.uri': 'text/x-uri', '.url': 'text/x-uri', '.ustar': 'application/x-ustar', '.vala': 'text/x-vala', '.vapi': 'text/x-vala', '.vcf': 'text/directory', '.vcs': 'text/calendar', '.vct': 'text/directory', '.vda': 'image/x-tga', '.vhd': 'text/x-vhdl', '.vhdl': 'text/x-vhdl', '.viv': 'video/vivo', '.vivo': 'video/vivo', '.vlc': 'audio/x-mpegurl', '.vob': 'video/mpeg', '.voc': 'audio/x-voc', '.vor': 'application/vnd.stardivision.writer', '.vst': 'image/x-tga', '.wav': 'audio/x-wav', '.wax': 'audio/x-ms-asx', '.wb1': 'application/x-quattropro', '.wb2': 'application/x-quattropro', '.wb3': 'application/x-quattropro', '.wbmp': 'image/vnd.wap.wbmp', '.wcm': 'application/vnd.ms-works', '.wdb': 'application/vnd.ms-works', '.wk1': 'application/vnd.lotus-1-2-3', '.wk3': 'application/vnd.lotus-1-2-3', '.wk4': 'application/vnd.lotus-1-2-3', '.wks': 'application/vnd.ms-works', '.wma': 'audio/x-ms-wma', '.wmf': 'image/x-wmf', '.wml': 'text/vnd.wap.wml', '.wmls': 'text/vnd.wap.wmlscript', '.wmv': 'video/x-ms-wmv', '.wmx': 'audio/x-ms-asx', '.wp': 'application/vnd.wordperfect', '.wp4': 'application/vnd.wordperfect', '.wp5': 'application/vnd.wordperfect', '.wp6': 'application/vnd.wordperfect', '.wpd': 'application/vnd.wordperfect', '.wpg': 'application/x-wpg', '.wpl': 'application/vnd.ms-wpl', '.wpp': 'application/vnd.wordperfect', '.wps': 'application/vnd.ms-works', '.wri': 'application/x-mswrite', '.wrl': 'model/vrml', '.wv': 'audio/x-wavpack', '.wvc': 'audio/x-wavpack-correction', '.wvp': 'audio/x-wavpack', '.wvx': 'audio/x-ms-asx', '.x3f': 'image/x-sigma-x3f', '.xac': 'application/x-gnucash', '.xbel': 'application/x-xbel', '.xbl': 'application/xml', '.xbm': 'image/x-xbitmap', '.xcf': 'image/x-xcf', '.xcf.bz2': 'image/x-compressed-xcf', '.xcf.gz': 'image/x-compressed-xcf', '.xhtml': 'application/xhtml+xml', '.xi': 'audio/x-xi', '.xla': 'application/vnd.ms-excel', '.xlc': 'application/vnd.ms-excel', '.xld': 'application/vnd.ms-excel', '.xlf': 'application/x-xliff', '.xliff': 'application/x-xliff', '.xll': 'application/vnd.ms-excel', '.xlm': 'application/vnd.ms-excel', '.xls': 'application/vnd.ms-excel', '.xlsm': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', '.xlt': 'application/vnd.ms-excel', '.xlw': 'application/vnd.ms-excel', '.xm': 'audio/x-xm', '.xmf': 'audio/x-xmf', '.xmi': 'text/x-xmi', '.xml': 'application/xml', '.xpm': 'image/x-xpixmap', '.xps': 'application/vnd.ms-xpsdocument', '.xsl': 'application/xml', '.xslfo': 'text/x-xslfo', '.xslt': 'application/xml', '.xspf': 'application/xspf+xml', '.xul': 'application/vnd.mozilla.xul+xml', '.xwd': 'image/x-xwindowdump', '.xyz': 'chemical/x-pdb', '.xz': 'application/x-xz', '.w2p': 'application/w2p', '.z': 'application/x-compress', '.zabw': 'application/x-abiword', '.zip': 'application/zip', '.zoo': 'application/x-zoo', } def contenttype(filename, default='text/plain'): """ Returns the Content-Type string matching extension of the given filename. """ i = filename.rfind('.') if i>=0: default = CONTENT_TYPE.get(filename[i:].lower(),default) j = filename.rfind('.', 0, i) if j>=0: default = CONTENT_TYPE.get(filename[j:].lower(),default) if default.startswith('text/'): default += '; charset=utf-8' return default
Python
#!/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) gluon.rewrite parses incoming URLs and formats outgoing URLs for gluon.html.URL. In addition, it rewrites both incoming and outgoing URLs based on the (optional) user-supplied routes.py, which also allows for rewriting of certain error messages. routes.py supports two styles of URL rewriting, depending on whether 'routers' is defined. Refer to router.example.py and routes.example.py for additional documentation. """ import os import re import logging import traceback import threading import urllib from storage import Storage, List from http import HTTP from fileutils import abspath, read_file from settings import global_settings logger = logging.getLogger('web2py.rewrite') thread = threading.local() # thread-local storage for routing parameters def _router_default(): "return new copy of default base router" router = Storage( default_application = 'init', applications = 'ALL', default_controller = 'default', controllers = 'DEFAULT', default_function = 'index', functions = None, default_language = None, languages = None, root_static = ['favicon.ico', 'robots.txt'], domains = None, exclusive_domain = False, map_hyphen = False, acfe_match = r'\w+$', # legal app/ctlr/fcn/ext file_match = r'(\w+[-=./]?)+$', # legal file (path) name args_match = r'([\w@ -]+[=.]?)*$', # legal arg in args ) return router def _params_default(app=None): "return new copy of default parameters" p = Storage() p.name = app or "BASE" p.default_application = app or "init" p.default_controller = "default" p.default_function = "index" p.routes_app = [] p.routes_in = [] p.routes_out = [] p.routes_onerror = [] p.routes_apps_raw = [] p.error_handler = None p.error_message = '<html><body><h1>%s</h1></body></html>' p.error_message_ticket = \ '<html><body><h1>Internal error</h1>Ticket issued: <a href="/admin/default/ticket/%(ticket)s" target="_blank">%(ticket)s</a></body><!-- this is junk text else IE does not display the page: '+('x'*512)+' //--></html>' p.routers = None return p params_apps = dict() params = _params_default(app=None) # regex rewrite parameters thread.routes = params # default to base regex rewrite parameters routers = None ROUTER_KEYS = set(('default_application', 'applications', 'default_controller', 'controllers', 'default_function', 'functions', 'default_language', 'languages', 'domain', 'domains', 'root_static', 'path_prefix', 'exclusive_domain', 'map_hyphen', 'map_static', 'acfe_match', 'file_match', 'args_match')) ROUTER_BASE_KEYS = set(('applications', 'default_application', 'domains', 'path_prefix')) # The external interface to rewrite consists of: # # load: load routing configuration file(s) # url_in: parse and rewrite incoming URL # url_out: assemble and rewrite outgoing URL # # thread.routes.default_application # thread.routes.error_message # thread.routes.error_message_ticket # thread.routes.try_redirect_on_error # thread.routes.error_handler # # filter_url: helper for doctest & unittest # filter_err: helper for doctest & unittest # regex_filter_out: doctest def url_in(request, environ): "parse and rewrite incoming URL" if routers: return map_url_in(request, environ) return regex_url_in(request, environ) def url_out(request, env, application, controller, function, args, other, scheme, host, port): "assemble and rewrite outgoing URL" if routers: acf = map_url_out(request, env, application, controller, function, args, other, scheme, host, port) url = '%s%s' % (acf, other) else: url = '/%s/%s/%s%s' % (application, controller, function, other) url = regex_filter_out(url, env) # # fill in scheme and host if absolute URL is requested # scheme can be a string, eg 'http', 'https', 'ws', 'wss' # if scheme or port is not None: if host is None: # scheme or port implies host host = True if not scheme or scheme is True: if request and request.env: scheme = request.env.get('WSGI_URL_SCHEME', 'http').lower() else: scheme = 'http' # some reasonable default in case we need it if host is not None: if host is True: host = request.env.http_host if host: if port is None: port = '' else: port = ':%s' % port url = '%s://%s%s%s' % (scheme, host, port, url) return url def try_rewrite_on_error(http_response, request, environ, ticket=None): """ called from main.wsgibase to rewrite the http response. """ status = int(str(http_response.status).split()[0]) if status>=399 and thread.routes.routes_onerror: keys=set(('%s/%s' % (request.application, status), '%s/*' % (request.application), '*/%s' % (status), '*/*')) for (key,uri) in thread.routes.routes_onerror: if key in keys: if uri == '!': # do nothing! return http_response, environ elif '?' in uri: path_info, query_string = uri.split('?',1) query_string += '&' else: path_info, query_string = uri, '' query_string += \ 'code=%s&ticket=%s&requested_uri=%s&request_url=%s' % \ (status,ticket,request.env.request_uri,request.url) if uri.startswith('http://') or uri.startswith('https://'): # make up a response url = path_info+'?'+query_string message = 'You are being redirected <a href="%s">here</a>' return HTTP(303, message % url, Location=url), environ elif path_info!=environ['PATH_INFO']: # rewrite request, call wsgibase recursively, avoid loop environ['PATH_INFO'] = path_info environ['QUERY_STRING'] = query_string return None, environ # do nothing! return http_response, environ def try_redirect_on_error(http_object, request, ticket=None): "called from main.wsgibase to rewrite the http response" status = int(str(http_object.status).split()[0]) if status>399 and thread.routes.routes_onerror: keys=set(('%s/%s' % (request.application, status), '%s/*' % (request.application), '*/%s' % (status), '*/*')) for (key,redir) in thread.routes.routes_onerror: if key in keys: if redir == '!': break elif '?' in redir: url = '%s&code=%s&ticket=%s&requested_uri=%s&request_url=%s' % \ (redir,status,ticket,request.env.request_uri,request.url) else: url = '%s?code=%s&ticket=%s&requested_uri=%s&request_url=%s' % \ (redir,status,ticket,request.env.request_uri,request.url) return HTTP(303, 'You are being redirected <a href="%s">here</a>' % url, Location=url) return http_object def load(routes='routes.py', app=None, data=None, rdict=None): """ load: read (if file) and parse routes store results in params (called from main.py at web2py initialization time) If data is present, it's used instead of the routes.py contents. If rdict is present, it must be a dict to be used for routers (unit test) """ global params global routers if app is None: # reinitialize global params_apps params_apps = dict() params = _params_default(app=None) # regex rewrite parameters thread.routes = params # default to base regex rewrite parameters routers = None if isinstance(rdict, dict): symbols = dict(routers=rdict) path = 'rdict' else: if data is not None: path = 'routes' else: if app is None: path = abspath(routes) else: path = abspath('applications', app, routes) if not os.path.exists(path): return data = read_file(path).replace('\r\n','\n') symbols = {} try: exec (data + '\n') in symbols except SyntaxError, e: logger.error( '%s has a syntax error and will not be loaded\n' % path + traceback.format_exc()) raise e p = _params_default(app) for sym in ('routes_app', 'routes_in', 'routes_out'): if sym in symbols: for (k, v) in symbols[sym]: p[sym].append(compile_regex(k, v)) for sym in ('routes_onerror', 'routes_apps_raw', 'error_handler','error_message', 'error_message_ticket', 'default_application','default_controller', 'default_function'): if sym in symbols: p[sym] = symbols[sym] if 'routers' in symbols: p.routers = Storage(symbols['routers']) for key in p.routers: if isinstance(p.routers[key], dict): p.routers[key] = Storage(p.routers[key]) if app is None: params = p # install base rewrite parameters thread.routes = params # install default as current routes # # create the BASE router if routers in use # routers = params.routers # establish routers if present if isinstance(routers, dict): routers = Storage(routers) if routers is not None: router = _router_default() if routers.BASE: router.update(routers.BASE) routers.BASE = router # scan each app in applications/ # create a router, if routers are in use # parse the app-specific routes.py if present # all_apps = [] for appname in [app for app in os.listdir(abspath('applications')) if not app.startswith('.')]: if os.path.isdir(abspath('applications', appname)) and \ os.path.isdir(abspath('applications', appname, 'controllers')): all_apps.append(appname) if routers: router = Storage(routers.BASE) # new copy if appname in routers: for key in routers[appname].keys(): if key in ROUTER_BASE_KEYS: raise SyntaxError, "BASE-only key '%s' in router '%s'" % (key, appname) router.update(routers[appname]) routers[appname] = router if os.path.exists(abspath('applications', appname, routes)): load(routes, appname) if routers: load_routers(all_apps) else: # app params_apps[app] = p if routers and p.routers: if app in p.routers: routers[app].update(p.routers[app]) logger.debug('URL rewrite is on. configuration in %s' % path) regex_at = re.compile(r'(?<!\\)\$[a-zA-Z]\w*') regex_anything = re.compile(r'(?<!\\)\$anything') def compile_regex(k, v): """ Preprocess and compile the regular expressions in routes_app/in/out The resulting regex will match a pattern of the form: [remote address]:[protocol]://[host]:[method] [path] We allow abbreviated regexes on input; here we try to complete them. """ k0 = k # original k for error reporting # bracket regex in ^...$ if not already done if not k[0] == '^': k = '^%s' % k if not k[-1] == '$': k = '%s$' % k # if there are no :-separated parts, prepend a catch-all for the IP address if k.find(':') < 0: # k = '^.*?:%s' % k[1:] k = '^.*?:https?://[^:/]+:[a-z]+ %s' % k[1:] # if there's no ://, provide a catch-all for the protocol, host & method if k.find('://') < 0: i = k.find(':/') if i < 0: raise SyntaxError, "routes pattern syntax error: path needs leading '/' [%s]" % k0 k = r'%s:https?://[^:/]+:[a-z]+ %s' % (k[:i], k[i+1:]) # $anything -> ?P<anything>.* for item in regex_anything.findall(k): k = k.replace(item, '(?P<anything>.*)') # $a (etc) -> ?P<a>\w+ for item in regex_at.findall(k): k = k.replace(item, r'(?P<%s>\w+)' % item[1:]) # same for replacement pattern, but with \g for item in regex_at.findall(v): v = v.replace(item, r'\g<%s>' % item[1:]) return (re.compile(k, re.DOTALL), v) def load_routers(all_apps): "load-time post-processing of routers" for app in routers.keys(): # initialize apps with routers that aren't present, on behalf of unit tests if app not in all_apps: all_apps.append(app) router = Storage(routers.BASE) # new copy if app != 'BASE': for key in routers[app].keys(): if key in ROUTER_BASE_KEYS: raise SyntaxError, "BASE-only key '%s' in router '%s'" % (key, app) router.update(routers[app]) routers[app] = router router = routers[app] for key in router.keys(): if key not in ROUTER_KEYS: raise SyntaxError, "unknown key '%s' in router '%s'" % (key, app) if not router.controllers: router.controllers = set() elif not isinstance(router.controllers, str): router.controllers = set(router.controllers) if router.functions: router.functions = set(router.functions) else: router.functions = set() if router.languages: router.languages = set(router.languages) else: router.languages = set() if app != 'BASE': for base_only in ROUTER_BASE_KEYS: router.pop(base_only, None) if 'domain' in router: routers.BASE.domains[router.domain] = app if isinstance(router.controllers, str) and router.controllers == 'DEFAULT': router.controllers = set() if os.path.isdir(abspath('applications', app)): cpath = abspath('applications', app, 'controllers') for cname in os.listdir(cpath): if os.path.isfile(abspath(cpath, cname)) and cname.endswith('.py'): router.controllers.add(cname[:-3]) if router.controllers: router.controllers.add('static') router.controllers.add(router.default_controller) if router.functions: router.functions.add(router.default_function) if isinstance(routers.BASE.applications, str) and routers.BASE.applications == 'ALL': routers.BASE.applications = list(all_apps) if routers.BASE.applications: routers.BASE.applications = set(routers.BASE.applications) else: routers.BASE.applications = set() for app in routers.keys(): # set router name router = routers[app] router.name = app # compile URL validation patterns router._acfe_match = re.compile(router.acfe_match) router._file_match = re.compile(router.file_match) if router.args_match: router._args_match = re.compile(router.args_match) # convert path_prefix to a list of path elements if router.path_prefix: if isinstance(router.path_prefix, str): router.path_prefix = router.path_prefix.strip('/').split('/') # rewrite BASE.domains as tuples # # key: 'domain[:port]' -> (domain, port) # value: 'application[/controller] -> (application, controller) # (port and controller may be None) # domains = dict() if routers.BASE.domains: for (domain, app) in [(d.strip(':'), a.strip('/')) for (d, a) in routers.BASE.domains.items()]: port = None if ':' in domain: (domain, port) = domain.split(':') ctlr = None if '/' in app: (app, ctlr) = app.split('/') if app not in all_apps and app not in routers: raise SyntaxError, "unknown app '%s' in domains" % app domains[(domain, port)] = (app, ctlr) routers.BASE.domains = domains def regex_uri(e, regexes, tag, default=None): "filter incoming URI against a list of regexes" path = e['PATH_INFO'] host = e.get('HTTP_HOST', 'localhost').lower() i = host.find(':') if i > 0: host = host[:i] key = '%s:%s://%s:%s %s' % \ (e.get('REMOTE_ADDR','localhost'), e.get('WSGI_URL_SCHEME', 'http').lower(), host, e.get('REQUEST_METHOD', 'get').lower(), path) for (regex, value) in regexes: if regex.match(key): rewritten = regex.sub(value, key) logger.debug('%s: [%s] [%s] -> %s' % (tag, key, value, rewritten)) return rewritten logger.debug('%s: [%s] -> %s (not rewritten)' % (tag, key, default)) return default def regex_select(env=None, app=None, request=None): """ select a set of regex rewrite params for the current request """ if app: thread.routes = params_apps.get(app, params) elif env and params.routes_app: if routers: map_url_in(request, env, app=True) else: app = regex_uri(env, params.routes_app, "routes_app") thread.routes = params_apps.get(app, params) else: thread.routes = params # default to base rewrite parameters logger.debug("select routing parameters: %s" % thread.routes.name) return app # for doctest def regex_filter_in(e): "regex rewrite incoming URL" query = e.get('QUERY_STRING', None) e['WEB2PY_ORIGINAL_URI'] = e['PATH_INFO'] + (query and ('?' + query) or '') if thread.routes.routes_in: path = regex_uri(e, thread.routes.routes_in, "routes_in", e['PATH_INFO']) items = path.split('?', 1) e['PATH_INFO'] = items[0] if len(items) > 1: if query: query = items[1] + '&' + query else: query = items[1] e['QUERY_STRING'] = query e['REQUEST_URI'] = e['PATH_INFO'] + (query and ('?' + query) or '') return e # pattern to replace spaces with underscore in URL # also the html escaped variants '+' and '%20' are covered regex_space = re.compile('(\+|\s|%20)+') # pattern to find valid paths in url /application/controller/... # this could be: # for static pages: # /<b:application>/static/<x:file> # for dynamic pages: # /<a:application>[/<c:controller>[/<f:function>[.<e:ext>][/<s:args>]]] # application, controller, function and ext may only contain [a-zA-Z0-9_] # file and args may also contain '-', '=', '.' and '/' # apps in routes_apps_raw must parse raw_args into args regex_static = re.compile(r''' (^ # static pages /(?P<b> \w+) # b=app /static # /b/static /(?P<x> (\w[\-\=\./]?)* ) # x=file $) ''', re.X) regex_url = re.compile(r''' (^( # (/a/c/f.e/s) /(?P<a> [\w\s+]+ ) # /a=app ( # (/c.f.e/s) /(?P<c> [\w\s+]+ ) # /a/c=controller ( # (/f.e/s) /(?P<f> [\w\s+]+ ) # /a/c/f=function ( # (.e) \.(?P<e> [\w\s+]+ ) # /a/c/f.e=extension )? ( # (/s) /(?P<r> # /a/c/f.e/r=raw_args .* ) )? )? )? )? /?$) ''', re.X) regex_args = re.compile(r''' (^ (?P<s> ( [\w@/-][=.]? )* # s=args )? /?$) # trailing slash ''', re.X) def regex_url_in(request, environ): "rewrite and parse incoming URL" # ################################################## # select application # rewrite URL if routes_in is defined # update request.env # ################################################## regex_select(env=environ, request=request) if thread.routes.routes_in: environ = regex_filter_in(environ) for (key, value) in environ.items(): request.env[key.lower().replace('.', '_')] = value path = request.env.path_info.replace('\\', '/') # ################################################## # serve if a static file # ################################################## match = regex_static.match(regex_space.sub('_', path)) if match and match.group('x'): static_file = os.path.join(request.env.applications_parent, 'applications', match.group('b'), 'static', match.group('x')) return (static_file, environ) # ################################################## # parse application, controller and function # ################################################## path = re.sub('%20', ' ', path) match = regex_url.match(path) if not match or match.group('c') == 'static': raise HTTP(400, thread.routes.error_message % 'invalid request', web2py_error='invalid path') request.application = \ regex_space.sub('_', match.group('a') or thread.routes.default_application) request.controller = \ regex_space.sub('_', match.group('c') or thread.routes.default_controller) request.function = \ regex_space.sub('_', match.group('f') or thread.routes.default_function) group_e = match.group('e') request.raw_extension = group_e and regex_space.sub('_', group_e) or None request.extension = request.raw_extension or 'html' request.raw_args = match.group('r') request.args = List([]) if request.application in thread.routes.routes_apps_raw: # application is responsible for parsing args request.args = None elif request.raw_args: match = regex_args.match(request.raw_args.replace(' ', '_')) if match: group_s = match.group('s') request.args = \ List((group_s and group_s.split('/')) or []) if request.args and request.args[-1] == '': request.args.pop() # adjust for trailing empty arg else: raise HTTP(400, thread.routes.error_message % 'invalid request', web2py_error='invalid path (args)') return (None, environ) def regex_filter_out(url, e=None): "regex rewrite outgoing URL" if not hasattr(thread, 'routes'): regex_select() # ensure thread.routes is set (for application threads) if routers: return url # already filtered if thread.routes.routes_out: items = url.split('?', 1) if e: host = e.get('http_host', 'localhost').lower() i = host.find(':') if i > 0: host = host[:i] items[0] = '%s:%s://%s:%s %s' % \ (e.get('remote_addr', ''), e.get('wsgi_url_scheme', 'http').lower(), host, e.get('request_method', 'get').lower(), items[0]) else: items[0] = ':http://localhost:get %s' % items[0] for (regex, value) in thread.routes.routes_out: if regex.match(items[0]): rewritten = '?'.join([regex.sub(value, items[0])] + items[1:]) logger.debug('routes_out: [%s] -> %s' % (url, rewritten)) return rewritten logger.debug('routes_out: [%s] not rewritten' % url) return url def filter_url(url, method='get', remote='0.0.0.0', out=False, app=False, lang=None, domain=(None,None), env=False, scheme=None, host=None, port=None): "doctest/unittest interface to regex_filter_in() and regex_filter_out()" regex_url = re.compile(r'^(?P<scheme>http|https|HTTP|HTTPS)\://(?P<host>[^/]*)(?P<uri>.*)') match = regex_url.match(url) urlscheme = match.group('scheme').lower() urlhost = match.group('host').lower() uri = match.group('uri') k = uri.find('?') if k < 0: k = len(uri) (path_info, query_string) = (uri[:k], uri[k+1:]) path_info = urllib.unquote(path_info) # simulate server e = { 'REMOTE_ADDR': remote, 'REQUEST_METHOD': method, 'WSGI_URL_SCHEME': urlscheme, 'HTTP_HOST': urlhost, 'REQUEST_URI': uri, 'PATH_INFO': path_info, 'QUERY_STRING': query_string, #for filter_out request.env use lowercase 'remote_addr': remote, 'request_method': method, 'wsgi_url_scheme': urlscheme, 'http_host': urlhost } request = Storage() e["applications_parent"] = global_settings.applications_parent request.env = Storage(e) request.uri_language = lang # determine application only # if app: if routers: return map_url_in(request, e, app=True) return regex_select(e) # rewrite outbound URL # if out: (request.env.domain_application, request.env.domain_controller) = domain items = path_info.lstrip('/').split('/') if items[-1] == '': items.pop() # adjust trailing empty args assert len(items) >= 3, "at least /a/c/f is required" a = items.pop(0) c = items.pop(0) f = items.pop(0) if not routers: return regex_filter_out(uri, e) acf = map_url_out(request, None, a, c, f, items, None, scheme, host, port) if items: url = '%s/%s' % (acf, '/'.join(items)) if items[-1] == '': url += '/' else: url = acf if query_string: url += '?' + query_string return url # rewrite inbound URL # (static, e) = url_in(request, e) if static: return static result = "/%s/%s/%s" % (request.application, request.controller, request.function) if request.extension and request.extension != 'html': result += ".%s" % request.extension if request.args: result += " %s" % request.args if e['QUERY_STRING']: result += " ?%s" % e['QUERY_STRING'] if request.uri_language: result += " (%s)" % request.uri_language if env: return request.env return result def filter_err(status, application='app', ticket='tkt'): "doctest/unittest interface to routes_onerror" if status > 399 and thread.routes.routes_onerror: keys = set(('%s/%s' % (application, status), '%s/*' % (application), '*/%s' % (status), '*/*')) for (key,redir) in thread.routes.routes_onerror: if key in keys: if redir == '!': break elif '?' in redir: url = redir + '&' + 'code=%s&ticket=%s' % (status,ticket) else: url = redir + '?' + 'code=%s&ticket=%s' % (status,ticket) return url # redirection return status # no action # router support # class MapUrlIn(object): "logic for mapping incoming URLs" def __init__(self, request=None, env=None): "initialize a map-in object" self.request = request self.env = env self.router = None self.application = None self.language = None self.controller = None self.function = None self.extension = 'html' self.controllers = set() self.functions = set() self.languages = set() self.default_language = None self.map_hyphen = False self.exclusive_domain = False path = self.env['PATH_INFO'] self.query = self.env.get('QUERY_STRING', None) path = path.lstrip('/') self.env['PATH_INFO'] = '/' + path self.env['WEB2PY_ORIGINAL_URI'] = self.env['PATH_INFO'] + (self.query and ('?' + self.query) or '') # to handle empty args, strip exactly one trailing slash, if present # .../arg1// represents one trailing empty arg # if path.endswith('/'): path = path[:-1] self.args = List(path and path.split('/') or []) # see http://www.python.org/dev/peps/pep-3333/#url-reconstruction for URL composition self.remote_addr = self.env.get('REMOTE_ADDR','localhost') self.scheme = self.env.get('WSGI_URL_SCHEME', 'http').lower() self.method = self.env.get('REQUEST_METHOD', 'get').lower() self.host = self.env.get('HTTP_HOST') self.port = None if not self.host: self.host = self.env.get('SERVER_NAME') self.port = self.env.get('SERVER_PORT') if not self.host: self.host = 'localhost' self.port = '80' if ':' in self.host: (self.host, self.port) = self.host.split(':') if not self.port: if self.scheme == 'https': self.port = '443' else: self.port = '80' def map_prefix(self): "strip path prefix, if present in its entirety" prefix = routers.BASE.path_prefix if prefix: prefixlen = len(prefix) if prefixlen > len(self.args): return for i in xrange(prefixlen): if prefix[i] != self.args[i]: return # prefix didn't match self.args = List(self.args[prefixlen:]) # strip the prefix def map_app(self): "determine application name" base = routers.BASE # base router self.domain_application = None self.domain_controller = None arg0 = self.harg0 if base.applications and arg0 in base.applications: self.application = arg0 elif (self.host, self.port) in base.domains: (self.application, self.domain_controller) = base.domains[(self.host, self.port)] self.env['domain_application'] = self.application self.env['domain_controller'] = self.domain_controller elif (self.host, None) in base.domains: (self.application, self.domain_controller) = base.domains[(self.host, None)] self.env['domain_application'] = self.application self.env['domain_controller'] = self.domain_controller elif arg0 and not base.applications: self.application = arg0 else: self.application = base.default_application or '' self.pop_arg_if(self.application == arg0) if not base._acfe_match.match(self.application): raise HTTP(400, thread.routes.error_message % 'invalid request', web2py_error="invalid application: '%s'" % self.application) if self.application not in routers and \ (self.application != thread.routes.default_application or self.application == 'welcome'): raise HTTP(400, thread.routes.error_message % 'invalid request', web2py_error="unknown application: '%s'" % self.application) # set the application router # logger.debug("select application=%s" % self.application) self.request.application = self.application if self.application not in routers: self.router = routers.BASE # support gluon.main.wsgibase init->welcome else: self.router = routers[self.application] # application router self.controllers = self.router.controllers self.default_controller = self.domain_controller or self.router.default_controller self.functions = self.router.functions self.languages = self.router.languages self.default_language = self.router.default_language self.map_hyphen = self.router.map_hyphen self.exclusive_domain = self.router.exclusive_domain self._acfe_match = self.router._acfe_match self._file_match = self.router._file_match self._args_match = self.router._args_match def map_root_static(self): ''' handle root-static files (no hyphen mapping) a root-static file is one whose incoming URL expects it to be at the root, typically robots.txt & favicon.ico ''' if len(self.args) == 1 and self.arg0 in self.router.root_static: self.controller = self.request.controller = 'static' root_static_file = os.path.join(self.request.env.applications_parent, 'applications', self.application, self.controller, self.arg0) logger.debug("route: root static=%s" % root_static_file) return root_static_file return None def map_language(self): "handle language (no hyphen mapping)" arg0 = self.arg0 # no hyphen mapping if arg0 and self.languages and arg0 in self.languages: self.language = arg0 else: self.language = self.default_language if self.language: logger.debug("route: language=%s" % self.language) self.pop_arg_if(self.language == arg0) arg0 = self.arg0 def map_controller(self): "identify controller" # handle controller # arg0 = self.harg0 # map hyphens if not arg0 or (self.controllers and arg0 not in self.controllers): self.controller = self.default_controller or '' else: self.controller = arg0 self.pop_arg_if(arg0 == self.controller) logger.debug("route: controller=%s" % self.controller) if not self.router._acfe_match.match(self.controller): raise HTTP(400, thread.routes.error_message % 'invalid request', web2py_error='invalid controller') def map_static(self): ''' handle static files file_match but no hyphen mapping ''' if self.controller != 'static': return None file = '/'.join(self.args) if not self.router._file_match.match(file): raise HTTP(400, thread.routes.error_message % 'invalid request', web2py_error='invalid static file') # # support language-specific static subdirectories, # eg /appname/en/static/filename => applications/appname/static/en/filename # if language-specific file doesn't exist, try same file in static # if self.language: static_file = os.path.join(self.request.env.applications_parent, 'applications', self.application, 'static', self.language, file) if not self.language or not os.path.isfile(static_file): static_file = os.path.join(self.request.env.applications_parent, 'applications', self.application, 'static', file) logger.debug("route: static=%s" % static_file) return static_file def map_function(self): "handle function.extension" arg0 = self.harg0 # map hyphens if not arg0 or self.functions and arg0 not in self.functions and self.controller == self.default_controller: self.function = self.router.default_function or "" self.pop_arg_if(arg0 and self.function == arg0) else: func_ext = arg0.split('.') if len(func_ext) > 1: self.function = func_ext[0] self.extension = func_ext[-1] else: self.function = arg0 self.pop_arg_if(True) logger.debug("route: function.ext=%s.%s" % (self.function, self.extension)) if not self.router._acfe_match.match(self.function): raise HTTP(400, thread.routes.error_message % 'invalid request', web2py_error='invalid function') if self.extension and not self.router._acfe_match.match(self.extension): raise HTTP(400, thread.routes.error_message % 'invalid request', web2py_error='invalid extension') def validate_args(self): ''' check args against validation pattern ''' for arg in self.args: if not self.router._args_match.match(arg): raise HTTP(400, thread.routes.error_message % 'invalid request', web2py_error='invalid arg <%s>' % arg) def update_request(self): ''' update request from self build env.request_uri make lower-case versions of http headers in env ''' self.request.application = self.application self.request.controller = self.controller self.request.function = self.function self.request.extension = self.extension self.request.args = self.args if self.language: self.request.uri_language = self.language uri = '/%s/%s/%s' % (self.application, self.controller, self.function) if self.map_hyphen: uri = uri.replace('_', '-') if self.extension != 'html': uri += '.' + self.extension if self.language: uri = '/%s%s' % (self.language, uri) uri += self.args and urllib.quote('/' + '/'.join([str(x) for x in self.args])) or '' uri += (self.query and ('?' + self.query) or '') self.env['REQUEST_URI'] = uri for (key, value) in self.env.items(): self.request.env[key.lower().replace('.', '_')] = value @property def arg0(self): "return first arg" return self.args(0) @property def harg0(self): "return first arg with optional hyphen mapping" if self.map_hyphen and self.args(0): return self.args(0).replace('-', '_') return self.args(0) def pop_arg_if(self, dopop): "conditionally remove first arg and return new first arg" if dopop: self.args.pop(0) class MapUrlOut(object): "logic for mapping outgoing URLs" def __init__(self, request, env, application, controller, function, args, other, scheme, host, port): "initialize a map-out object" self.default_application = routers.BASE.default_application if application in routers: self.router = routers[application] else: self.router = routers.BASE self.request = request self.env = env self.application = application self.controller = controller self.function = function self.args = args self.other = other self.scheme = scheme self.host = host self.port = port self.applications = routers.BASE.applications self.controllers = self.router.controllers self.functions = self.router.functions self.languages = self.router.languages self.default_language = self.router.default_language self.exclusive_domain = self.router.exclusive_domain self.map_hyphen = self.router.map_hyphen self.map_static = self.router.map_static self.path_prefix = routers.BASE.path_prefix self.domain_application = request and self.request.env.domain_application self.domain_controller = request and self.request.env.domain_controller self.default_function = self.router.default_function if (self.router.exclusive_domain and self.domain_application and self.domain_application != self.application and not self.host): raise SyntaxError, 'cross-domain conflict: must specify host' lang = request and request.uri_language if lang and self.languages and lang in self.languages: self.language = lang else: self.language = None self.omit_application = False self.omit_language = False self.omit_controller = False self.omit_function = False def omit_lang(self): "omit language if possible" if not self.language or self.language == self.default_language: self.omit_language = True def omit_acf(self): "omit what we can of a/c/f" router = self.router # Handle the easy no-args case of tail-defaults: /a/c /a / # if not self.args and self.function == router.default_function: self.omit_function = True if self.controller == router.default_controller: self.omit_controller = True if self.application == self.default_application: self.omit_application = True # omit default application # (which might be the domain default application) # default_application = self.domain_application or self.default_application if self.application == default_application: self.omit_application = True # omit controller if default controller # default_controller = ((self.application == self.domain_application) and self.domain_controller) or router.default_controller or '' if self.controller == default_controller: self.omit_controller = True # omit function if default controller/function # if self.functions and self.function == self.default_function and self.omit_controller: self.omit_function = True # prohibit ambiguous cases # # because we presume the lang string to be unambiguous, its presence protects application omission # if self.omit_language: if not self.applications or self.controller in self.applications: self.omit_application = False if self.omit_application: if not self.applications or self.function in self.applications: self.omit_controller = False if not self.controllers or self.function in self.controllers: self.omit_controller = False if self.args: if self.args[0] in self.functions or self.args[0] in self.controllers or self.args[0] in self.applications: self.omit_function = False if self.omit_controller: if self.function in self.controllers or self.function in self.applications: self.omit_controller = False if self.omit_application: if self.controller in self.applications: self.omit_application = False # handle static as a special case # (easier for external static handling) # if self.controller == 'static' or self.controller.startswith('static/'): if not self.map_static: self.omit_application = False if self.language: self.omit_language = False self.omit_controller = False self.omit_function = False def build_acf(self): "build acf from components" acf = '' if self.map_hyphen: self.application = self.application.replace('_', '-') self.controller = self.controller.replace('_', '-') if self.controller != 'static' and not self.controller.startswith('static/'): self.function = self.function.replace('_', '-') if not self.omit_application: acf += '/' + self.application if not self.omit_language: acf += '/' + self.language if not self.omit_controller: acf += '/' + self.controller if not self.omit_function: acf += '/' + self.function if self.path_prefix: acf = '/' + '/'.join(self.path_prefix) + acf if self.args: return acf return acf or '/' def acf(self): "convert components to /app/lang/controller/function" if not routers: return None # use regex filter self.omit_lang() # try to omit language self.omit_acf() # try to omit a/c/f return self.build_acf() # build and return the /a/lang/c/f string def map_url_in(request, env, app=False): "route incoming URL" # initialize router-url object # thread.routes = params # default to base routes map = MapUrlIn(request=request, env=env) map.map_prefix() # strip prefix if present map.map_app() # determine application # configure thread.routes for error rewrite # if params.routes_app: thread.routes = params_apps.get(app, params) if app: return map.application root_static_file = map.map_root_static() # handle root-static files if root_static_file: return (root_static_file, map.env) map.map_language() map.map_controller() static_file = map.map_static() if static_file: return (static_file, map.env) map.map_function() map.validate_args() map.update_request() return (None, map.env) def map_url_out(request, env, application, controller, function, args, other, scheme, host, port): ''' supply /a/c/f (or /a/lang/c/f) portion of outgoing url The basic rule is that we can only make transformations that map_url_in can reverse. Suppose that the incoming arguments are a,c,f,args,lang and that the router defaults are da, dc, df, dl. We can perform these transformations trivially if args=[] and lang=None or dl: /da/dc/df => / /a/dc/df => /a /a/c/df => /a/c We would also like to be able to strip the default application or application/controller from URLs with function/args present, thus: /da/c/f/args => /c/f/args /da/dc/f/args => /f/args We use [applications] and [controllers] and [functions] to suppress ambiguous omissions. We assume that language names do not collide with a/c/f names. ''' map = MapUrlOut(request, env, application, controller, function, args, other, scheme, host, port) return map.acf() def get_effective_router(appname): "return a private copy of the effective router for the specified application" if not routers or appname not in routers: return None return Storage(routers[appname]) # return a copy
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) """ from SimpleXMLRPCServer import SimpleXMLRPCDispatcher def handler(request, response, methods): response.session_id = None # no sessions for xmlrpc dispatcher = SimpleXMLRPCDispatcher(allow_none=True, encoding=None) for method in methods: dispatcher.register_function(method) dispatcher.register_introspection_functions() response.headers['Content-Type'] = 'text/xml' dispatch = getattr(dispatcher, '_dispatch', None) return dispatcher._marshaled_dispatch(request.body.read(), dispatch)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu> and Limodou <limodou@gmail.com>. License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) This makes uses of the pywin32 package (http://sourceforge.net/projects/pywin32/). You do not need to install this package to use web2py. """ import time import os import sys import traceback try: import win32serviceutil import win32service import win32event except: if os.name == 'nt': print "Warning, winservice is unable to install the Mark Hammond Win32 extensions" import servicemanager import _winreg from fileutils import up __all__ = ['web2py_windows_service_handler'] class Service(win32serviceutil.ServiceFramework): _svc_name_ = '_unNamed' _svc_display_name_ = '_Service Template' def __init__(self, *args): win32serviceutil.ServiceFramework.__init__(self, *args) self.stop_event = win32event.CreateEvent(None, 0, 0, None) def log(self, msg): servicemanager.LogInfoMsg(str(msg)) def SvcDoRun(self): self.ReportServiceStatus(win32service.SERVICE_START_PENDING) try: self.ReportServiceStatus(win32service.SERVICE_RUNNING) self.start() win32event.WaitForSingleObject(self.stop_event, win32event.INFINITE) except: self.log(traceback.format_exc(sys.exc_info)) self.SvcStop() self.ReportServiceStatus(win32service.SERVICE_STOPPED) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) try: self.stop() except: self.log(traceback.format_exc(sys.exc_info)) win32event.SetEvent(self.stop_event) self.ReportServiceStatus(win32service.SERVICE_STOPPED) # to be overridden def start(self): pass # to be overridden def stop(self): pass class Web2pyService(Service): _svc_name_ = 'web2py' _svc_display_name_ = 'web2py Service' _exe_args_ = 'options' server = None def chdir(self): try: h = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'SYSTEM\CurrentControlSet\Services\%s' % self._svc_name_) try: cls = _winreg.QueryValue(h, 'PythonClass') finally: _winreg.CloseKey(h) dir = os.path.dirname(cls) os.chdir(dir) return True except: self.log("Can't change to web2py working path; server is stopped") return False def start(self): self.log('web2py server starting') if not self.chdir(): return if len(sys.argv) == 2: opt_mod = sys.argv[1] else: opt_mod = self._exe_args_ options = __import__(opt_mod, [], [], '') if True: # legacy support for old options files, which have only (deprecated) numthreads if hasattr(options, 'numthreads') and not hasattr(options, 'minthreads'): options.minthreads = options.numthreads if not hasattr(options, 'minthreads'): options.minthreads = None if not hasattr(options, 'maxthreads'): options.maxthreads = None import main self.server = main.HttpServer( ip=options.ip, port=options.port, password=options.password, pid_filename=options.pid_filename, log_filename=options.log_filename, profiler_filename=options.profiler_filename, ssl_certificate=options.ssl_certificate, ssl_private_key=options.ssl_private_key, min_threads=options.minthreads, max_threads=options.maxthreads, server_name=options.server_name, request_queue_size=options.request_queue_size, timeout=options.timeout, shutdown_timeout=options.shutdown_timeout, path=options.folder ) try: self.server.start() except: # self.server.stop() self.server = None raise def stop(self): self.log('web2py server stopping') if not self.chdir(): return if self.server: self.server.stop() time.sleep(1) def web2py_windows_service_handler(argv=None, opt_file='options'): path = os.path.dirname(__file__) classstring = os.path.normpath(os.path.join(up(path), 'gluon.winservice.Web2pyService')) if opt_file: Web2pyService._exe_args_ = opt_file win32serviceutil.HandleCommandLine(Web2pyService, serviceClassString=classstring, argv=['', 'install']) win32serviceutil.HandleCommandLine(Web2pyService, serviceClassString=classstring, argv=argv) if __name__ == '__main__': web2py_windows_service_handler()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) """ import cgi import os import re import copy import types import urllib import base64 import sanitizer import rewrite import itertools import decoder import copy_reg import cPickle import marshal from HTMLParser import HTMLParser from htmlentitydefs import name2codepoint from contrib.markmin.markmin2html import render from storage import Storage from highlight import highlight from utils import web2py_uuid, hmac_hash import hmac import hashlib regex_crlf = re.compile('\r|\n') join = ''.join __all__ = [ 'A', 'B', 'BEAUTIFY', 'BODY', 'BR', 'BUTTON', 'CENTER', 'CAT', 'CODE', 'DIV', 'EM', 'EMBED', 'FIELDSET', 'FORM', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'HEAD', 'HR', 'HTML', 'I', 'IFRAME', 'IMG', 'INPUT', 'LABEL', 'LEGEND', 'LI', 'LINK', 'OL', 'UL', 'MARKMIN', 'MENU', 'META', 'OBJECT', 'ON', 'OPTION', 'P', 'PRE', 'SCRIPT', 'OPTGROUP', 'SELECT', 'SPAN', 'STYLE', 'TABLE', 'TAG', 'TD', 'TEXTAREA', 'TH', 'THEAD', 'TBODY', 'TFOOT', 'TITLE', 'TR', 'TT', 'URL', 'XHTML', 'XML', 'xmlescape', 'embed64', ] def xmlescape(data, quote = True): """ returns an escaped string of the provided data :param data: the data to be escaped :param quote: optional (default False) """ # first try the xml function if hasattr(data,'xml') and callable(data.xml): return data.xml() # otherwise, make it a string if not isinstance(data, (str, unicode)): data = str(data) elif isinstance(data, unicode): data = data.encode('utf8', 'xmlcharrefreplace') # ... and do the escaping data = cgi.escape(data, quote).replace("'","&#x27;") return data def URL( a=None, c=None, f=None, r=None, args=[], vars={}, anchor='', extension=None, env=None, hmac_key=None, hash_vars=True, salt=None, user_signature=None, scheme=None, host=None, port=None, ): """ generate a URL example:: >>> str(URL(a='a', c='c', f='f', args=['x', 'y', 'z'], ... vars={'p':1, 'q':2}, anchor='1')) '/a/c/f/x/y/z?p=1&q=2#1' >>> str(URL(a='a', c='c', f='f', args=['x', 'y', 'z'], ... vars={'p':(1,3), 'q':2}, anchor='1')) '/a/c/f/x/y/z?p=1&p=3&q=2#1' >>> str(URL(a='a', c='c', f='f', args=['x', 'y', 'z'], ... vars={'p':(3,1), 'q':2}, anchor='1')) '/a/c/f/x/y/z?p=3&p=1&q=2#1' >>> str(URL(a='a', c='c', f='f', anchor='1+2')) '/a/c/f#1%2B2' >>> str(URL(a='a', c='c', f='f', args=['x', 'y', 'z'], ... vars={'p':(1,3), 'q':2}, anchor='1', hmac_key='key')) '/a/c/f/x/y/z?p=1&p=3&q=2&_signature=5d06bb8a4a6093dd325da2ee591c35c61afbd3c6#1' generates a url '/a/c/f' corresponding to application a, controller c and function f. If r=request is passed, a, c, f are set, respectively, to r.application, r.controller, r.function. The more typical usage is: URL(r=request, f='index') that generates a url for the index function within the present application and controller. :param a: application (default to current if r is given) :param c: controller (default to current if r is given) :param f: function (default to current if r is given) :param r: request (optional) :param args: any arguments (optional) :param vars: any variables (optional) :param anchor: anchorname, without # (optional) :param hmac_key: key to use when generating hmac signature (optional) :param hash_vars: which of the vars to include in our hmac signature True (default) - hash all vars, False - hash none of the vars, iterable - hash only the included vars ['key1','key2'] :param scheme: URI scheme (True, 'http' or 'https', etc); forces absolute URL (optional) :param host: string to force absolute URL with host (True means http_host) :param port: optional port number (forces absolute URL) :raises SyntaxError: when no application, controller or function is available :raises SyntaxError: when a CRLF is found in the generated url """ if args in (None,[]): args = [] vars = vars or {} application = None controller = None function = None if not r: if a and not c and not f: (f,a,c)=(a,c,f) elif a and c and not f: (c,f,a)=(a,c,f) from globals import current if hasattr(current,'request'): r = current.request if r: application = r.application controller = r.controller function = r.function env = r.env if extension is None and r.extension != 'html': extension = r.extension if a: application = a if c: controller = c if f: if not isinstance(f, str): function = f.__name__ elif '.' in f: function, extension = f.split('.', 1) else: function = f function2 = '%s.%s' % (function,extension or 'html') if not (application and controller and function): raise SyntaxError, 'not enough information to build the url' if not isinstance(args, (list, tuple)): args = [args] other = args and urllib.quote('/' + '/'.join([str(x) for x in args])) or '' if other.endswith('/'): other += '/' # add trailing slash to make last trailing empty arg explicit if vars.has_key('_signature'): vars.pop('_signature') list_vars = [] for (key, vals) in sorted(vars.items()): if not isinstance(vals, (list, tuple)): vals = [vals] for val in vals: list_vars.append((key, val)) if user_signature: from globals import current if current.session.auth: hmac_key = current.session.auth.hmac_key if hmac_key: # generate an hmac signature of the vars & args so can later # verify the user hasn't messed with anything h_args = '/%s/%s/%s%s' % (application, controller, function2, other) # how many of the vars should we include in our hash? if hash_vars is True: # include them all h_vars = list_vars elif hash_vars is False: # include none of them h_vars = '' else: # include just those specified if hash_vars and not isinstance(hash_vars, (list, tuple)): hash_vars = [hash_vars] h_vars = [(k, v) for (k, v) in list_vars if k in hash_vars] # re-assembling the same way during hash authentication message = h_args + '?' + urllib.urlencode(sorted(h_vars)) sig = hmac_hash(message,hmac_key,salt=salt) # add the signature into vars list_vars.append(('_signature', sig)) if list_vars: other += '?%s' % urllib.urlencode(list_vars) if anchor: other += '#' + urllib.quote(str(anchor)) if extension: function += '.' + extension if regex_crlf.search(join([application, controller, function, other])): raise SyntaxError, 'CRLF Injection Detected' url = rewrite.url_out(r, env, application, controller, function, args, other, scheme, host, port) return url def verifyURL(request, hmac_key=None, hash_vars=True, salt=None, user_signature=None): """ Verifies that a request's args & vars have not been tampered with by the user :param request: web2py's request object :param hmac_key: the key to authenticate with, must be the same one previously used when calling URL() :param hash_vars: which vars to include in our hashing. (Optional) Only uses the 1st value currently True (or undefined) means all, False none, an iterable just the specified keys do not call directly. Use instead: URL.verify(hmac_key='...') the key has to match the one used to generate the URL. >>> r = Storage() >>> gv = Storage(p=(1,3),q=2,_signature='5d06bb8a4a6093dd325da2ee591c35c61afbd3c6') >>> r.update(dict(application='a', controller='c', function='f')) >>> r['args'] = ['x', 'y', 'z'] >>> r['get_vars'] = gv >>> verifyURL(r, 'key') True >>> verifyURL(r, 'kay') False >>> r.get_vars.p = (3, 1) >>> verifyURL(r, 'key') True >>> r.get_vars.p = (3, 2) >>> verifyURL(r, 'key') False """ if not request.get_vars.has_key('_signature'): return False # no signature in the request URL # check if user_signature requires if user_signature: from globals import current if not current.session: return False hmac_key = current.session.auth.hmac_key if not hmac_key: return False # get our sig from request.get_vars for later comparison original_sig = request.get_vars._signature # now generate a new hmac for the remaining args & vars vars, args = request.get_vars, request.args # remove the signature var since it was not part of our signed message request.get_vars.pop('_signature') # join all the args & vars into one long string # always include all of the args other = args and urllib.quote('/' + '/'.join([str(x) for x in args])) or '' h_args = '/%s/%s/%s.%s%s' % (request.application, request.controller, request.function, request.extension, other) # but only include those vars specified (allows more flexibility for use with # forms or ajax) list_vars = [] for (key, vals) in sorted(vars.items()): if not isinstance(vals, (list, tuple)): vals = [vals] for val in vals: list_vars.append((key, val)) # which of the vars are to be included? if hash_vars is True: # include them all h_vars = list_vars elif hash_vars is False: # include none of them h_vars = '' else: # include just those specified # wrap in a try - if the desired vars have been removed it'll fail try: if hash_vars and not isinstance(hash_vars, (list, tuple)): hash_vars = [hash_vars] h_vars = [(k, v) for (k, v) in list_vars if k in hash_vars] except: # user has removed one of our vars! Immediate fail return False # build the full message string with both args & vars message = h_args + '?' + urllib.urlencode(sorted(h_vars)) # hash with the hmac_key provided sig = hmac_hash(message,str(hmac_key),salt=salt) # put _signature back in get_vars just in case a second call to URL.verify is performed # (otherwise it'll immediately return false) request.get_vars['_signature'] = original_sig # return whether or not the signature in the request matched the one we just generated # (I.E. was the message the same as the one we originally signed) return original_sig == sig URL.verify = verifyURL ON = True class XmlComponent(object): """ Abstract root for all Html components """ # TODO: move some DIV methods to here def xml(self): raise NotImplementedError class XML(XmlComponent): """ use it to wrap a string that contains XML/HTML so that it will not be escaped by the template example: >>> XML('<h1>Hello</h1>').xml() '<h1>Hello</h1>' """ def __init__( self, text, sanitize = False, permitted_tags = [ 'a', 'b', 'blockquote', 'br/', 'i', 'li', 'ol', 'ul', 'p', 'cite', 'code', 'pre', 'img/', 'h1','h2','h3','h4','h5','h6', 'table','tr','td','div', ], allowed_attributes = { 'a': ['href', 'title'], 'img': ['src', 'alt'], 'blockquote': ['type'], 'td': ['colspan'], }, ): """ :param text: the XML text :param sanitize: sanitize text using the permitted tags and allowed attributes (default False) :param permitted_tags: list of permitted tags (default: simple list of tags) :param allowed_attributes: dictionary of allowed attributed (default for A, IMG and BlockQuote). The key is the tag; the value is a list of allowed attributes. """ if sanitize: text = sanitizer.sanitize(text, permitted_tags, allowed_attributes) if isinstance(text, unicode): text = text.encode('utf8', 'xmlcharrefreplace') elif not isinstance(text, str): text = str(text) self.text = text def xml(self): return self.text def __str__(self): return self.xml() def __add__(self,other): return '%s%s' % (self,other) def __radd__(self,other): return '%s%s' % (other,self) def __cmp__(self,other): return cmp(str(self),str(other)) def __hash__(self): return hash(str(self)) def __getattr__(self,name): return getattr(str(self),name) def __getitem__(self,i): return str(self)[i] def __getslice__(self,i,j): return str(self)[i:j] def __iter__(self): for c in str(self): yield c def __len__(self): return len(str(self)) def flatten(self,render=None): """ return the text stored by the XML object rendered by the render function """ if render: return render(self.text,None,{}) return self.text def elements(self, *args, **kargs): """ to be considered experimental since the behavior of this method is questionable another options could be TAG(self.text).elements(*args,**kargs) """ return [] ### important to allow safe session.flash=T(....) def XML_unpickle(data): return marshal.loads(data) def XML_pickle(data): return XML_unpickle, (marshal.dumps(str(data)),) copy_reg.pickle(XML, XML_pickle, XML_unpickle) class DIV(XmlComponent): """ HTML helper, for easy generating and manipulating a DOM structure. Little or no validation is done. Behaves like a dictionary regarding updating of attributes. Behaves like a list regarding inserting/appending components. example:: >>> DIV('hello', 'world', _style='color:red;').xml() '<div style=\"color:red;\">helloworld</div>' all other HTML helpers are derived from DIV. _something=\"value\" attributes are transparently translated into something=\"value\" HTML attributes """ # name of the tag, subclasses should update this # tags ending with a '/' denote classes that cannot # contain components tag = 'div' def __init__(self, *components, **attributes): """ :param *components: any components that should be nested in this element :param **attributes: any attributes you want to give to this element :raises SyntaxError: when a stand alone tag receives components """ if self.tag[-1:] == '/' and components: raise SyntaxError, '<%s> tags cannot have components'\ % self.tag if len(components) == 1 and isinstance(components[0], (list,tuple)): self.components = list(components[0]) else: self.components = list(components) self.attributes = attributes self._fixup() # converts special attributes in components attributes self._postprocessing() self.parent = None for c in self.components: self._setnode(c) def update(self, **kargs): """ dictionary like updating of the tag attributes """ for (key, value) in kargs.items(): self[key] = value return self def append(self, value): """ list style appending of components >>> a=DIV() >>> a.append(SPAN('x')) >>> print a <div><span>x</span></div> """ self._setnode(value) ret = self.components.append(value) self._fixup() return ret def insert(self, i, value): """ list style inserting of components >>> a=DIV() >>> a.insert(0,SPAN('x')) >>> print a <div><span>x</span></div> """ self._setnode(value) ret = self.components.insert(i, value) self._fixup() return ret def __getitem__(self, i): """ gets attribute with name 'i' or component #i. If attribute 'i' is not found returns None :param i: index if i is a string: the name of the attribute otherwise references to number of the component """ if isinstance(i, str): try: return self.attributes[i] except KeyError: return None else: return self.components[i] def __setitem__(self, i, value): """ sets attribute with name 'i' or component #i. :param i: index if i is a string: the name of the attribute otherwise references to number of the component :param value: the new value """ self._setnode(value) if isinstance(i, (str, unicode)): self.attributes[i] = value else: self.components[i] = value def __delitem__(self, i): """ deletes attribute with name 'i' or component #i. :param i: index if i is a string: the name of the attribute otherwise references to number of the component """ if isinstance(i, str): del self.attributes[i] else: del self.components[i] def __len__(self): """ returns the number of included components """ return len(self.components) def __nonzero__(self): """ always return True """ return True def _fixup(self): """ Handling of provided components. Nothing to fixup yet. May be overridden by subclasses, eg for wrapping some components in another component or blocking them. """ return def _wrap_components(self, allowed_parents, wrap_parent = None, wrap_lambda = None): """ helper for _fixup. Checks if a component is in allowed_parents, otherwise wraps it in wrap_parent :param allowed_parents: (tuple) classes that the component should be an instance of :param wrap_parent: the class to wrap the component in, if needed :param wrap_lambda: lambda to use for wrapping, if needed """ components = [] for c in self.components: if isinstance(c, allowed_parents): pass elif wrap_lambda: c = wrap_lambda(c) else: c = wrap_parent(c) if isinstance(c,DIV): c.parent = self components.append(c) self.components = components def _postprocessing(self): """ Handling of attributes (normally the ones not prefixed with '_'). Nothing to postprocess yet. May be overridden by subclasses """ return def _traverse(self, status, hideerror=False): # TODO: docstring newstatus = status for c in self.components: if hasattr(c, '_traverse') and callable(c._traverse): c.vars = self.vars c.request_vars = self.request_vars c.errors = self.errors c.latest = self.latest c.session = self.session c.formname = self.formname c['hideerror']=hideerror newstatus = c._traverse(status,hideerror) and newstatus # for input, textarea, select, option # deal with 'value' and 'validation' name = self['_name'] if newstatus: newstatus = self._validate() self._postprocessing() elif 'old_value' in self.attributes: self['value'] = self['old_value'] self._postprocessing() elif name and name in self.vars: self['value'] = self.vars[name] self._postprocessing() if name: self.latest[name] = self['value'] return newstatus def _validate(self): """ nothing to validate yet. May be overridden by subclasses """ return True def _setnode(self,value): if isinstance(value,DIV): value.parent = self def _xml(self): """ helper for xml generation. Returns separately: - the component attributes - the generated xml of the inner components Component attributes start with an underscore ('_') and do not have a False or None value. The underscore is removed. A value of True is replaced with the attribute name. :returns: tuple: (attributes, components) """ # get the attributes for this component # (they start with '_', others may have special meanings) fa = '' for key in sorted(self.attributes): value = self[key] if key[:1] != '_': continue name = key[1:] if value is True: value = name elif value is False or value is None: continue fa += ' %s="%s"' % (name, xmlescape(value, True)) # get the xml for the inner components co = join([xmlescape(component) for component in self.components]) return (fa, co) def xml(self): """ generates the xml for this component. """ (fa, co) = self._xml() if not self.tag: return co if self.tag[-1:] == '/': # <tag [attributes] /> return '<%s%s />' % (self.tag[:-1], fa) # else: <tag [attributes]> inner components xml </tag> return '<%s%s>%s</%s>' % (self.tag, fa, co, self.tag) def __str__(self): """ str(COMPONENT) returns equals COMPONENT.xml() """ return self.xml() def flatten(self, render=None): """ return the text stored by the DIV object rendered by the render function the render function must take text, tagname, and attributes render=None is equivalent to render=lambda text, tag, attr: text >>> markdown = lambda text,tag=None,attributes={}: \ {None: re.sub('\s+',' ',text), \ 'h1':'#'+text+'\\n\\n', \ 'p':text+'\\n'}.get(tag,text) >>> a=TAG('<h1>Header</h1><p>this is a test</p>') >>> a.flatten(markdown) '#Header\\n\\nthis is a test\\n' """ text = '' for c in self.components: if isinstance(c,XmlComponent): s=c.flatten(render) elif render: s=render(str(c)) else: s=str(c) text+=s if render: text = render(text,self.tag,self.attributes) return text regex_tag=re.compile('^[\w\-\:]+') regex_id=re.compile('#([\w\-]+)') regex_class=re.compile('\.([\w\-]+)') regex_attr=re.compile('\[([\w\-\:]+)=(.*?)\]') def elements(self, *args, **kargs): """ find all component that match the supplied attribute dictionary, or None if nothing could be found All components of the components are searched. >>> a = DIV(DIV(SPAN('x'),3,DIV(SPAN('y')))) >>> for c in a.elements('span',first_only=True): c[0]='z' >>> print a <div><div><span>z</span>3<div><span>y</span></div></div></div> >>> for c in a.elements('span'): c[0]='z' >>> print a <div><div><span>z</span>3<div><span>z</span></div></div></div> It also supports a syntax compatible with jQuery >>> a=TAG('<div><span><a id="1-1" u:v=$>hello</a></span><p class="this is a test">world</p></div>') >>> for e in a.elements('div a#1-1, p.is'): print e.flatten() hello world >>> for e in a.elements('#1-1'): print e.flatten() hello >>> a.elements('a[u:v=$]')[0].xml() '<a id="1-1" u:v="$">hello</a>' >>> a=FORM( INPUT(_type='text'), SELECT(range(1)), TEXTAREA() ) >>> for c in a.elements('input, select, textarea'): c['_disabled'] = 'disabled' >>> a.xml() '<form action="" enctype="multipart/form-data" method="post"><input disabled="disabled" type="text" /><select disabled="disabled"><option value="0">0</option></select><textarea cols="40" disabled="disabled" rows="10"></textarea></form>' """ if len(args)==1: args = [a.strip() for a in args[0].split(',')] if len(args)>1: subset = [self.elements(a,**kargs) for a in args] return reduce(lambda a,b:a+b,subset,[]) elif len(args)==1: items = args[0].split() if len(items)>1: subset=[a.elements(' '.join(items[1:]),**kargs) for a in self.elements(items[0])] return reduce(lambda a,b:a+b,subset,[]) else: item=items[0] if '#' in item or '.' in item or '[' in item: match_tag = self.regex_tag.search(item) match_id = self.regex_id.search(item) match_class = self.regex_class.search(item) match_attr = self.regex_attr.finditer(item) args = [] if match_tag: args = [match_tag.group()] if match_id: kargs['_id'] = match_id.group(1) if match_class: kargs['_class'] = re.compile('(?<!\w)%s(?!\w)' % \ match_class.group(1).replace('-','\\-').replace(':','\\:')) for item in match_attr: kargs['_'+item.group(1)]=item.group(2) return self.elements(*args,**kargs) # make a copy of the components matches = [] first_only = False if kargs.has_key("first_only"): first_only = kargs["first_only"] del kargs["first_only"] # check if the component has an attribute with the same # value as provided check = True tag = getattr(self,'tag').replace("/","") if args and tag not in args: check = False for (key, value) in kargs.items(): if isinstance(value,(str,int)): if self[key] != str(value): check = False elif key in self.attributes: if not value.search(str(self[key])): check = False else: check = False if 'find' in kargs: find = kargs['find'] for c in self.components: if isinstance(find,(str,int)): if isinstance(c,str) and str(find) in c: check = True else: if isinstance(c,str) and find.search(c): check = True # if found, return the component if check: matches.append(self) if first_only: return matches # loop the copy for c in self.components: if isinstance(c, XmlComponent): kargs['first_only'] = first_only child_matches = c.elements( *args, **kargs ) if first_only and len(child_matches) != 0: return child_matches matches.extend( child_matches ) return matches def element(self, *args, **kargs): """ find the first component that matches the supplied attribute dictionary, or None if nothing could be found Also the components of the components are searched. """ kargs['first_only'] = True elements = self.elements(*args, **kargs) if not elements: # we found nothing return None return elements[0] def siblings(self,*args,**kargs): """ find all sibling components that match the supplied argument list and attribute dictionary, or None if nothing could be found """ sibs = [s for s in self.parent.components if not s == self] matches = [] first_only = False if kargs.has_key("first_only"): first_only = kargs["first_only"] del kargs["first_only"] for c in sibs: try: check = True tag = getattr(c,'tag').replace("/","") if args and tag not in args: check = False for (key, value) in kargs.items(): if c[key] != value: check = False if check: matches.append(c) if first_only: break except: pass return matches def sibling(self,*args,**kargs): """ find the first sibling component that match the supplied argument list and attribute dictionary, or None if nothing could be found """ kargs['first_only'] = True sibs = self.siblings(*args, **kargs) if not sibs: return None return sibs[0] class CAT(DIV): tag = '' def TAG_unpickler(data): return cPickle.loads(data) def TAG_pickler(data): d = DIV() d.__dict__ = data.__dict__ marshal_dump = cPickle.dumps(d) return (TAG_unpickler, (marshal_dump,)) class __TAG__(XmlComponent): """ TAG factory example:: >>> print TAG.first(TAG.second('test'), _key = 3) <first key=\"3\"><second>test</second></first> """ def __getitem__(self, name): return self.__getattr__(name) def __getattr__(self, name): if name[-1:] == '_': name = name[:-1] + '/' if isinstance(name,unicode): name = name.encode('utf-8') class __tag__(DIV): tag = name copy_reg.pickle(__tag__, TAG_pickler, TAG_unpickler) return lambda *a, **b: __tag__(*a, **b) def __call__(self,html): return web2pyHTMLParser(decoder.decoder(html)).tree TAG = __TAG__() class HTML(DIV): """ There are four predefined document type definitions. They can be specified in the 'doctype' parameter: -'strict' enables strict doctype -'transitional' enables transitional doctype (default) -'frameset' enables frameset doctype -'html5' enables HTML 5 doctype -any other string will be treated as user's own doctype 'lang' parameter specifies the language of the document. Defaults to 'en'. See also :class:`DIV` """ tag = 'html' strict = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n' transitional = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">\n' frameset = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">\n' html5 = '<!DOCTYPE HTML>\n' def xml(self): lang = self['lang'] if not lang: lang = 'en' self.attributes['_lang'] = lang doctype = self['doctype'] if doctype: if doctype == 'strict': doctype = self.strict elif doctype == 'transitional': doctype = self.transitional elif doctype == 'frameset': doctype = self.frameset elif doctype == 'html5': doctype = self.html5 else: doctype = '%s\n' % doctype else: doctype = self.transitional (fa, co) = self._xml() return '%s<%s%s>%s</%s>' % (doctype, self.tag, fa, co, self.tag) class XHTML(DIV): """ This is XHTML version of the HTML helper. There are three predefined document type definitions. They can be specified in the 'doctype' parameter: -'strict' enables strict doctype -'transitional' enables transitional doctype (default) -'frameset' enables frameset doctype -any other string will be treated as user's own doctype 'lang' parameter specifies the language of the document and the xml document. Defaults to 'en'. 'xmlns' parameter specifies the xml namespace. Defaults to 'http://www.w3.org/1999/xhtml'. See also :class:`DIV` """ tag = 'html' strict = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n' transitional = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n' frameset = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">\n' xmlns = 'http://www.w3.org/1999/xhtml' def xml(self): xmlns = self['xmlns'] if xmlns: self.attributes['_xmlns'] = xmlns else: self.attributes['_xmlns'] = self.xmlns lang = self['lang'] if not lang: lang = 'en' self.attributes['_lang'] = lang self.attributes['_xml:lang'] = lang doctype = self['doctype'] if doctype: if doctype == 'strict': doctype = self.strict elif doctype == 'transitional': doctype = self.transitional elif doctype == 'frameset': doctype = self.frameset else: doctype = '%s\n' % doctype else: doctype = self.transitional (fa, co) = self._xml() return '%s<%s%s>%s</%s>' % (doctype, self.tag, fa, co, self.tag) class HEAD(DIV): tag = 'head' class TITLE(DIV): tag = 'title' class META(DIV): tag = 'meta/' class LINK(DIV): tag = 'link/' class SCRIPT(DIV): tag = 'script' def xml(self): (fa, co) = self._xml() # no escaping of subcomponents co = '\n'.join([str(component) for component in self.components]) if co: # <script [attributes]><!--//--><![CDATA[//><!-- # script body # //--><!]]></script> # return '<%s%s><!--//--><![CDATA[//><!--\n%s\n//--><!]]></%s>' % (self.tag, fa, co, self.tag) return '<%s%s><!--\n%s\n//--></%s>' % (self.tag, fa, co, self.tag) else: return DIV.xml(self) class STYLE(DIV): tag = 'style' def xml(self): (fa, co) = self._xml() # no escaping of subcomponents co = '\n'.join([str(component) for component in self.components]) if co: # <style [attributes]><!--/*--><![CDATA[/*><!--*/ # style body # /*]]>*/--></style> return '<%s%s><!--/*--><![CDATA[/*><!--*/\n%s\n/*]]>*/--></%s>' % (self.tag, fa, co, self.tag) else: return DIV.xml(self) class IMG(DIV): tag = 'img/' class SPAN(DIV): tag = 'span' class BODY(DIV): tag = 'body' class H1(DIV): tag = 'h1' class H2(DIV): tag = 'h2' class H3(DIV): tag = 'h3' class H4(DIV): tag = 'h4' class H5(DIV): tag = 'h5' class H6(DIV): tag = 'h6' class P(DIV): """ Will replace ``\\n`` by ``<br />`` if the `cr2br` attribute is provided. see also :class:`DIV` """ tag = 'p' def xml(self): text = DIV.xml(self) if self['cr2br']: text = text.replace('\n', '<br />') return text class B(DIV): tag = 'b' class BR(DIV): tag = 'br/' class HR(DIV): tag = 'hr/' class A(DIV): tag = 'a' def xml(self): if self['callback']: self['_onclick']="ajax('%s',[],'%s');return false;" % \ (self['callback'],self['target'] or '') self['_href'] = self['_href'] or '#null' elif self['cid']: self['_onclick']='web2py_component("%s","%s");return false;' % \ (self['_href'],self['cid']) return DIV.xml(self) class BUTTON(DIV): tag = 'button' class EM(DIV): tag = 'em' class EMBED(DIV): tag = 'embed/' class TT(DIV): tag = 'tt' class PRE(DIV): tag = 'pre' class CENTER(DIV): tag = 'center' class CODE(DIV): """ displays code in HTML with syntax highlighting. :param attributes: optional attributes: - language: indicates the language, otherwise PYTHON is assumed - link: can provide a link - styles: for styles Example:: {{=CODE(\"print 'hello world'\", language='python', link=None, counter=1, styles={}, highlight_line=None)}} supported languages are \"python\", \"html_plain\", \"c\", \"cpp\", \"web2py\", \"html\". The \"html\" language interprets {{ and }} tags as \"web2py\" code, \"html_plain\" doesn't. if a link='/examples/global/vars/' is provided web2py keywords are linked to the online docs. the counter is used for line numbering, counter can be None or a prompt string. """ def xml(self): language = self['language'] or 'PYTHON' link = self['link'] counter = self.attributes.get('counter', 1) highlight_line = self.attributes.get('highlight_line', None) styles = self['styles'] or {} return highlight( join(self.components), language=language, link=link, counter=counter, styles=styles, attributes=self.attributes, highlight_line=highlight_line, ) class LABEL(DIV): tag = 'label' class LI(DIV): tag = 'li' class UL(DIV): """ UL Component. If subcomponents are not LI-components they will be wrapped in a LI see also :class:`DIV` """ tag = 'ul' def _fixup(self): self._wrap_components(LI, LI) class OL(UL): tag = 'ol' class TD(DIV): tag = 'td' class TH(DIV): tag = 'th' class TR(DIV): """ TR Component. If subcomponents are not TD/TH-components they will be wrapped in a TD see also :class:`DIV` """ tag = 'tr' def _fixup(self): self._wrap_components((TD, TH), TD) class THEAD(DIV): tag = 'thead' def _fixup(self): self._wrap_components(TR, TR) class TBODY(DIV): tag = 'tbody' def _fixup(self): self._wrap_components(TR, TR) class TFOOT(DIV): tag = 'tfoot' def _fixup(self): self._wrap_components(TR, TR) class COL(DIV): tag = 'col' class COLGROUP(DIV): tag = 'colgroup' class TABLE(DIV): """ TABLE Component. If subcomponents are not TR/TBODY/THEAD/TFOOT-components they will be wrapped in a TR see also :class:`DIV` """ tag = 'table' def _fixup(self): self._wrap_components((TR, TBODY, THEAD, TFOOT, COL, COLGROUP), TR) class I(DIV): tag = 'i' class IFRAME(DIV): tag = 'iframe' class INPUT(DIV): """ INPUT Component examples:: >>> INPUT(_type='text', _name='name', value='Max').xml() '<input name=\"name\" type=\"text\" value=\"Max\" />' >>> INPUT(_type='checkbox', _name='checkbox', value='on').xml() '<input checked=\"checked\" name=\"checkbox\" type=\"checkbox\" value=\"on\" />' >>> INPUT(_type='radio', _name='radio', _value='yes', value='yes').xml() '<input checked=\"checked\" name=\"radio\" type=\"radio\" value=\"yes\" />' >>> INPUT(_type='radio', _name='radio', _value='no', value='yes').xml() '<input name=\"radio\" type=\"radio\" value=\"no\" />' the input helper takes two special attributes value= and requires=. :param value: used to pass the initial value for the input field. value differs from _value because it works for checkboxes, radio, textarea and select/option too. - for a checkbox value should be '' or 'on'. - for a radio or select/option value should be the _value of the checked/selected item. :param requires: should be None, or a validator or a list of validators for the value of the field. """ tag = 'input/' def _validate(self): # # this only changes value, not _value name = self['_name'] if name is None or name == '': return True name = str(name) if self['_type'] != 'checkbox': self['old_value'] = self['value'] or self['_value'] or '' value = self.request_vars.get(name, '') self['value'] = value else: self['old_value'] = self['value'] or False value = self.request_vars.get(name) if isinstance(value, (tuple, list)): self['value'] = self['_value'] in value else: self['value'] = self['_value'] == value requires = self['requires'] if requires: if not isinstance(requires, (list, tuple)): requires = [requires] for validator in requires: (value, errors) = validator(value) if errors != None: self.vars[name] = value self.errors[name] = errors break if not name in self.errors: self.vars[name] = value return True return False def _postprocessing(self): t = self['_type'] if not t: t = self['_type'] = 'text' t = t.lower() value = self['value'] if self['_value'] == None: _value = None else: _value = str(self['_value']) if t == 'checkbox': if not _value: _value = self['_value'] = 'on' if not value: value = [] elif value is True: value = [_value] elif not isinstance(value,(list,tuple)): value = str(value).split('|') self['_checked'] = _value in value and 'checked' or None elif t == 'radio': if str(value) == str(_value): self['_checked'] = 'checked' else: self['_checked'] = None elif t == 'text' or t == 'hidden': if value != None: self['_value'] = value else: self['value'] = _value def xml(self): name = self.attributes.get('_name', None) if name and hasattr(self, 'errors') \ and self.errors.get(name, None) \ and self['hideerror'] != True: return DIV.xml(self) + DIV(self.errors[name], _class='error', errors=None, _id='%s__error' % name).xml() else: return DIV.xml(self) class TEXTAREA(INPUT): """ example:: TEXTAREA(_name='sometext', value='blah '*100, requires=IS_NOT_EMPTY()) 'blah blah blah ...' will be the content of the textarea field. """ tag = 'textarea' def _postprocessing(self): if not '_rows' in self.attributes: self['_rows'] = 10 if not '_cols' in self.attributes: self['_cols'] = 40 if self['value'] != None: self.components = [self['value']] elif self.components: self['value'] = self.components[0] class OPTION(DIV): tag = 'option' def _fixup(self): if not '_value' in self.attributes: self.attributes['_value'] = str(self.components[0]) class OBJECT(DIV): tag = 'object' class OPTGROUP(DIV): tag = 'optgroup' def _fixup(self): components = [] for c in self.components: if isinstance(c, OPTION): components.append(c) else: components.append(OPTION(c, _value=str(c))) self.components = components class SELECT(INPUT): """ example:: >>> from validators import IS_IN_SET >>> SELECT('yes', 'no', _name='selector', value='yes', ... requires=IS_IN_SET(['yes', 'no'])).xml() '<select name=\"selector\"><option selected=\"selected\" value=\"yes\">yes</option><option value=\"no\">no</option></select>' """ tag = 'select' def _fixup(self): components = [] for c in self.components: if isinstance(c, (OPTION, OPTGROUP)): components.append(c) else: components.append(OPTION(c, _value=str(c))) self.components = components def _postprocessing(self): component_list = [] for c in self.components: if isinstance(c, OPTGROUP): component_list.append(c.components) else: component_list.append([c]) options = itertools.chain(*component_list) value = self['value'] if value != None: if not self['_multiple']: for c in options: # my patch if value and str(c['_value'])==str(value): c['_selected'] = 'selected' else: c['_selected'] = None else: if isinstance(value,(list,tuple)): values = [str(item) for item in value] else: values = [str(value)] for c in options: # my patch if value and str(c['_value']) in values: c['_selected'] = 'selected' else: c['_selected'] = None class FIELDSET(DIV): tag = 'fieldset' class LEGEND(DIV): tag = 'legend' class FORM(DIV): """ example:: >>> from validators import IS_NOT_EMPTY >>> form=FORM(INPUT(_name=\"test\", requires=IS_NOT_EMPTY())) >>> form.xml() '<form action=\"\" enctype=\"multipart/form-data\" method=\"post\"><input name=\"test\" type=\"text\" /></form>' a FORM is container for INPUT, TEXTAREA, SELECT and other helpers form has one important method:: form.accepts(request.vars, session) if form is accepted (and all validators pass) form.vars contains the accepted vars, otherwise form.errors contains the errors. in case of errors the form is modified to present the errors to the user. """ tag = 'form' def __init__(self, *components, **attributes): DIV.__init__(self, *components, **attributes) self.vars = Storage() self.errors = Storage() self.latest = Storage() def accepts( self, vars, session=None, formname='default', keepvalues=False, onvalidation=None, hideerror=False, ): if vars.__class__.__name__ == 'Request': vars=vars.post_vars self.errors.clear() self.request_vars = Storage() self.request_vars.update(vars) self.session = session self.formname = formname self.keepvalues = keepvalues # if this tag is a form and we are in accepting mode (status=True) # check formname and formkey status = True if self.session: formkey = self.session.get('_formkey[%s]' % self.formname, None) # check if user tampering with form and void CSRF if formkey != self.request_vars._formkey: status = False if self.formname != self.request_vars._formname: status = False if status and self.session: # check if editing a record that has been modified by the server if hasattr(self,'record_hash') and self.record_hash != formkey: status = False self.record_changed = True status = self._traverse(status,hideerror) if onvalidation: if isinstance(onvalidation, dict): onsuccess = onvalidation.get('onsuccess', None) onfailure = onvalidation.get('onfailure', None) if onsuccess and status: onsuccess(self) if onfailure and vars and not status: onfailure(self) status = len(self.errors) == 0 elif status: if isinstance(onvalidation, (list, tuple)): [f(self) for f in onvalidation] else: onvalidation(self) if self.errors: status = False if session != None: if hasattr(self,'record_hash'): formkey = self.record_hash else: formkey = web2py_uuid() self.formkey = session['_formkey[%s]' % formname] = formkey if status and not keepvalues: self._traverse(False,hideerror) return status def _postprocessing(self): if not '_action' in self.attributes: self['_action'] = '' if not '_method' in self.attributes: self['_method'] = 'post' if not '_enctype' in self.attributes: self['_enctype'] = 'multipart/form-data' def hidden_fields(self): c = [] if 'hidden' in self.attributes: for (key, value) in self.attributes.get('hidden',{}).items(): c.append(INPUT(_type='hidden', _name=key, _value=value)) if hasattr(self, 'formkey') and self.formkey: c.append(INPUT(_type='hidden', _name='_formkey', _value=self.formkey)) if hasattr(self, 'formname') and self.formname: c.append(INPUT(_type='hidden', _name='_formname', _value=self.formname)) return DIV(c, _class="hidden") def xml(self): newform = FORM(*self.components, **self.attributes) hidden_fields = self.hidden_fields() if hidden_fields.components: newform.append(hidden_fields) return DIV.xml(newform) def validate(self, values=None, session=None, formname='default', keepvalues=False, onvalidation=None, hideerror=False, onsuccess='flash', onfailure='flash', message_onsuccess=None, message_onfailure=None, ): """ This function validates the form, you can use it instead of directly form.accepts. Usage: In controller def action(): form=FORM(INPUT(_name=\"test\", requires=IS_NOT_EMPTY())) form.validate() #you can pass some args here - see below return dict(form=form) This can receive a bunch of arguments onsuccess = 'flash' - will show message_onsuccess in response.flash None - will do nothing can be a function (lambda form: pass) onfailure = 'flash' - will show message_onfailure in response.flash None - will do nothing can be a function (lambda form: pass) values = values to test the validation - dictionary, response.vars, session or other - Default to (request.vars, session) message_onsuccess message_onfailure """ from gluon import current if not session: session = current.session if not values: values = current.request.post_vars message_onsuccess = message_onsuccess or current.T("Success!") message_onfailure = message_onfailure or \ current.T("Errors in form, please check it out.") if self.accepts(values, session): if onsuccess == 'flash': current.response.flash = message_onsuccess elif callable(onsuccess): onsuccess(self) return True elif self.errors: if onfailure == 'flash': current.response.flash = message_onfailure elif callable(onfailure): onfailure(self) return False def process(self, values=None, session=None, **args): """ Perform the .validate() method but returns the form Usage in controllers: # directly on return def action(): #some code here return dict(form=FORM(...).process(...)) You can use it with FORM, SQLFORM or FORM based plugins Examples: #response.flash messages def action(): form = SQLFORM(db.table).process(message_onsuccess='Sucess!') retutn dict(form=form) # callback function # callback receives True or False as first arg, and a list of args. def my_callback(status, msg): response.flash = "Success! "+msg if status else "Errors occured" # after argument can be 'flash' to response.flash messages # or a function name to use as callback or None to do nothing. def action(): return dict(form=SQLFORM(db.table).process(onsuccess=my_callback) """ self.validate(values=values, session=session, **args) return self class BEAUTIFY(DIV): """ example:: >>> BEAUTIFY(['a', 'b', {'hello': 'world'}]).xml() '<div><table><tr><td><div>a</div></td></tr><tr><td><div>b</div></td></tr><tr><td><div><table><tr><td style="font-weight:bold;">hello</td><td valign="top">:</td><td><div>world</div></td></tr></table></div></td></tr></table></div>' turns any list, dictionary, etc into decent looking html. Two special attributes are :sorted: a function that takes the dict and returned sorted keys :keyfilter: a funciton that takes a key and returns its representation or None if the key is to be skipped. By default key[:1]=='_' is skipped. """ tag = 'div' @staticmethod def no_underscore(key): if key[:1]=='_': return None return key def __init__(self, component, **attributes): self.components = [component] self.attributes = attributes sorter = attributes.get('sorted',sorted) keyfilter = attributes.get('keyfilter',BEAUTIFY.no_underscore) components = [] attributes = copy.copy(self.attributes) level = attributes['level'] = attributes.get('level',6) - 1 if '_class' in attributes: attributes['_class'] += 'i' if level == 0: return for c in self.components: if hasattr(c,'xml') and callable(c.xml): components.append(c) continue elif hasattr(c,'keys') and callable(c.keys): rows = [] try: keys = (sorter and sorter(c)) or c for key in keys: if isinstance(key,(str,unicode)) and keyfilter: filtered_key = keyfilter(key) else: filtered_key = str(key) if filtered_key is None: continue value = c[key] if type(value) == types.LambdaType: continue rows.append(TR(TD(filtered_key, _style='font-weight:bold;'), TD(':',_valign='top'), TD(BEAUTIFY(value, **attributes)))) components.append(TABLE(*rows, **attributes)) continue except: pass if isinstance(c, str): components.append(str(c)) elif isinstance(c, unicode): components.append(c.encode('utf8')) elif isinstance(c, (list, tuple)): items = [TR(TD(BEAUTIFY(item, **attributes))) for item in c] components.append(TABLE(*items, **attributes)) elif isinstance(c, cgi.FieldStorage): components.append('FieldStorage object') else: components.append(repr(c)) self.components = components class MENU(DIV): """ Used to build menus Optional arguments _class: defaults to 'web2py-menu web2py-menu-vertical' ul_class: defaults to 'web2py-menu-vertical' li_class: defaults to 'web2py-menu-expand' Example: menu = MENU([['name', False, URL(...), [submenu]], ...]) {{=menu}} """ tag = 'ul' def __init__(self, data, **args): self.data = data self.attributes = args if not '_class' in self.attributes: self['_class'] = 'web2py-menu web2py-menu-vertical' if not 'ul_class' in self.attributes: self['ul_class'] = 'web2py-menu-vertical' if not 'li_class' in self.attributes: self['li_class'] = 'web2py-menu-expand' if not 'li_active' in self.attributes: self['li_active'] = 'web2py-menu-active' def serialize(self, data, level=0): if level == 0: ul = UL(**self.attributes) else: ul = UL(_class=self['ul_class']) for item in data: (name, active, link) = item[:3] if isinstance(link,DIV): li = LI(link) elif 'no_link_url' in self.attributes and self['no_link_url']==link: li = LI(DIV(name)) elif link: li = LI(A(name, _href=link)) else: li = LI(A(name, _href='#', _onclick='javascript:void(0);return false;')) if len(item) > 3 and item[3]: li['_class'] = self['li_class'] li.append(self.serialize(item[3], level+1)) if active or ('active_url' in self.attributes and self['active_url']==link): if li['_class']: li['_class'] = li['_class']+' '+self['li_active'] else: li['_class'] = self['li_active'] ul.append(li) return ul def xml(self): return self.serialize(self.data, 0).xml() def embed64( filename = None, file = None, data = None, extension = 'image/gif', ): """ helper to encode the provided (binary) data into base64. :param filename: if provided, opens and reads this file in 'rb' mode :param file: if provided, reads this file :param data: if provided, uses the provided data """ if filename and os.path.exists(file): fp = open(filename, 'rb') data = fp.read() fp.close() data = base64.b64encode(data) return 'data:%s;base64,%s' % (extension, data) def test(): """ Example: >>> from validators import * >>> print DIV(A('click me', _href=URL(a='a', c='b', f='c')), BR(), HR(), DIV(SPAN(\"World\"), _class='unknown')).xml() <div><a href=\"/a/b/c\">click me</a><br /><hr /><div class=\"unknown\"><span>World</span></div></div> >>> print DIV(UL(\"doc\",\"cat\",\"mouse\")).xml() <div><ul><li>doc</li><li>cat</li><li>mouse</li></ul></div> >>> print DIV(UL(\"doc\", LI(\"cat\", _class='feline'), 18)).xml() <div><ul><li>doc</li><li class=\"feline\">cat</li><li>18</li></ul></div> >>> print TABLE(['a', 'b', 'c'], TR('d', 'e', 'f'), TR(TD(1), TD(2), TD(3))).xml() <table><tr><td>a</td><td>b</td><td>c</td></tr><tr><td>d</td><td>e</td><td>f</td></tr><tr><td>1</td><td>2</td><td>3</td></tr></table> >>> form=FORM(INPUT(_type='text', _name='myvar', requires=IS_EXPR('int(value)<10'))) >>> print form.xml() <form action=\"\" enctype=\"multipart/form-data\" method=\"post\"><input name=\"myvar\" type=\"text\" /></form> >>> print form.accepts({'myvar':'34'}, formname=None) False >>> print form.xml() <form action="" enctype="multipart/form-data" method="post"><input name="myvar" type="text" value="34" /><div class="error" id="myvar__error">invalid expression</div></form> >>> print form.accepts({'myvar':'4'}, formname=None, keepvalues=True) True >>> print form.xml() <form action=\"\" enctype=\"multipart/form-data\" method=\"post\"><input name=\"myvar\" type=\"text\" value=\"4\" /></form> >>> form=FORM(SELECT('cat', 'dog', _name='myvar')) >>> print form.accepts({'myvar':'dog'}, formname=None, keepvalues=True) True >>> print form.xml() <form action=\"\" enctype=\"multipart/form-data\" method=\"post\"><select name=\"myvar\"><option value=\"cat\">cat</option><option selected=\"selected\" value=\"dog\">dog</option></select></form> >>> form=FORM(INPUT(_type='text', _name='myvar', requires=IS_MATCH('^\w+$', 'only alphanumeric!'))) >>> print form.accepts({'myvar':'as df'}, formname=None) False >>> print form.xml() <form action=\"\" enctype=\"multipart/form-data\" method=\"post\"><input name=\"myvar\" type=\"text\" value=\"as df\" /><div class=\"error\" id=\"myvar__error\">only alphanumeric!</div></form> >>> session={} >>> form=FORM(INPUT(value=\"Hello World\", _name=\"var\", requires=IS_MATCH('^\w+$'))) >>> if form.accepts({}, session,formname=None): print 'passed' >>> if form.accepts({'var':'test ', '_formkey': session['_formkey[None]']}, session, formname=None): print 'passed' """ pass class web2pyHTMLParser(HTMLParser): """ obj = web2pyHTMLParser(text) parses and html/xml text into web2py helpers. obj.tree contains the root of the tree, and tree can be manipulated >>> str(web2pyHTMLParser('hello<div a="b" c=3>wor&lt;ld<span>xxx</span>y<script/>yy</div>zzz').tree) 'hello<div a="b" c="3">wor&lt;ld<span>xxx</span>y<script></script>yy</div>zzz' >>> str(web2pyHTMLParser('<div>a<span>b</div>c').tree) '<div>a<span>b</span></div>c' >>> tree = web2pyHTMLParser('hello<div a="b">world</div>').tree >>> tree.element(_a='b')['_c']=5 >>> str(tree) 'hello<div a="b" c="5">world</div>' """ def __init__(self,text,closed=('input','link')): HTMLParser.__init__(self) self.tree = self.parent = TAG['']() self.closed = closed self.tags = [x for x in __all__ if isinstance(eval(x),DIV)] self.last = None self.feed(text) def handle_starttag(self, tagname, attrs): if tagname.upper() in self.tags: tag=eval(tagname.upper()) else: if tagname in self.closed: tagname+='/' tag = TAG[tagname]() for key,value in attrs: tag['_'+key]=value tag.parent = self.parent self.parent.append(tag) if not tag.tag.endswith('/'): self.parent=tag else: self.last = tag.tag[:-1] def handle_data(self,data): try: self.parent.append(data.encode('utf8','xmlcharref')) except: self.parent.append(data.decode('latin1').encode('utf8','xmlcharref')) def handle_charref(self,name): if name[1].lower()=='x': self.parent.append(unichr(int(name[2:], 16)).encode('utf8')) else: self.parent.append(unichr(int(name[1:], 10)).encode('utf8')) def handle_entityref(self,name): self.parent.append(unichr(name2codepoint[name]).encode('utf8')) def handle_endtag(self, tagname): # this deals with unbalanced tags if tagname==self.last: return while True: try: parent_tagname=self.parent.tag self.parent = self.parent.parent except: raise RuntimeError, "unable to balance tag %s" % tagname if parent_tagname[:len(tagname)]==tagname: break def markdown_serializer(text,tag=None,attr={}): if tag is None: return re.sub('\s+',' ',text) if tag=='br': return '\n\n' if tag=='h1': return '#'+text+'\n\n' if tag=='h2': return '#'*2+text+'\n\n' if tag=='h3': return '#'*3+text+'\n\n' if tag=='h4': return '#'*4+text+'\n\n' if tag=='p': return text+'\n\n' if tag=='b' or tag=='strong': return '**%s**' % text if tag=='em' or tag=='i': return '*%s*' % text if tag=='tt' or tag=='code': return '`%s`' % text if tag=='a': return '[%s](%s)' % (text,attr.get('_href','')) if tag=='img': return '![%s](%s)' % (attr.get('_alt',''),attr.get('_src','')) return text def markmin_serializer(text,tag=None,attr={}): # if tag is None: return re.sub('\s+',' ',text) if tag=='br': return '\n\n' if tag=='h1': return '# '+text+'\n\n' if tag=='h2': return '#'*2+' '+text+'\n\n' if tag=='h3': return '#'*3+' '+text+'\n\n' if tag=='h4': return '#'*4+' '+text+'\n\n' if tag=='p': return text+'\n\n' if tag=='li': return '\n- '+text.replace('\n',' ') if tag=='tr': return text[3:].replace('\n',' ')+'\n' if tag in ['table','blockquote']: return '\n-----\n'+text+'\n------\n' if tag in ['td','th']: return ' | '+text if tag in ['b','strong','label']: return '**%s**' % text if tag in ['em','i']: return "''%s''" % text if tag in ['tt']: return '``%s``' % text.strip() if tag in ['code']: return '``\n%s``' % text if tag=='a': return '[[%s %s]]' % (text,attr.get('_href','')) if tag=='img': return '[[%s %s left]]' % (attr.get('_alt','no title'),attr.get('_src','')) return text class MARKMIN(XmlComponent): """ For documentation: http://web2py.com/examples/static/markmin.html """ def __init__(self, text, extra={}, allowed={}, sep='p'): self.text = text self.extra = extra self.allowed = allowed self.sep = sep def xml(self): """ calls the gluon.contrib.markmin render function to convert the wiki syntax """ return render(self.text,extra=self.extra,allowed=self.allowed,sep=self.sep) def __str__(self): return self.xml() def flatten(self,render=None): """ return the text stored by the MARKMIN object rendered by the render function """ return self.text def elements(self, *args, **kargs): """ to be considered experimental since the behavior of this method is questionable another options could be TAG(self.text).elements(*args,**kargs) """ return [self.text] if __name__ == '__main__': import doctest doctest.testmod()
Python
""" Extract client information from http user agent The module does not try to detect all capabilities of browser in current form (it can easily be extended though). Aim is * fast * very easy to extend * reliable enough for practical purposes * and assist python web apps to detect clients. Taken from http://pypi.python.org/pypi/httpagentparser (MIT license) Modified my Ross Peoples for web2py to better support iPhone and iPad. """ import sys from storage import Storage class DetectorsHub(dict): _known_types = ['os', 'dist', 'flavor', 'browser'] def __init__(self, *args, **kw): dict.__init__(self, *args, **kw) for typ in self._known_types: self.setdefault(typ, []) self.registerDetectors() def register(self, detector): if detector.info_type not in self._known_types: self[detector.info_type] = [detector] self._known_types.insert(detector.order, detector.info_type) else: self[detector.info_type].append(detector) def reorderByPrefs(self, detectors, prefs): if prefs is None: return [] elif prefs == []: return detectors else: prefs.insert(0, '') def key_name(d): return d.name in prefs and prefs.index(d.name) or sys.maxint return sorted(detectors, key=key_name) def __iter__(self): return iter(self._known_types) def registerDetectors(self): detectors = [v() for v in globals().values() \ if DetectorBase in getattr(v, '__mro__', [])] for d in detectors: if d.can_register: self.register(d) class DetectorBase(object): name = "" # "to perform match in DetectorsHub object" info_type = "override me" result_key = "override me" order = 10 # 0 is highest look_for = "string to look for" skip_if_found = [] # strings if present stop processin can_register = False prefs = Storage() # dict(info_type = [name1, name2], ..) version_splitters = ["/", " "] _suggested_detectors = None def __init__(self): if not self.name: self.name = self.__class__.__name__ self.can_register = (self.__class__.__dict__.get('can_register', True)) def detect(self, agent, result): if agent and self.checkWords(agent): result[self.info_type] = Storage(name=self.name) version = self.getVersion(agent) if version: result[self.info_type].version = version return True return False def checkWords(self, agent): for w in self.skip_if_found: if w in agent: return False if self.look_for: return True return False def getVersion(self, agent): # -> version string /None vs = self.version_splitters return agent.split(self.look_for + vs[0])[-1].split(vs[1])[0].strip() class OS(DetectorBase): info_type = "os" can_register = False version_splitters = [";", " "] class Dist(DetectorBase): info_type = "dist" can_register = False class Flavor(DetectorBase): info_type = "flavor" can_register = False class Browser(DetectorBase): info_type = "browser" can_register = False class Macintosh(OS): look_for = 'Macintosh' prefs = Storage(dist=None) def getVersion(self, agent): pass class Firefox(Browser): look_for = "Firefox" class Konqueror(Browser): look_for = "Konqueror" version_splitters = ["/", ";"] class Opera(Browser): look_for = "Opera" def getVersion(self, agent): return agent.split(self.look_for)[1][1:].split(' ')[0] class Netscape(Browser): look_for = "Netscape" class MSIE(Browser): look_for = "MSIE" skip_if_found = ["Opera"] name = "Microsoft Internet Explorer" version_splitters = [" ", ";"] class Galeon(Browser): look_for = "Galeon" class Safari(Browser): look_for = "Safari" def checkWords(self, agent): unless_list = ["Chrome", "OmniWeb"] if self.look_for in agent: for word in unless_list: if word in agent: return False return True def getVersion(self, agent): if "Version/" in agent: return agent.split('Version/')[-1].split(' ')[0].strip() else: # Mobile Safari return agent.split('Safari ')[-1].split(' ')[0].strip() class Linux(OS): look_for = 'Linux' prefs = Storage(browser=["Firefox"], dist=["Ubuntu", "Android"], flavor=None) def getVersion(self, agent): pass class Macintosh(OS): look_for = 'Macintosh' prefs = Storage(dist=None, flavor=['MacOS']) def getVersion(self, agent): pass class MacOS(Flavor): look_for = 'Mac OS' prefs = Storage(browser=['Firefox', 'Opera', "Microsoft Internet Explorer"]) def getVersion(self, agent): version_end_chars = [';', ')'] part = agent.split('Mac OS')[-1].strip() for c in version_end_chars: if c in part: version = part.split(c)[0] break return version.replace('_', '.') class Windows(OS): look_for = 'Windows' prefs = Storage(browser=["Microsoft Internet Explorer", 'Firefox'], dict=None, flavor=None) def getVersion(self, agent): v = agent.split('Windows')[-1].split(';')[0].strip() if ')' in v: v = v.split(')')[0] return v class Ubuntu(Dist): look_for = 'Ubuntu' version_splitters = ["/", " "] prefs = Storage(browser=['Firefox']) class Debian(Dist): look_for = 'Debian' version_splitters = ["/", " "] prefs = Storage(browser=['Firefox']) class Chrome(Browser): look_for = "Chrome" version_splitters = ["/", " "] class ChromeOS(OS): look_for = "CrOS" version_splitters = [" ", " "] prefs = Storage(browser=['Chrome']) def getVersion(self, agent): vs = self.version_splitters return agent.split(self.look_for+vs[0])[-1].split(vs[1])[1].strip()[:-1] class Android(Dist): look_for = 'Android' def getVersion(self, agent): return agent.split('Android')[-1].split(';')[0].strip() class iPhone(Dist): look_for = 'iPhone' def getVersion(self, agent): version_end_chars = ['like', ';', ')'] part = agent.split('CPU OS')[-1].strip() for c in version_end_chars: if c in part: version = 'iOS ' + part.split(c)[0].strip() break return version.replace('_', '.') class iPad(Dist): look_for = 'iPad' def getVersion(self, agent): version_end_chars = ['like', ';', ')'] part = agent.split('CPU OS')[-1].strip() for c in version_end_chars: if c in part: version = 'iOS ' + part.split(c)[0].strip() break return version.replace('_', '.') detectorshub = DetectorsHub() def detect(agent): result = Storage() prefs = Storage() _suggested_detectors = [] for info_type in detectorshub: if not _suggested_detectors: detectors = detectorshub[info_type] _d_prefs = prefs.get(info_type, []) detectors = detectorshub.reorderByPrefs(detectors, _d_prefs) if "detector" in locals(): detector._suggested_detectors = detectors else: detectors = _suggested_detectors for detector in detectors: print "detector name: ", detector.name if detector.detect(agent, result): prefs = detector.prefs _suggested_detectors = detector._suggested_detectors break return result class Result(Storage): def __missing__(self, k): return "" def detect(agent): result = Result() _suggested_detectors = [] for info_type in detectorshub: detectors = _suggested_detectors or detectorshub[info_type] for detector in detectors: if detector.detect(agent, result): if detector.prefs and not detector._suggested_detectors: _suggested_detectors = detectorshub.reorderByPrefs( detectors, detector.prefs.get(info_type)) detector._suggested_detectors = _suggested_detectors break return result def simple_detect(agent): """ -> (os, browser) # tuple of strings """ result = detect(agent) os_list = [] if 'flavor' in result: os_list.append(result['flavor']['name']) if 'dist' in result: os_list.append(result['dist']['name']) if 'os' in result: os_list.append(result['os']['name']) os = os_list and " ".join(os_list) or "Unknown OS" os_version = os_list and (result['flavor'] and result['flavor'].get( 'version')) or (result['dist'] and result['dist'].get('version')) \ or (result['os'] and result['os'].get('version')) or "" browser = 'browser' in result and result['browser']['name'] \ or 'Unknown Browser' browser_version = 'browser' in result \ and result['browser'].get('version') or "" if browser_version: browser = " ".join((browser, browser_version)) if os_version: os = " ".join((os, os_version)) return os, browser if __name__ == '__main__': import time import unittest data = ( ("Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-GB; rv:1.9.0.10) Gecko/2009042315 Firefox/3.0.10", ('MacOS Macintosh X 10.5', 'Firefox 3.0.10'), {'flavor': {'version': 'X 10.5', 'name': 'MacOS'}, 'os': {'name': 'Macintosh'}, 'browser': {'version': '3.0.10', 'name': 'Firefox'}},), ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_6) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.3 Safari/534.24,gzip(gfe)", ('MacOS Macintosh X 10.6.6', 'Chrome 11.0.696.3'), {'flavor': {'version': 'X 10.6.6', 'name': 'MacOS'}, 'os': {'name': 'Macintosh'}, 'browser': {'version': '11.0.696.3', 'name': 'Chrome'}},), ("Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2) Gecko/20100308 Ubuntu/10.04 (lucid) Firefox/3.6 GTB7.1", ('Ubuntu Linux 10.04', 'Firefox 3.6'), {'dist': {'version': '10.04', 'name': 'Ubuntu'}, 'os': {'name': 'Linux'}, 'browser': {'version': '3.6', 'name': 'Firefox'}},), ("Mozilla/5.0 (Linux; U; Android 2.2.1; fr-ch; A43 Build/FROYO) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1", ('Android Linux 2.2.1', 'Safari 4.0'), {'dist': {'version': '2.2.1', 'name': 'Android'}, 'os': {'name': 'Linux'}, 'browser': {'version': '4.0', 'name': 'Safari'}},), ("Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3", ('MacOS IPhone X', 'Safari 3.0'), {'flavor': {'version': 'X', 'name': 'MacOS'}, 'dist': {'version': 'X', 'name': 'IPhone'}, 'browser': {'version': '3.0', 'name': 'Safari'}},), ("Mozilla/5.0 (X11; CrOS i686 0.0.0) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.27 Safari/534.24,gzip(gfe)", ('ChromeOS 0.0.0', 'Chrome 11.0.696.27'), {'os': {'name': 'ChromeOS', 'version': '0.0.0'}, 'browser': {'name': 'Chrome', 'version': '11.0.696.27'}},), ("Mozilla/4.0 (compatible; MSIE 6.0; MSIE 5.5; Windows NT 5.1) Opera 7.02 [en]", ('Windows NT 5.1', 'Opera 7.02'), {'os': {'name': 'Windows', 'version': 'NT 5.1'}, 'browser': {'name': 'Opera', 'version': '7.02'}},), ("Opera/9.80 (X11; Linux i686; U; en) Presto/2.9.168 Version/11.50", ("Linux", "Opera 9.80"), {"os": {"name": "Linux"}, "browser": {"name": "Opera", "version": "9.80"}},), ("Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20060127 Netscape/8.1", ("Windows NT 5.1", "Netscape 8.1"), {'os': {'name': 'Windows', 'version': 'NT 5.1'}, 'browser': {'name': 'Netscape', 'version': '8.1'}},), ) class TestHAP(unittest.TestCase): def setUp(self): self.harass_repeat = 1000 self.data = data def test_simple_detect(self): for agent, simple_res, res in data: self.assertEqual(simple_detect(agent), simple_res) def test_detect(self): for agent, simple_res, res in data: self.assertEqual(detect(agent), res) def test_harass(self): then = time.time() for agent, simple_res, res in data * self.harass_repeat: detect(agent) time_taken = time.time() - then no_of_tests = len(self.data) * self.harass_repeat print "\nTime taken for %s detecttions: %s" \ % (no_of_tests, time_taken) print "Time taken for single detecttion: ", \ time_taken / (len(self.data) * self.harass_repeat) unittest.main()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """Universal feed parser Handles RSS 0.9x, RSS 1.0, RSS 2.0, CDF, Atom 0.3, and Atom 1.0 feeds Visit http://feedparser.org/ for the latest version Visit http://feedparser.org/docs/ for the latest documentation Required: Python 2.1 or later Recommended: Python 2.3 or later Recommended: CJKCodecs and iconv_codec <http://cjkpython.i18n.org/> """ # + "$Revision: 1.92 $"[11:15] + "-cvs" __version__ = '4.1' __license__ = \ """Copyright (c) 2002-2006, Mark Pilgrim, All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.""" __author__ = 'Mark Pilgrim <http://diveintomark.org/>' __contributors__ = ['Jason Diamond <http://injektilo.org/>', 'John Beimler <http://john.beimler.org/>', 'Fazal Majid <http://www.majid.info/mylos/weblog/>' , 'Aaron Swartz <http://aaronsw.com/>', 'Kevin Marks <http://epeus.blogspot.com/>'] _debug = 0 # HTTP "User-Agent" header to send to servers when downloading feeds. # If you are embedding feedparser in a larger application, you should # change this to your application name and URL. USER_AGENT = 'UniversalFeedParser/%s +http://feedparser.org/'\ % __version__ # HTTP "Accept" header to send to servers when downloading feeds. If you don't # want to send an Accept header, set this to None. ACCEPT_HEADER = \ 'application/atom+xml,application/rdf+xml,application/rss+xml,application/x-netcdf,application/xml;q=0.9,text/xml;q=0.2,*/*;q=0.1' # List of preferred XML parsers, by SAX driver name. These will be tried first, # but if they're not installed, Python will keep searching through its own list # of pre-installed parsers until it finds one that supports everything we need. PREFERRED_XML_PARSERS = ['drv_libxml2'] # If you want feedparser to automatically run HTML markup through HTML Tidy, set # this to 1. Requires mxTidy <http://www.egenix.com/files/python/mxTidy.html> # or utidylib <http://utidylib.berlios.de/>. TIDY_MARKUP = 0 # List of Python interfaces for HTML Tidy, in order of preference. Only useful # if TIDY_MARKUP = 1 PREFERRED_TIDY_INTERFACES = ['uTidy', 'mxTidy'] # ---------- required modules (should come with any Python distribution) ---------- import sgmllib import re import sys import copy import urlparse import time import rfc822 import types import cgi import urllib import urllib2 try: from cStringIO import StringIO as _StringIO except: from StringIO import StringIO as _StringIO # ---------- optional modules (feedparser will work without these, but with reduced functionality) ---------- # gzip is included with most Python distributions, but may not be available if you compiled your own try: import gzip except: gzip = None try: import zlib except: zlib = None # If a real XML parser is available, feedparser will attempt to use it. feedparser has # been tested with the built-in SAX parser, PyXML, and libxml2. On platforms where the # Python distribution does not come with an XML parser (such as Mac OS X 10.2 and some # versions of FreeBSD), feedparser will quietly fall back on regex-based parsing. try: import xml.sax xml.sax.make_parser(PREFERRED_XML_PARSERS) # test for valid parsers from xml.sax.saxutils import escape as _xmlescape _XML_AVAILABLE = 1 except: _XML_AVAILABLE = 0 def _xmlescape(data): data = data.replace('&', '&amp;') data = data.replace('>', '&gt;') data = data.replace('<', '&lt;') return data # base64 support for Atom feeds that contain embedded binary data try: import base64 import binascii except: base64 = binascii = None # cjkcodecs and iconv_codec provide support for more character encodings. # Both are available from http://cjkpython.i18n.org/ try: import cjkcodecs.aliases except: pass try: import iconv_codec except: pass # chardet library auto-detects character encodings # Download from http://chardet.feedparser.org/ try: import chardet if _debug: import chardet.constants chardet.constants._debug = 1 except: chardet = None # ---------- don't touch these ---------- class ThingsNobodyCaresAboutButMe(Exception): pass class CharacterEncodingOverride(ThingsNobodyCaresAboutButMe): pass class CharacterEncodingUnknown(ThingsNobodyCaresAboutButMe): pass class NonXMLContentType(ThingsNobodyCaresAboutButMe): pass class UndeclaredNamespace(Exception): pass sgmllib.tagfind = re.compile('[a-zA-Z][-_.:a-zA-Z0-9]*') sgmllib.special = re.compile('<!') sgmllib.charref = re.compile('&#(x?[0-9A-Fa-f]+)[^0-9A-Fa-f]') SUPPORTED_VERSIONS = { '': 'unknown', 'rss090': 'RSS 0.90', 'rss091n': 'RSS 0.91 (Netscape)', 'rss091u': 'RSS 0.91 (Userland)', 'rss092': 'RSS 0.92', 'rss093': 'RSS 0.93', 'rss094': 'RSS 0.94', 'rss20': 'RSS 2.0', 'rss10': 'RSS 1.0', 'rss': 'RSS (unknown version)', 'atom01': 'Atom 0.1', 'atom02': 'Atom 0.2', 'atom03': 'Atom 0.3', 'atom10': 'Atom 1.0', 'atom': 'Atom (unknown version)', 'cdf': 'CDF', 'hotrss': 'Hot RSS', } try: UserDict = dict except NameError: # Python 2.1 does not have dict from UserDict import UserDict def dict(aList): rc = {} for (k, v) in aList: rc[k] = v return rc class FeedParserDict(UserDict): keymap = { 'channel': 'feed', 'items': 'entries', 'guid': 'id', 'date': 'updated', 'date_parsed': 'updated_parsed', 'description': ['subtitle', 'summary'], 'url': ['href'], 'modified': 'updated', 'modified_parsed': 'updated_parsed', 'issued': 'published', 'issued_parsed': 'published_parsed', 'copyright': 'rights', 'copyright_detail': 'rights_detail', 'tagline': 'subtitle', 'tagline_detail': 'subtitle_detail', } def __getitem__(self, key): if key == 'category': return UserDict.__getitem__(self, 'tags')[0]['term'] if key == 'categories': return [(tag['scheme'], tag['term']) for tag in UserDict.__getitem__(self, 'tags')] realkey = self.keymap.get(key, key) if type(realkey) == types.ListType: for k in realkey: if UserDict.has_key(self, k): return UserDict.__getitem__(self, k) if UserDict.has_key(self, key): return UserDict.__getitem__(self, key) return UserDict.__getitem__(self, realkey) def __setitem__(self, key, value): for k in self.keymap.keys(): if key == k: key = self.keymap[k] if type(key) == types.ListType: key = key[0] return UserDict.__setitem__(self, key, value) def get(self, key, default=None): if self.has_key(key): return self[key] else: return default def setdefault(self, key, value): if not self.has_key(key): self[key] = value return self[key] def has_key(self, key): try: return hasattr(self, key) or UserDict.has_key(self, key) except AttributeError: return False def __getattr__(self, key): try: return self.__dict__[key] except KeyError: pass try: assert not key.startswith('_') return self.__getitem__(key) except: raise AttributeError, "object has no attribute '%s'" % key def __setattr__(self, key, value): if key.startswith('_') or key == 'data': self.__dict__[key] = value else: return self.__setitem__(key, value) def __contains__(self, key): return self.has_key(key) def zopeCompatibilityHack(): global FeedParserDict del FeedParserDict def FeedParserDict(aDict=None): rc = {} if aDict: rc.update(aDict) return rc _ebcdic_to_ascii_map = None def _ebcdic_to_ascii(s): global _ebcdic_to_ascii_map if not _ebcdic_to_ascii_map: emap = ( 0, 1, 2, 3, 156, 9, 134, 127, 151, 141, 142, 11, 12, 13, 14, 15, 16, 17, 18, 19, 157, 133, 8, 135, 24, 25, 146, 143, 28, 29, 30, 31, 128, 129, 130, 131, 132, 10, 23, 27, 136, 137, 138, 139, 140, 5, 6, 7, 144, 145, 22, 147, 148, 149, 150, 4, 152, 153, 154, 155, 20, 21, 158, 26, 32, 160, 161, 162, 163, 164, 165, 166, 167, 168, 91, 46, 60, 40, 43, 33, 38, 169, 170, 171, 172, 173, 174, 175, 176, 177, 93, 36, 42, 41, 59, 94, 45, 47, 178, 179, 180, 181, 182, 183, 184, 185, 124, 44, 37, 95, 62, 63, 186, 187, 188, 189, 190, 191, 192, 193, 194, 96, 58, 35, 64, 39, 61, 34, 195, 97, 98, 99, 100, 101, 102, 103, 104, 105, 196, 197, 198, 199, 200, 201, 202, 106, 107, 108, 109, 110, 111, 112, 113, 114, 203, 204, 205, 206, 207, 208, 209, 126, 115, 116, 117, 118, 119, 120, 121, 122, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 123, 65, 66, 67, 68, 69, 70, 71, 72, 73, 232, 233, 234, 235, 236, 237, 125, 74, 75, 76, 77, 78, 79, 80, 81, 82, 238, 239, 240, 241, 242, 243, 92, 159, 83, 84, 85, 86, 87, 88, 89, 90, 244, 245, 246, 247, 248, 249, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 250, 251, 252, 253, 254, 255, ) import string _ebcdic_to_ascii_map = string.maketrans(''.join(map(chr, range(256))), ''.join(map(chr, emap))) return s.translate(_ebcdic_to_ascii_map) _urifixer = re.compile('^([A-Za-z][A-Za-z0-9+-.]*://)(/*)(.*?)') def _urljoin(base, uri): uri = _urifixer.sub(r'\1\3', uri) return urlparse.urljoin(base, uri) class _FeedParserMixin: namespaces = { '': '', 'http://backend.userland.com/rss': '', 'http://blogs.law.harvard.edu/tech/rss': '', 'http://purl.org/rss/1.0/': '', 'http://my.netscape.com/rdf/simple/0.9/': '', 'http://example.com/newformat#': '', 'http://example.com/necho': '', 'http://purl.org/echo/': '', 'uri/of/echo/namespace#': '', 'http://purl.org/pie/': '', 'http://purl.org/atom/ns#': '', 'http://www.w3.org/2005/Atom': '', 'http://purl.org/rss/1.0/modules/rss091#': '', 'http://webns.net/mvcb/': 'admin', 'http://purl.org/rss/1.0/modules/aggregation/': 'ag', 'http://purl.org/rss/1.0/modules/annotate/': 'annotate', 'http://media.tangent.org/rss/1.0/': 'audio', 'http://backend.userland.com/blogChannelModule': 'blogChannel', 'http://web.resource.org/cc/': 'cc', 'http://backend.userland.com/creativeCommonsRssModule': 'creativeCommons', 'http://purl.org/rss/1.0/modules/company': 'co', 'http://purl.org/rss/1.0/modules/content/': 'content', 'http://my.theinfo.org/changed/1.0/rss/': 'cp', 'http://purl.org/dc/elements/1.1/': 'dc', 'http://purl.org/dc/terms/': 'dcterms', 'http://purl.org/rss/1.0/modules/email/': 'email', 'http://purl.org/rss/1.0/modules/event/': 'ev', 'http://rssnamespace.org/feedburner/ext/1.0': 'feedburner', 'http://freshmeat.net/rss/fm/': 'fm', 'http://xmlns.com/foaf/0.1/': 'foaf', 'http://www.w3.org/2003/01/geo/wgs84_pos#': 'geo', 'http://postneo.com/icbm/': 'icbm', 'http://purl.org/rss/1.0/modules/image/': 'image', 'http://www.itunes.com/DTDs/PodCast-1.0.dtd': 'itunes', 'http://example.com/DTDs/PodCast-1.0.dtd': 'itunes', 'http://purl.org/rss/1.0/modules/link/': 'l', 'http://search.yahoo.com/mrss': 'media', 'http://madskills.com/public/xml/rss/module/pingback/': 'pingback', 'http://prismstandard.org/namespaces/1.2/basic/': 'prism', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#': 'rdf', 'http://www.w3.org/2000/01/rdf-schema#': 'rdfs', 'http://purl.org/rss/1.0/modules/reference/': 'ref', 'http://purl.org/rss/1.0/modules/richequiv/': 'reqv', 'http://purl.org/rss/1.0/modules/search/': 'search', 'http://purl.org/rss/1.0/modules/slash/': 'slash', 'http://schemas.xmlsoap.org/soap/envelope/': 'soap', 'http://purl.org/rss/1.0/modules/servicestatus/': 'ss', 'http://hacks.benhammersley.com/rss/streaming/': 'str', 'http://purl.org/rss/1.0/modules/subscription/': 'sub', 'http://purl.org/rss/1.0/modules/syndication/': 'sy', 'http://purl.org/rss/1.0/modules/taxonomy/': 'taxo', 'http://purl.org/rss/1.0/modules/threading/': 'thr', 'http://purl.org/rss/1.0/modules/textinput/': 'ti', 'http://madskills.com/public/xml/rss/module/trackback/': 'trackback', 'http://wellformedweb.org/commentAPI/': 'wfw', 'http://purl.org/rss/1.0/modules/wiki/': 'wiki', 'http://www.w3.org/1999/xhtml': 'xhtml', 'http://www.w3.org/XML/1998/namespace': 'xml', 'http://schemas.pocketsoap.com/rss/myDescModule/': 'szf', } _matchnamespaces = {} can_be_relative_uri = [ 'link', 'id', 'wfw_comment', 'wfw_commentrss', 'docs', 'url', 'href', 'comments', 'license', 'icon', 'logo', ] can_contain_relative_uris = [ 'content', 'title', 'summary', 'info', 'tagline', 'subtitle', 'copyright', 'rights', 'description', ] can_contain_dangerous_markup = [ 'content', 'title', 'summary', 'info', 'tagline', 'subtitle', 'copyright', 'rights', 'description', ] html_types = ['text/html', 'application/xhtml+xml'] def __init__( self, baseuri=None, baselang=None, encoding='utf-8', ): if _debug: sys.stderr.write('initializing FeedParser\n') if not self._matchnamespaces: for (k, v) in self.namespaces.items(): self._matchnamespaces[k.lower()] = v self.feeddata = FeedParserDict() # feed-level data self.encoding = encoding # character encoding self.entries = [] # list of entry-level data self.version = '' # feed type/version, see SUPPORTED_VERSIONS self.namespacesInUse = {} # dictionary of namespaces defined by the feed # the following are used internally to track state; # this is really out of control and should be refactored self.infeed = 0 self.inentry = 0 self.incontent = 0 self.intextinput = 0 self.inimage = 0 self.inauthor = 0 self.incontributor = 0 self.inpublisher = 0 self.insource = 0 self.sourcedata = FeedParserDict() self.contentparams = FeedParserDict() self._summaryKey = None self.namespacemap = {} self.elementstack = [] self.basestack = [] self.langstack = [] self.baseuri = baseuri or '' self.lang = baselang or None if baselang: self.feeddata['language'] = baselang def unknown_starttag(self, tag, attrs): if _debug: sys.stderr.write('start %s with %s\n' % (tag, attrs)) # normalize attrs attrs = [(k.lower(), v) for (k, v) in attrs] attrs = [(k, k in ('rel', 'type') and v.lower() or v) for (k, v) in attrs] # track xml:base and xml:lang attrsD = dict(attrs) baseuri = attrsD.get('xml:base', attrsD.get('base'))\ or self.baseuri self.baseuri = _urljoin(self.baseuri, baseuri) lang = attrsD.get('xml:lang', attrsD.get('lang')) if lang == '': # xml:lang could be explicitly set to '', we need to capture that lang = None elif lang is None: # if no xml:lang is specified, use parent lang lang = self.lang if lang: if tag in ('feed', 'rss', 'rdf:RDF'): self.feeddata['language'] = lang self.lang = lang self.basestack.append(self.baseuri) self.langstack.append(lang) # track namespaces for (prefix, uri) in attrs: if prefix.startswith('xmlns:'): self.trackNamespace(prefix[6:], uri) elif prefix == 'xmlns': self.trackNamespace(None, uri) # track inline content if self.incontent and self.contentparams.has_key('type')\ and not self.contentparams.get('type', 'xml' ).endswith('xml'): # element declared itself as escaped markup, but it isn't really self.contentparams['type'] = 'application/xhtml+xml' if self.incontent and self.contentparams.get('type')\ == 'application/xhtml+xml': # Note: probably shouldn't simply recreate localname here, but # our namespace handling isn't actually 100% correct in cases where # the feed redefines the default namespace (which is actually # the usual case for inline content, thanks Sam), so here we # cheat and just reconstruct the element based on localname # because that compensates for the bugs in our namespace handling. # This will horribly munge inline content with non-empty qnames, # but nobody actually does that, so I'm not fixing it. tag = tag.split(':')[-1] return self.handle_data('<%s%s>' % (tag, ''.join([' %s="%s"' % t for t in attrs])), escape=0) # match namespaces if tag.find(':') != -1: (prefix, suffix) = tag.split(':', 1) else: (prefix, suffix) = ('', tag) prefix = self.namespacemap.get(prefix, prefix) if prefix: prefix = prefix + '_' # special hack for better tracking of empty textinput/image elements in illformed feeds if not prefix and tag not in ('title', 'link', 'description', 'name'): self.intextinput = 0 if not prefix and tag not in ( 'title', 'link', 'description', 'url', 'href', 'width', 'height', ): self.inimage = 0 # call special handler (if defined) or default handler methodname = '_start_' + prefix + suffix try: method = getattr(self, methodname) return method(attrsD) except AttributeError: return self.push(prefix + suffix, 1) def unknown_endtag(self, tag): if _debug: sys.stderr.write('end %s\n' % tag) # match namespaces if tag.find(':') != -1: (prefix, suffix) = tag.split(':', 1) else: (prefix, suffix) = ('', tag) prefix = self.namespacemap.get(prefix, prefix) if prefix: prefix = prefix + '_' # call special handler (if defined) or default handler methodname = '_end_' + prefix + suffix try: method = getattr(self, methodname) method() except AttributeError: self.pop(prefix + suffix) # track inline content if self.incontent and self.contentparams.has_key('type')\ and not self.contentparams.get('type', 'xml' ).endswith('xml'): # element declared itself as escaped markup, but it isn't really self.contentparams['type'] = 'application/xhtml+xml' if self.incontent and self.contentparams.get('type')\ == 'application/xhtml+xml': tag = tag.split(':')[-1] self.handle_data('</%s>' % tag, escape=0) # track xml:base and xml:lang going out of scope if self.basestack: self.basestack.pop() if self.basestack and self.basestack[-1]: self.baseuri = self.basestack[-1] if self.langstack: self.langstack.pop() if self.langstack: # and (self.langstack[-1] is not None): self.lang = self.langstack[-1] def handle_charref(self, ref): # called for each character reference, e.g. for '&#160;', ref will be '160' if not self.elementstack: return ref = ref.lower() if ref in ( '34', '38', '39', '60', '62', 'x22', 'x26', 'x27', 'x3c', 'x3e', ): text = '&#%s;' % ref else: if ref[0] == 'x': c = int(ref[1:], 16) else: c = int(ref) text = unichr(c).encode('utf-8') self.elementstack[-1][2].append(text) def handle_entityref(self, ref): # called for each entity reference, e.g. for '&copy;', ref will be 'copy' if not self.elementstack: return if _debug: sys.stderr.write('entering handle_entityref with %s\n' % ref) if ref in ('lt', 'gt', 'quot', 'amp', 'apos'): text = '&%s;' % ref else: # entity resolution graciously donated by Aaron Swartz def name2cp(k): import htmlentitydefs if hasattr(htmlentitydefs, 'name2codepoint'): # requires Python 2.3 return htmlentitydefs.name2codepoint[k] k = htmlentitydefs.entitydefs[k] if k.startswith('&#') and k.endswith(';'): return int(k[2:-1]) # not in latin-1 return ord(k) try: name2cp(ref) except KeyError: text = '&%s;' % ref else: text = unichr(name2cp(ref)).encode('utf-8') self.elementstack[-1][2].append(text) def handle_data(self, text, escape=1): # called for each block of plain text, i.e. outside of any tag and # not containing any character or entity references if not self.elementstack: return if escape and self.contentparams.get('type')\ == 'application/xhtml+xml': text = _xmlescape(text) self.elementstack[-1][2].append(text) def handle_comment(self, text): # called for each comment, e.g. <!-- insert message here --> pass def handle_pi(self, text): # called for each processing instruction, e.g. <?instruction> pass def handle_decl(self, text): pass def parse_declaration(self, i): # override internal declaration handler to handle CDATA blocks if _debug: sys.stderr.write('entering parse_declaration\n') if self.rawdata[i:i + 9] == '<![CDATA[': k = self.rawdata.find(']]>', i) if k == -1: k = len(self.rawdata) self.handle_data(_xmlescape(self.rawdata[i + 9:k]), 0) return k + 3 else: k = self.rawdata.find('>', i) return k + 1 def mapContentType(self, contentType): contentType = contentType.lower() if contentType == 'text': contentType = 'text/plain' elif contentType == 'html': contentType = 'text/html' elif contentType == 'xhtml': contentType = 'application/xhtml+xml' return contentType def trackNamespace(self, prefix, uri): loweruri = uri.lower() if (prefix, loweruri) == (None, 'http://my.netscape.com/rdf/simple/0.9/' ) and not self.version: self.version = 'rss090' if loweruri == 'http://purl.org/rss/1.0/' and not self.version: self.version = 'rss10' if loweruri == 'http://www.w3.org/2005/atom'\ and not self.version: self.version = 'atom10' if loweruri.find('backend.userland.com/rss') != -1: # match any backend.userland.com namespace uri = 'http://backend.userland.com/rss' loweruri = uri if self._matchnamespaces.has_key(loweruri): self.namespacemap[prefix] = self._matchnamespaces[loweruri] self.namespacesInUse[self._matchnamespaces[loweruri]] = uri else: self.namespacesInUse[prefix or ''] = uri def resolveURI(self, uri): return _urljoin(self.baseuri or '', uri) def decodeEntities(self, element, data): return data def push(self, element, expectingText): self.elementstack.append([element, expectingText, []]) def pop(self, element, stripWhitespace=1): if not self.elementstack: return if self.elementstack[-1][0] != element: return (element, expectingText, pieces) = self.elementstack.pop() output = ''.join(pieces) if stripWhitespace: output = output.strip() if not expectingText: return output # decode base64 content if base64 and self.contentparams.get('base64', 0): try: output = base64.decodestring(output) except binascii.Error: pass except binascii.Incomplete: pass # resolve relative URIs if element in self.can_be_relative_uri and output: output = self.resolveURI(output) # decode entities within embedded markup if not self.contentparams.get('base64', 0): output = self.decodeEntities(element, output) # remove temporary cruft from contentparams try: del self.contentparams['mode'] except KeyError: pass try: del self.contentparams['base64'] except KeyError: pass # resolve relative URIs within embedded markup if self.mapContentType(self.contentparams.get('type', 'text/html')) in self.html_types: if element in self.can_contain_relative_uris: output = _resolveRelativeURIs(output, self.baseuri, self.encoding) # sanitize embedded markup if self.mapContentType(self.contentparams.get('type', 'text/html')) in self.html_types: if element in self.can_contain_dangerous_markup: output = _sanitizeHTML(output, self.encoding) if self.encoding and type(output) != type(u''): try: output = unicode(output, self.encoding) except: pass # categories/tags/keywords/whatever are handled in _end_category if element == 'category': return output # store output in appropriate place(s) if self.inentry and not self.insource: if element == 'content': self.entries[-1].setdefault(element, []) contentparams = copy.deepcopy(self.contentparams) contentparams['value'] = output self.entries[-1][element].append(contentparams) elif element == 'link': self.entries[-1][element] = output if output: self.entries[-1]['links'][-1]['href'] = output else: if element == 'description': element = 'summary' self.entries[-1][element] = output if self.incontent: contentparams = copy.deepcopy(self.contentparams) contentparams['value'] = output self.entries[-1][element + '_detail'] = \ contentparams elif (self.infeed or self.insource) and not self.intextinput\ and not self.inimage: context = self._getContext() if element == 'description': element = 'subtitle' context[element] = output if element == 'link': context['links'][-1]['href'] = output elif self.incontent: contentparams = copy.deepcopy(self.contentparams) contentparams['value'] = output context[element + '_detail'] = contentparams return output def pushContent( self, tag, attrsD, defaultContentType, expectingText, ): self.incontent += 1 self.contentparams = FeedParserDict({'type' : self.mapContentType(attrsD.get('type', defaultContentType)), 'language': self.lang, 'base' : self.baseuri}) self.contentparams['base64'] = self._isBase64(attrsD, self.contentparams) self.push(tag, expectingText) def popContent(self, tag): value = self.pop(tag) self.incontent -= 1 self.contentparams.clear() return value def _mapToStandardPrefix(self, name): colonpos = name.find(':') if colonpos != -1: prefix = name[:colonpos] suffix = name[colonpos + 1:] prefix = self.namespacemap.get(prefix, prefix) name = prefix + ':' + suffix return name def _getAttribute(self, attrsD, name): return attrsD.get(self._mapToStandardPrefix(name)) def _isBase64(self, attrsD, contentparams): if attrsD.get('mode', '') == 'base64': return 1 if self.contentparams['type'].startswith('text/'): return 0 if self.contentparams['type'].endswith('+xml'): return 0 if self.contentparams['type'].endswith('/xml'): return 0 return 1 def _itsAnHrefDamnIt(self, attrsD): href = attrsD.get('url', attrsD.get('uri', attrsD.get('href', None))) if href: try: del attrsD['url'] except KeyError: pass try: del attrsD['uri'] except KeyError: pass attrsD['href'] = href return attrsD def _save(self, key, value): context = self._getContext() context.setdefault(key, value) def _start_rss(self, attrsD): versionmap = { '0.91': 'rss091u', '0.92': 'rss092', '0.93': 'rss093', '0.94': 'rss094', } if not self.version: attr_version = attrsD.get('version', '') version = versionmap.get(attr_version) if version: self.version = version elif attr_version.startswith('2.'): self.version = 'rss20' else: self.version = 'rss' def _start_dlhottitles(self, attrsD): self.version = 'hotrss' def _start_channel(self, attrsD): self.infeed = 1 self._cdf_common(attrsD) _start_feedinfo = _start_channel def _cdf_common(self, attrsD): if attrsD.has_key('lastmod'): self._start_modified({}) self.elementstack[-1][-1] = attrsD['lastmod'] self._end_modified() if attrsD.has_key('href'): self._start_link({}) self.elementstack[-1][-1] = attrsD['href'] self._end_link() def _start_feed(self, attrsD): self.infeed = 1 versionmap = {'0.1': 'atom01', '0.2': 'atom02', '0.3': 'atom03'} if not self.version: attr_version = attrsD.get('version') version = versionmap.get(attr_version) if version: self.version = version else: self.version = 'atom' def _end_channel(self): self.infeed = 0 _end_feed = _end_channel def _start_image(self, attrsD): self.inimage = 1 self.push('image', 0) context = self._getContext() context.setdefault('image', FeedParserDict()) def _end_image(self): self.pop('image') self.inimage = 0 def _start_textinput(self, attrsD): self.intextinput = 1 self.push('textinput', 0) context = self._getContext() context.setdefault('textinput', FeedParserDict()) _start_textInput = _start_textinput def _end_textinput(self): self.pop('textinput') self.intextinput = 0 _end_textInput = _end_textinput def _start_author(self, attrsD): self.inauthor = 1 self.push('author', 1) _start_managingeditor = _start_author _start_dc_author = _start_author _start_dc_creator = _start_author _start_itunes_author = _start_author def _end_author(self): self.pop('author') self.inauthor = 0 self._sync_author_detail() _end_managingeditor = _end_author _end_dc_author = _end_author _end_dc_creator = _end_author _end_itunes_author = _end_author def _start_itunes_owner(self, attrsD): self.inpublisher = 1 self.push('publisher', 0) def _end_itunes_owner(self): self.pop('publisher') self.inpublisher = 0 self._sync_author_detail('publisher') def _start_contributor(self, attrsD): self.incontributor = 1 context = self._getContext() context.setdefault('contributors', []) context['contributors'].append(FeedParserDict()) self.push('contributor', 0) def _end_contributor(self): self.pop('contributor') self.incontributor = 0 def _start_dc_contributor(self, attrsD): self.incontributor = 1 context = self._getContext() context.setdefault('contributors', []) context['contributors'].append(FeedParserDict()) self.push('name', 0) def _end_dc_contributor(self): self._end_name() self.incontributor = 0 def _start_name(self, attrsD): self.push('name', 0) _start_itunes_name = _start_name def _end_name(self): value = self.pop('name') if self.inpublisher: self._save_author('name', value, 'publisher') elif self.inauthor: self._save_author('name', value) elif self.incontributor: self._save_contributor('name', value) elif self.intextinput: context = self._getContext() context['textinput']['name'] = value _end_itunes_name = _end_name def _start_width(self, attrsD): self.push('width', 0) def _end_width(self): value = self.pop('width') try: value = int(value) except: value = 0 if self.inimage: context = self._getContext() context['image']['width'] = value def _start_height(self, attrsD): self.push('height', 0) def _end_height(self): value = self.pop('height') try: value = int(value) except: value = 0 if self.inimage: context = self._getContext() context['image']['height'] = value def _start_url(self, attrsD): self.push('href', 1) _start_homepage = _start_url _start_uri = _start_url def _end_url(self): value = self.pop('href') if self.inauthor: self._save_author('href', value) elif self.incontributor: self._save_contributor('href', value) elif self.inimage: context = self._getContext() context['image']['href'] = value elif self.intextinput: context = self._getContext() context['textinput']['link'] = value _end_homepage = _end_url _end_uri = _end_url def _start_email(self, attrsD): self.push('email', 0) _start_itunes_email = _start_email def _end_email(self): value = self.pop('email') if self.inpublisher: self._save_author('email', value, 'publisher') elif self.inauthor: self._save_author('email', value) elif self.incontributor: self._save_contributor('email', value) _end_itunes_email = _end_email def _getContext(self): if self.insource: context = self.sourcedata elif self.inentry: context = self.entries[-1] else: context = self.feeddata return context def _save_author( self, key, value, prefix='author', ): context = self._getContext() context.setdefault(prefix + '_detail', FeedParserDict()) context[prefix + '_detail'][key] = value self._sync_author_detail() def _save_contributor(self, key, value): context = self._getContext() context.setdefault('contributors', [FeedParserDict()]) context['contributors'][-1][key] = value def _sync_author_detail(self, key='author'): context = self._getContext() detail = context.get('%s_detail' % key) if detail: name = detail.get('name') email = detail.get('email') if name and email: context[key] = '%s (%s)' % (name, email) elif name: context[key] = name elif email: context[key] = email else: author = context.get(key) if not author: return emailmatch = \ re.search(r'''(([a-zA-Z0-9\_\-\.\+]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?))''' , author) if not emailmatch: return email = emailmatch.group(0) # probably a better way to do the following, but it passes all the tests author = author.replace(email, '') author = author.replace('()', '') author = author.strip() if author and author[0] == '(': author = author[1:] if author and author[-1] == ')': author = author[:-1] author = author.strip() context.setdefault('%s_detail' % key, FeedParserDict()) context['%s_detail' % key]['name'] = author context['%s_detail' % key]['email'] = email def _start_subtitle(self, attrsD): self.pushContent('subtitle', attrsD, 'text/plain', 1) _start_tagline = _start_subtitle _start_itunes_subtitle = _start_subtitle def _end_subtitle(self): self.popContent('subtitle') _end_tagline = _end_subtitle _end_itunes_subtitle = _end_subtitle def _start_rights(self, attrsD): self.pushContent('rights', attrsD, 'text/plain', 1) _start_dc_rights = _start_rights _start_copyright = _start_rights def _end_rights(self): self.popContent('rights') _end_dc_rights = _end_rights _end_copyright = _end_rights def _start_item(self, attrsD): self.entries.append(FeedParserDict()) self.push('item', 0) self.inentry = 1 self.guidislink = 0 id = self._getAttribute(attrsD, 'rdf:about') if id: context = self._getContext() context['id'] = id self._cdf_common(attrsD) _start_entry = _start_item _start_product = _start_item def _end_item(self): self.pop('item') self.inentry = 0 _end_entry = _end_item def _start_dc_language(self, attrsD): self.push('language', 1) _start_language = _start_dc_language def _end_dc_language(self): self.lang = self.pop('language') _end_language = _end_dc_language def _start_dc_publisher(self, attrsD): self.push('publisher', 1) _start_webmaster = _start_dc_publisher def _end_dc_publisher(self): self.pop('publisher') self._sync_author_detail('publisher') _end_webmaster = _end_dc_publisher def _start_published(self, attrsD): self.push('published', 1) _start_dcterms_issued = _start_published _start_issued = _start_published def _end_published(self): value = self.pop('published') self._save('published_parsed', _parse_date(value)) _end_dcterms_issued = _end_published _end_issued = _end_published def _start_updated(self, attrsD): self.push('updated', 1) _start_modified = _start_updated _start_dcterms_modified = _start_updated _start_pubdate = _start_updated _start_dc_date = _start_updated def _end_updated(self): value = self.pop('updated') parsed_value = _parse_date(value) self._save('updated_parsed', parsed_value) _end_modified = _end_updated _end_dcterms_modified = _end_updated _end_pubdate = _end_updated _end_dc_date = _end_updated def _start_created(self, attrsD): self.push('created', 1) _start_dcterms_created = _start_created def _end_created(self): value = self.pop('created') self._save('created_parsed', _parse_date(value)) _end_dcterms_created = _end_created def _start_expirationdate(self, attrsD): self.push('expired', 1) def _end_expirationdate(self): self._save('expired_parsed', _parse_date(self.pop('expired'))) def _start_cc_license(self, attrsD): self.push('license', 1) value = self._getAttribute(attrsD, 'rdf:resource') if value: self.elementstack[-1][2].append(value) self.pop('license') def _start_creativecommons_license(self, attrsD): self.push('license', 1) def _end_creativecommons_license(self): self.pop('license') def _addTag( self, term, scheme, label, ): context = self._getContext() tags = context.setdefault('tags', []) if not term and not scheme and not label: return value = FeedParserDict({'term': term, 'scheme': scheme, 'label' : label}) if value not in tags: tags.append(FeedParserDict({'term': term, 'scheme': scheme, 'label': label})) def _start_category(self, attrsD): if _debug: sys.stderr.write('entering _start_category with %s\n' % repr(attrsD)) term = attrsD.get('term') scheme = attrsD.get('scheme', attrsD.get('domain')) label = attrsD.get('label') self._addTag(term, scheme, label) self.push('category', 1) _start_dc_subject = _start_category _start_keywords = _start_category def _end_itunes_keywords(self): for term in self.pop('itunes_keywords').split(): self._addTag(term, 'http://www.itunes.com/', None) def _start_itunes_category(self, attrsD): self._addTag(attrsD.get('text'), 'http://www.itunes.com/', None) self.push('category', 1) def _end_category(self): value = self.pop('category') if not value: return context = self._getContext() tags = context['tags'] if value and len(tags) and not tags[-1]['term']: tags[-1]['term'] = value else: self._addTag(value, None, None) _end_dc_subject = _end_category _end_keywords = _end_category _end_itunes_category = _end_category def _start_cloud(self, attrsD): self._getContext()['cloud'] = FeedParserDict(attrsD) def _start_link(self, attrsD): attrsD.setdefault('rel', 'alternate') attrsD.setdefault('type', 'text/html') attrsD = self._itsAnHrefDamnIt(attrsD) if attrsD.has_key('href'): attrsD['href'] = self.resolveURI(attrsD['href']) expectingText = self.infeed or self.inentry or self.insource context = self._getContext() context.setdefault('links', []) context['links'].append(FeedParserDict(attrsD)) if attrsD['rel'] == 'enclosure': self._start_enclosure(attrsD) if attrsD.has_key('href'): expectingText = 0 if attrsD.get('rel') == 'alternate'\ and self.mapContentType(attrsD.get('type'))\ in self.html_types: context['link'] = attrsD['href'] else: self.push('link', expectingText) _start_producturl = _start_link def _end_link(self): value = self.pop('link') context = self._getContext() if self.intextinput: context['textinput']['link'] = value if self.inimage: context['image']['link'] = value _end_producturl = _end_link def _start_guid(self, attrsD): self.guidislink = attrsD.get('ispermalink', 'true') == 'true' self.push('id', 1) def _end_guid(self): value = self.pop('id') self._save('guidislink', self.guidislink and not self._getContext().has_key('link')) if self.guidislink: # guid acts as link, but only if 'ispermalink' is not present or is 'true', # and only if the item doesn't already have a link element self._save('link', value) def _start_title(self, attrsD): self.pushContent('title', attrsD, 'text/plain', self.infeed or self.inentry or self.insource) _start_dc_title = _start_title _start_media_title = _start_title def _end_title(self): value = self.popContent('title') context = self._getContext() if self.intextinput: context['textinput']['title'] = value elif self.inimage: context['image']['title'] = value _end_dc_title = _end_title _end_media_title = _end_title def _start_description(self, attrsD): context = self._getContext() if context.has_key('summary'): self._summaryKey = 'content' self._start_content(attrsD) else: self.pushContent('description', attrsD, 'text/html', self.infeed or self.inentry or self.insource) def _start_abstract(self, attrsD): self.pushContent('description', attrsD, 'text/plain', self.infeed or self.inentry or self.insource) def _end_description(self): if self._summaryKey == 'content': self._end_content() else: value = self.popContent('description') context = self._getContext() if self.intextinput: context['textinput']['description'] = value elif self.inimage: context['image']['description'] = value self._summaryKey = None _end_abstract = _end_description def _start_info(self, attrsD): self.pushContent('info', attrsD, 'text/plain', 1) _start_feedburner_browserfriendly = _start_info def _end_info(self): self.popContent('info') _end_feedburner_browserfriendly = _end_info def _start_generator(self, attrsD): if attrsD: attrsD = self._itsAnHrefDamnIt(attrsD) if attrsD.has_key('href'): attrsD['href'] = self.resolveURI(attrsD['href']) self._getContext()['generator_detail'] = FeedParserDict(attrsD) self.push('generator', 1) def _end_generator(self): value = self.pop('generator') context = self._getContext() if context.has_key('generator_detail'): context['generator_detail']['name'] = value def _start_admin_generatoragent(self, attrsD): self.push('generator', 1) value = self._getAttribute(attrsD, 'rdf:resource') if value: self.elementstack[-1][2].append(value) self.pop('generator') self._getContext()['generator_detail'] = FeedParserDict({'href' : value}) def _start_admin_errorreportsto(self, attrsD): self.push('errorreportsto', 1) value = self._getAttribute(attrsD, 'rdf:resource') if value: self.elementstack[-1][2].append(value) self.pop('errorreportsto') def _start_summary(self, attrsD): context = self._getContext() if context.has_key('summary'): self._summaryKey = 'content' self._start_content(attrsD) else: self._summaryKey = 'summary' self.pushContent(self._summaryKey, attrsD, 'text/plain', 1) _start_itunes_summary = _start_summary def _end_summary(self): if self._summaryKey == 'content': self._end_content() else: self.popContent(self._summaryKey or 'summary') self._summaryKey = None _end_itunes_summary = _end_summary def _start_enclosure(self, attrsD): attrsD = self._itsAnHrefDamnIt(attrsD) self._getContext().setdefault('enclosures', []).append(FeedParserDict(attrsD)) href = attrsD.get('href') if href: context = self._getContext() if not context.get('id'): context['id'] = href def _start_source(self, attrsD): self.insource = 1 def _end_source(self): self.insource = 0 self._getContext()['source'] = copy.deepcopy(self.sourcedata) self.sourcedata.clear() def _start_content(self, attrsD): self.pushContent('content', attrsD, 'text/plain', 1) src = attrsD.get('src') if src: self.contentparams['src'] = src self.push('content', 1) def _start_prodlink(self, attrsD): self.pushContent('content', attrsD, 'text/html', 1) def _start_body(self, attrsD): self.pushContent('content', attrsD, 'application/xhtml+xml', 1) _start_xhtml_body = _start_body def _start_content_encoded(self, attrsD): self.pushContent('content', attrsD, 'text/html', 1) _start_fullitem = _start_content_encoded def _end_content(self): copyToDescription = \ self.mapContentType(self.contentparams.get('type'))\ in ['text/plain'] + self.html_types value = self.popContent('content') if copyToDescription: self._save('description', value) _end_body = _end_content _end_xhtml_body = _end_content _end_content_encoded = _end_content _end_fullitem = _end_content _end_prodlink = _end_content def _start_itunes_image(self, attrsD): self.push('itunes_image', 0) self._getContext()['image'] = FeedParserDict({'href' : attrsD.get('href')}) _start_itunes_link = _start_itunes_image def _end_itunes_block(self): value = self.pop('itunes_block', 0) self._getContext()['itunes_block'] = value == 'yes' and 1 or 0 def _end_itunes_explicit(self): value = self.pop('itunes_explicit', 0) self._getContext()['itunes_explicit'] = value == 'yes' and 1\ or 0 if _XML_AVAILABLE: class _StrictFeedParser(_FeedParserMixin, xml.sax.handler.ContentHandler): def __init__( self, baseuri, baselang, encoding, ): if _debug: sys.stderr.write('trying StrictFeedParser\n') xml.sax.handler.ContentHandler.__init__(self) _FeedParserMixin.__init__(self, baseuri, baselang, encoding) self.bozo = 0 self.exc = None def startPrefixMapping(self, prefix, uri): self.trackNamespace(prefix, uri) def startElementNS( self, name, qname, attrs, ): (namespace, localname) = name lowernamespace = str(namespace or '').lower() if lowernamespace.find('backend.userland.com/rss') != -1: # match any backend.userland.com namespace namespace = 'http://backend.userland.com/rss' lowernamespace = namespace if qname and qname.find(':') > 0: givenprefix = qname.split(':')[0] else: givenprefix = None prefix = self._matchnamespaces.get(lowernamespace, givenprefix) if givenprefix and (prefix == None or prefix == '' and lowernamespace == '')\ and not self.namespacesInUse.has_key(givenprefix): raise UndeclaredNamespace, \ "'%s' is not associated with a namespace"\ % givenprefix if prefix: localname = prefix + ':' + localname localname = str(localname).lower() if _debug: sys.stderr.write('startElementNS: qname = %s, namespace = %s, givenprefix = %s, prefix = %s, attrs = %s, localname = %s\n' % ( qname, namespace, givenprefix, prefix, attrs.items(), localname, )) # qname implementation is horribly broken in Python 2.1 (it # doesn't report any), and slightly broken in Python 2.2 (it # doesn't report the xml: namespace). So we match up namespaces # with a known list first, and then possibly override them with # the qnames the SAX parser gives us (if indeed it gives us any # at all). Thanks to MatejC for helping me test this and # tirelessly telling me that it didn't work yet. attrsD = {} for ((namespace, attrlocalname), attrvalue) in \ attrs._attrs.items(): lowernamespace = (namespace or '').lower() prefix = self._matchnamespaces.get(lowernamespace, '') if prefix: attrlocalname = prefix + ':' + attrlocalname attrsD[str(attrlocalname).lower()] = attrvalue for qname in attrs.getQNames(): attrsD[str(qname).lower()] = \ attrs.getValueByQName(qname) self.unknown_starttag(localname, attrsD.items()) def characters(self, text): self.handle_data(text) def endElementNS(self, name, qname): (namespace, localname) = name lowernamespace = str(namespace or '').lower() if qname and qname.find(':') > 0: givenprefix = qname.split(':')[0] else: givenprefix = '' prefix = self._matchnamespaces.get(lowernamespace, givenprefix) if prefix: localname = prefix + ':' + localname localname = str(localname).lower() self.unknown_endtag(localname) def error(self, exc): self.bozo = 1 self.exc = exc def fatalError(self, exc): self.error(exc) raise exc class _BaseHTMLProcessor(sgmllib.SGMLParser): elements_no_end_tag = [ 'area', 'base', 'basefont', 'br', 'col', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param', ] def __init__(self, encoding): self.encoding = encoding if _debug: sys.stderr.write('entering BaseHTMLProcessor, encoding=%s\n' % self.encoding) sgmllib.SGMLParser.__init__(self) def reset(self): self.pieces = [] sgmllib.SGMLParser.reset(self) def _shorttag_replace(self, match): tag = match.group(1) if tag in self.elements_no_end_tag: return '<' + tag + ' />' else: return '<' + tag + '></' + tag + '>' def feed(self, data): data = re.compile(r'<!((?!DOCTYPE|--|\[))', re.IGNORECASE).sub(r'&lt;!\1', data) # data = re.sub(r'<(\S+?)\s*?/>', self._shorttag_replace, data) # bug [ 1399464 ] Bad regexp for _shorttag_replace data = re.sub(r'<([^<\s]+?)\s*/>', self._shorttag_replace, data) data = data.replace('&#39;', "'") data = data.replace('&#34;', '"') if self.encoding and type(data) == type(u''): data = data.encode(self.encoding) sgmllib.SGMLParser.feed(self, data) def normalize_attrs(self, attrs): # utility method to be called by descendants attrs = [(k.lower(), v) for (k, v) in attrs] attrs = [(k, k in ('rel', 'type') and v.lower() or v) for (k, v) in attrs] return attrs def unknown_starttag(self, tag, attrs): # called for each start tag # attrs is a list of (attr, value) tuples # e.g. for <pre class='screen'>, tag='pre', attrs=[('class', 'screen')] if _debug: sys.stderr.write('_BaseHTMLProcessor, unknown_starttag, tag=%s\n' % tag) uattrs = [] # thanks to Kevin Marks for this breathtaking hack to deal with (valid) high-bit attribute values in UTF-8 feeds for (key, value) in attrs: if type(value) != type(u''): value = unicode(value, self.encoding) uattrs.append((unicode(key, self.encoding), value)) strattrs = u''.join([u' %s="%s"' % (key, value) for (key, value) in uattrs]).encode(self.encoding) if tag in self.elements_no_end_tag: self.pieces.append('<%(tag)s%(strattrs)s />' % locals()) else: self.pieces.append('<%(tag)s%(strattrs)s>' % locals()) def unknown_endtag(self, tag): # called for each end tag, e.g. for </pre>, tag will be 'pre' # Reconstruct the original end tag. if tag not in self.elements_no_end_tag: self.pieces.append('</%(tag)s>' % locals()) def handle_charref(self, ref): # called for each character reference, e.g. for '&#160;', ref will be '160' # Reconstruct the original character reference. self.pieces.append('&#%(ref)s;' % locals()) def handle_entityref(self, ref): # called for each entity reference, e.g. for '&copy;', ref will be 'copy' # Reconstruct the original entity reference. self.pieces.append('&%(ref)s;' % locals()) def handle_data(self, text): # called for each block of plain text, i.e. outside of any tag and # not containing any character or entity references # Store the original text verbatim. if _debug: sys.stderr.write('_BaseHTMLProcessor, handle_text, text=%s\n' % text) self.pieces.append(text) def handle_comment(self, text): # called for each HTML comment, e.g. <!-- insert Javascript code here --> # Reconstruct the original comment. self.pieces.append('<!--%(text)s-->' % locals()) def handle_pi(self, text): # called for each processing instruction, e.g. <?instruction> # Reconstruct original processing instruction. self.pieces.append('<?%(text)s>' % locals()) def handle_decl(self, text): # called for the DOCTYPE, if present, e.g. # <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" # "http://www.w3.org/TR/html4/loose.dtd"> # Reconstruct original DOCTYPE self.pieces.append('<!%(text)s>' % locals()) _new_declname_match = re.compile(r'[a-zA-Z][-_.a-zA-Z0-9:]*\s*' ).match def _scan_name(self, i, declstartpos): rawdata = self.rawdata n = len(rawdata) if i == n: return (None, -1) m = self._new_declname_match(rawdata, i) if m: s = m.group() name = s.strip() if i + len(s) == n: return (None, -1) # end of buffer return (name.lower(), m.end()) else: self.handle_data(rawdata) # self.updatepos(declstartpos, i) return (None, -1) def output(self): """Return processed HTML as a single string""" return ''.join([str(p) for p in self.pieces]) class _LooseFeedParser(_FeedParserMixin, _BaseHTMLProcessor): def __init__( self, baseuri, baselang, encoding, ): sgmllib.SGMLParser.__init__(self) _FeedParserMixin.__init__(self, baseuri, baselang, encoding) def decodeEntities(self, element, data): data = data.replace('&#60;', '&lt;') data = data.replace('&#x3c;', '&lt;') data = data.replace('&#62;', '&gt;') data = data.replace('&#x3e;', '&gt;') data = data.replace('&#38;', '&amp;') data = data.replace('&#x26;', '&amp;') data = data.replace('&#34;', '&quot;') data = data.replace('&#x22;', '&quot;') data = data.replace('&#39;', '&apos;') data = data.replace('&#x27;', '&apos;') if self.contentparams.has_key('type')\ and not self.contentparams.get('type', 'xml' ).endswith('xml'): data = data.replace('&lt;', '<') data = data.replace('&gt;', '>') data = data.replace('&amp;', '&') data = data.replace('&quot;', '"') data = data.replace('&apos;', "'") return data class _RelativeURIResolver(_BaseHTMLProcessor): relative_uris = [ ('a', 'href'), ('applet', 'codebase'), ('area', 'href'), ('blockquote', 'cite'), ('body', 'background'), ('del', 'cite'), ('form', 'action'), ('frame', 'longdesc'), ('frame', 'src'), ('iframe', 'longdesc'), ('iframe', 'src'), ('head', 'profile'), ('img', 'longdesc'), ('img', 'src'), ('img', 'usemap'), ('input', 'src'), ('input', 'usemap'), ('ins', 'cite'), ('link', 'href'), ('object', 'classid'), ('object', 'codebase'), ('object', 'data'), ('object', 'usemap'), ('q', 'cite'), ('script', 'src'), ] def __init__(self, baseuri, encoding): _BaseHTMLProcessor.__init__(self, encoding) self.baseuri = baseuri def resolveURI(self, uri): return _urljoin(self.baseuri, uri) def unknown_starttag(self, tag, attrs): attrs = self.normalize_attrs(attrs) attrs = [(key, (tag, key) in self.relative_uris and self.resolveURI(value) or value) for (key, value) in attrs] _BaseHTMLProcessor.unknown_starttag(self, tag, attrs) def _resolveRelativeURIs(htmlSource, baseURI, encoding): if _debug: sys.stderr.write('entering _resolveRelativeURIs\n') p = _RelativeURIResolver(baseURI, encoding) p.feed(htmlSource) return p.output() class _HTMLSanitizer(_BaseHTMLProcessor): acceptable_elements = [ 'a', 'abbr', 'acronym', 'address', 'area', 'b', 'big', 'blockquote', 'br', 'button', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'dd', 'del', 'dfn', 'dir', 'div', 'dl', 'dt', 'em', 'fieldset', 'font', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'map', 'menu', 'ol', 'optgroup', 'option', 'p', 'pre', 'q', 's', 'samp', 'select', 'small', 'span', 'strike', 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'tr', 'tt', 'u', 'ul', 'var', ] acceptable_attributes = [ 'abbr', 'accept', 'accept-charset', 'accesskey', 'action', 'align', 'alt', 'axis', 'border', 'cellpadding', 'cellspacing', 'char', 'charoff', 'charset', 'checked', 'cite', 'class', 'clear', 'cols', 'colspan', 'color', 'compact', 'coords', 'datetime', 'dir', 'disabled', 'enctype', 'for', 'frame', 'headers', 'height', 'href', 'hreflang', 'hspace', 'id', 'ismap', 'label', 'lang', 'longdesc', 'maxlength', 'media', 'method', 'multiple', 'name', 'nohref', 'noshade', 'nowrap', 'prompt', 'readonly', 'rel', 'rev', 'rows', 'rowspan', 'rules', 'scope', 'selected', 'shape', 'size', 'span', 'src', 'start', 'summary', 'tabindex', 'target', 'title', 'type', 'usemap', 'valign', 'value', 'vspace', 'width', ] unacceptable_elements_with_end_tag = ['script', 'applet'] def reset(self): _BaseHTMLProcessor.reset(self) self.unacceptablestack = 0 def unknown_starttag(self, tag, attrs): if not tag in self.acceptable_elements: if tag in self.unacceptable_elements_with_end_tag: self.unacceptablestack += 1 return attrs = self.normalize_attrs(attrs) attrs = [(key, value) for (key, value) in attrs if key in self.acceptable_attributes] _BaseHTMLProcessor.unknown_starttag(self, tag, attrs) def unknown_endtag(self, tag): if not tag in self.acceptable_elements: if tag in self.unacceptable_elements_with_end_tag: self.unacceptablestack -= 1 return _BaseHTMLProcessor.unknown_endtag(self, tag) def handle_pi(self, text): pass def handle_decl(self, text): pass def handle_data(self, text): if not self.unacceptablestack: _BaseHTMLProcessor.handle_data(self, text) def _sanitizeHTML(htmlSource, encoding): p = _HTMLSanitizer(encoding) p.feed(htmlSource) data = p.output() if TIDY_MARKUP: # loop through list of preferred Tidy interfaces looking for one that's installed, # then set up a common _tidy function to wrap the interface-specific API. _tidy = None for tidy_interface in PREFERRED_TIDY_INTERFACES: try: if tidy_interface == 'uTidy': from tidy import parseString as _utidy def _tidy(data, **kwargs): return str(_utidy(data, **kwargs)) break elif tidy_interface == 'mxTidy': from mx.Tidy import Tidy as _mxtidy def _tidy(data, **kwargs): (nerrors, nwarnings, data, errordata) = \ _mxtidy.tidy(data, **kwargs) return data break except: pass if _tidy: utf8 = type(data) == type(u'') if utf8: data = data.encode('utf-8') data = _tidy(data, output_xhtml=1, numeric_entities=1, wrap=0, char_encoding='utf8') if utf8: data = unicode(data, 'utf-8') if data.count('<body'): data = data.split('<body', 1)[1] if data.count('>'): data = data.split('>', 1)[1] if data.count('</body'): data = data.split('</body', 1)[0] data = data.strip().replace('\r\n', '\n') return data class _FeedURLHandler(urllib2.HTTPDigestAuthHandler, urllib2.HTTPRedirectHandler, urllib2.HTTPDefaultErrorHandler): def http_error_default( self, req, fp, code, msg, headers, ): if code / 100 == 3 and code != 304: return self.http_error_302(req, fp, code, msg, headers) infourl = urllib.addinfourl(fp, headers, req.get_full_url()) infourl.status = code return infourl def http_error_302( self, req, fp, code, msg, headers, ): if headers.dict.has_key('location'): infourl = urllib2.HTTPRedirectHandler.http_error_302( self, req, fp, code, msg, headers, ) else: infourl = urllib.addinfourl(fp, headers, req.get_full_url()) if not hasattr(infourl, 'status'): infourl.status = code return infourl def http_error_301( self, req, fp, code, msg, headers, ): if headers.dict.has_key('location'): infourl = urllib2.HTTPRedirectHandler.http_error_301( self, req, fp, code, msg, headers, ) else: infourl = urllib.addinfourl(fp, headers, req.get_full_url()) if not hasattr(infourl, 'status'): infourl.status = code return infourl http_error_300 = http_error_302 http_error_303 = http_error_302 http_error_307 = http_error_302 def http_error_401( self, req, fp, code, msg, headers, ): # Check if # - server requires digest auth, AND # - we tried (unsuccessfully) with basic auth, AND # - we're using Python 2.3.3 or later (digest auth is irreparably broken in earlier versions) # If all conditions hold, parse authentication information # out of the Authorization header we sent the first time # (for the username and password) and the WWW-Authenticate # header the server sent back (for the realm) and retry # the request with the appropriate digest auth headers instead. # This evil genius hack has been brought to you by Aaron Swartz. host = urlparse.urlparse(req.get_full_url())[1] try: assert sys.version.split()[0] >= '2.3.3' assert base64 != None (user, passw) = \ base64.decodestring(req.headers['Authorization' ].split(' ')[1]).split(':') realm = re.findall('realm="([^"]*)"', headers['WWW-Authenticate'])[0] self.add_password(realm, host, user, passw) retry = self.http_error_auth_reqed('www-authenticate', host, req, headers) self.reset_retry_count() return retry except: return self.http_error_default(req, fp, code, msg, headers) def _open_resource( url_file_stream_or_string, etag, modified, agent, referrer, handlers, ): """URL, filename, or string --> stream This function lets you define parsers that take any input source (URL, pathname to local or network file, or actual data as a string) and deal with it in a uniform manner. Returned object is guaranteed to have all the basic stdio read methods (read, readline, readlines). Just .close() the object when you're done with it. If the etag argument is supplied, it will be used as the value of an If-None-Match request header. If the modified argument is supplied, it must be a tuple of 9 integers as returned by gmtime() in the standard Python time module. This MUST be in GMT (Greenwich Mean Time). The formatted date/time will be used as the value of an If-Modified-Since request header. If the agent argument is supplied, it will be used as the value of a User-Agent request header. If the referrer argument is supplied, it will be used as the value of a Referer[sic] request header. If handlers is supplied, it is a list of handlers used to build a urllib2 opener. """ if hasattr(url_file_stream_or_string, 'read'): return url_file_stream_or_string if url_file_stream_or_string == '-': return sys.stdin if urlparse.urlparse(url_file_stream_or_string)[0] in ('http', 'https', 'ftp'): if not agent: agent = USER_AGENT # test for inline user:password for basic auth auth = None if base64: (urltype, rest) = \ urllib.splittype(url_file_stream_or_string) (realhost, rest) = urllib.splithost(rest) if realhost: (user_passwd, realhost) = urllib.splituser(realhost) if user_passwd: url_file_stream_or_string = '%s://%s%s' % (urltype, realhost, rest) auth = base64.encodestring(user_passwd).strip() # try to open with urllib2 (to use optional headers) request = urllib2.Request(url_file_stream_or_string) request.add_header('User-Agent', agent) if etag: request.add_header('If-None-Match', etag) if modified: # format into an RFC 1123-compliant timestamp. We can't use # time.strftime() since the %a and %b directives can be affected # by the current locale, but RFC 2616 states that dates must be # in English. short_weekdays = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun', ] months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', ] request.add_header('If-Modified-Since', '%s, %02d %s %04d %02d:%02d:%02d GMT' % ( short_weekdays[modified[6]], modified[2], months[modified[1] - 1], modified[0], modified[3], modified[4], modified[5], )) if referrer: request.add_header('Referer', referrer) if gzip and zlib: request.add_header('Accept-encoding', 'gzip, deflate') elif gzip: request.add_header('Accept-encoding', 'gzip') elif zlib: request.add_header('Accept-encoding', 'deflate') else: request.add_header('Accept-encoding', '') if auth: request.add_header('Authorization', 'Basic %s' % auth) if ACCEPT_HEADER: request.add_header('Accept', ACCEPT_HEADER) request.add_header('A-IM', 'feed') # RFC 3229 support opener = apply(urllib2.build_opener, tuple([_FeedURLHandler()] + handlers)) opener.addheaders = [] # RMK - must clear so we only send our custom User-Agent try: return opener.open(request) finally: opener.close() # JohnD # try to open with native open function (if url_file_stream_or_string is a filename) try: return open(url_file_stream_or_string) except: pass # treat url_file_stream_or_string as string return _StringIO(str(url_file_stream_or_string)) _date_handlers = [] def registerDateHandler(func): """Register a date handler function (takes string, returns 9-tuple date in GMT)""" _date_handlers.insert(0, func) # ISO-8601 date parsing routines written by Fazal Majid. # The ISO 8601 standard is very convoluted and irregular - a full ISO 8601 # parser is beyond the scope of feedparser and would be a worthwhile addition # to the Python library. # A single regular expression cannot parse ISO 8601 date formats into groups # as the standard is highly irregular (for instance is 030104 2003-01-04 or # 0301-04-01), so we use templates instead. # Please note the order in templates is significant because we need a # greedy match. _iso8601_tmpl = [ 'YYYY-?MM-?DD', 'YYYY-MM', 'YYYY-?OOO', 'YY-?MM-?DD', 'YY-?OOO', 'YYYY', '-YY-?MM', '-OOO', '-YY', '--MM-?DD', '--MM', '---DD', 'CC', '', ] _iso8601_re = [tmpl.replace('YYYY', r'(?P<year>\d{4})').replace('YY', r'(?P<year>\d\d)').replace('MM', r'(?P<month>[01]\d)' ).replace('DD', r'(?P<day>[0123]\d)').replace('OOO', r'(?P<ordinal>[0123]\d\d)').replace('CC', r'(?P<century>\d\d$)') + r'(T?(?P<hour>\d{2}):(?P<minute>\d{2})' + r'(:(?P<second>\d{2}))?' + r'(?P<tz>[+-](?P<tzhour>\d{2})(:(?P<tzmin>\d{2}))?|Z)?)?' for tmpl in _iso8601_tmpl] del tmpl _iso8601_matches = [re.compile(regex).match for regex in _iso8601_re] del regex def _parse_date_iso8601(dateString): """Parse a variety of ISO-8601-compatible formats like 20040105""" m = None for _iso8601_match in _iso8601_matches: m = _iso8601_match(dateString) if m: break if not m: return if m.span() == (0, 0): return params = m.groupdict() ordinal = params.get('ordinal', 0) if ordinal: ordinal = int(ordinal) else: ordinal = 0 year = params.get('year', '--') if not year or year == '--': year = time.gmtime()[0] elif len(year) == 2: # ISO 8601 assumes current century, i.e. 93 -> 2093, NOT 1993 year = 100 * int(time.gmtime()[0] / 100) + int(year) else: year = int(year) month = params.get('month', '-') if not month or month == '-': # ordinals are NOT normalized by mktime, we simulate them # by setting month=1, day=ordinal if ordinal: month = 1 else: month = time.gmtime()[1] month = int(month) day = params.get('day', 0) if not day: # see above if ordinal: day = ordinal elif params.get('century', 0) or params.get('year', 0)\ or params.get('month', 0): day = 1 else: day = time.gmtime()[2] else: day = int(day) # special case of the century - is the first year of the 21st century # 2000 or 2001 ? The debate goes on... if 'century' in params.keys(): year = (int(params['century']) - 1) * 100 + 1 # in ISO 8601 most fields are optional for field in ['hour', 'minute', 'second', 'tzhour', 'tzmin']: if not params.get(field, None): params[field] = 0 hour = int(params.get('hour', 0)) minute = int(params.get('minute', 0)) second = int(params.get('second', 0)) # weekday is normalized by mktime(), we can ignore it weekday = 0 # daylight savings is complex, but not needed for feedparser's purposes # as time zones, if specified, include mention of whether it is active # (e.g. PST vs. PDT, CET). Using -1 is implementation-dependent and # and most implementations have DST bugs daylight_savings_flag = 0 tm = [ year, month, day, hour, minute, second, weekday, ordinal, daylight_savings_flag, ] # ISO 8601 time zone adjustments tz = params.get('tz') if tz and tz != 'Z': if tz[0] == '-': tm[3] += int(params.get('tzhour', 0)) tm[4] += int(params.get('tzmin', 0)) elif tz[0] == '+': tm[3] -= int(params.get('tzhour', 0)) tm[4] -= int(params.get('tzmin', 0)) else: return None # Python's time.mktime() is a wrapper around the ANSI C mktime(3c) # which is guaranteed to normalize d/m/y/h/m/s. # Many implementations have bugs, but we'll pretend they don't. return time.localtime(time.mktime(tm)) registerDateHandler(_parse_date_iso8601) # 8-bit date handling routines written by ytrewq1. _korean_year = u'\ub144' # b3e2 in euc-kr _korean_month = u'\uc6d4' # bff9 in euc-kr _korean_day = u'\uc77c' # c0cf in euc-kr _korean_am = u'\uc624\uc804' # bfc0 c0fc in euc-kr _korean_pm = u'\uc624\ud6c4' # bfc0 c8c4 in euc-kr _korean_onblog_date_re = \ re.compile('(\d{4})%s\s+(\d{2})%s\s+(\d{2})%s\s+(\d{2}):(\d{2}):(\d{2})' % (_korean_year, _korean_month, _korean_day)) _korean_nate_date_re = \ re.compile(u'(\d{4})-(\d{2})-(\d{2})\s+(%s|%s)\s+(\d{,2}):(\d{,2}):(\d{,2})' % (_korean_am, _korean_pm)) def _parse_date_onblog(dateString): """Parse a string according to the OnBlog 8-bit date format""" m = _korean_onblog_date_re.match(dateString) if not m: return w3dtfdate = \ '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s:%(second)s%(zonediff)s'\ % { 'year': m.group(1), 'month': m.group(2), 'day': m.group(3), 'hour': m.group(4), 'minute': m.group(5), 'second': m.group(6), 'zonediff': '+09:00', } if _debug: sys.stderr.write('OnBlog date parsed as: %s\n' % w3dtfdate) return _parse_date_w3dtf(w3dtfdate) registerDateHandler(_parse_date_onblog) def _parse_date_nate(dateString): """Parse a string according to the Nate 8-bit date format""" m = _korean_nate_date_re.match(dateString) if not m: return hour = int(m.group(5)) ampm = m.group(4) if ampm == _korean_pm: hour += 12 hour = str(hour) if len(hour) == 1: hour = '0' + hour w3dtfdate = \ '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s:%(second)s%(zonediff)s'\ % { 'year': m.group(1), 'month': m.group(2), 'day': m.group(3), 'hour': hour, 'minute': m.group(6), 'second': m.group(7), 'zonediff': '+09:00', } if _debug: sys.stderr.write('Nate date parsed as: %s\n' % w3dtfdate) return _parse_date_w3dtf(w3dtfdate) registerDateHandler(_parse_date_nate) _mssql_date_re = \ re.compile('(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(\.\d+)?' ) def _parse_date_mssql(dateString): """Parse a string according to the MS SQL date format""" m = _mssql_date_re.match(dateString) if not m: return w3dtfdate = \ '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s:%(second)s%(zonediff)s'\ % { 'year': m.group(1), 'month': m.group(2), 'day': m.group(3), 'hour': m.group(4), 'minute': m.group(5), 'second': m.group(6), 'zonediff': '+09:00', } if _debug: sys.stderr.write('MS SQL date parsed as: %s\n' % w3dtfdate) return _parse_date_w3dtf(w3dtfdate) registerDateHandler(_parse_date_mssql) # Unicode strings for Greek date strings _greek_months = { u'\u0399\u03b1\u03bd': u'Jan', u'\u03a6\u03b5\u03b2': u'Feb', u'\u039c\u03ac\u03ce': u'Mar', u'\u039c\u03b1\u03ce': u'Mar', u'\u0391\u03c0\u03c1': u'Apr', u'\u039c\u03ac\u03b9': u'May', u'\u039c\u03b1\u03ca': u'May', u'\u039c\u03b1\u03b9': u'May', u'\u0399\u03bf\u03cd\u03bd': u'Jun', u'\u0399\u03bf\u03bd': u'Jun', u'\u0399\u03bf\u03cd\u03bb': u'Jul', u'\u0399\u03bf\u03bb': u'Jul', u'\u0391\u03cd\u03b3': u'Aug', u'\u0391\u03c5\u03b3': u'Aug', u'\u03a3\u03b5\u03c0': u'Sep', u'\u039f\u03ba\u03c4': u'Oct', u'\u039d\u03bf\u03ad': u'Nov', u'\u039d\u03bf\u03b5': u'Nov', u'\u0394\u03b5\u03ba': u'Dec', } _greek_wdays = { u'\u039a\u03c5\u03c1': u'Sun', u'\u0394\u03b5\u03c5': u'Mon', u'\u03a4\u03c1\u03b9': u'Tue', u'\u03a4\u03b5\u03c4': u'Wed', u'\u03a0\u03b5\u03bc': u'Thu', u'\u03a0\u03b1\u03c1': u'Fri', u'\u03a3\u03b1\u03b2': u'Sat', } _greek_date_format_re = \ re.compile(u'([^,]+),\s+(\d{2})\s+([^\s]+)\s+(\d{4})\s+(\d{2}):(\d{2}):(\d{2})\s+([^\s]+)' ) def _parse_date_greek(dateString): """Parse a string according to a Greek 8-bit date format.""" m = _greek_date_format_re.match(dateString) if not m: return try: wday = _greek_wdays[m.group(1)] month = _greek_months[m.group(3)] except: return rfc822date = \ '%(wday)s, %(day)s %(month)s %(year)s %(hour)s:%(minute)s:%(second)s %(zonediff)s'\ % { 'wday': wday, 'day': m.group(2), 'month': month, 'year': m.group(4), 'hour': m.group(5), 'minute': m.group(6), 'second': m.group(7), 'zonediff': m.group(8), } if _debug: sys.stderr.write('Greek date parsed as: %s\n' % rfc822date) return _parse_date_rfc822(rfc822date) registerDateHandler(_parse_date_greek) # Unicode strings for Hungarian date strings _hungarian_months = { u'janu\u00e1r': u'01', u'febru\u00e1ri': u'02', u'm\u00e1rcius': u'03', u'\u00e1prilis': u'04', u'm\u00e1ujus': u'05', u'j\u00fanius': u'06', u'j\u00falius': u'07', u'augusztus': u'08', u'szeptember': u'09', u'okt\u00f3ber': u'10', u'november': u'11', u'december': u'12', } _hungarian_date_format_re = \ re.compile(u'(\d{4})-([^-]+)-(\d{,2})T(\d{,2}):(\d{2})((\+|-)(\d{,2}:\d{2}))' ) def _parse_date_hungarian(dateString): """Parse a string according to a Hungarian 8-bit date format.""" m = _hungarian_date_format_re.match(dateString) if not m: return try: month = _hungarian_months[m.group(2)] day = m.group(3) if len(day) == 1: day = '0' + day hour = m.group(4) if len(hour) == 1: hour = '0' + hour except: return w3dtfdate = \ '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s%(zonediff)s' % { 'year': m.group(1), 'month': month, 'day': day, 'hour': hour, 'minute': m.group(5), 'zonediff': m.group(6), } if _debug: sys.stderr.write('Hungarian date parsed as: %s\n' % w3dtfdate) return _parse_date_w3dtf(w3dtfdate) registerDateHandler(_parse_date_hungarian) # W3DTF-style date parsing adapted from PyXML xml.utils.iso8601, written by # Drake and licensed under the Python license. Removed all range checking # for month, day, hour, minute, and second, since mktime will normalize # these later def _parse_date_w3dtf(dateString): def __extract_date(m): year = int(m.group('year')) if year < 100: year = 100 * int(time.gmtime()[0] / 100) + int(year) if year < 1000: return (0, 0, 0) julian = m.group('julian') if julian: julian = int(julian) month = julian / 30 + 1 day = julian % 30 + 1 jday = None while jday != julian: t = time.mktime(( year, month, day, 0, 0, 0, 0, 0, 0, )) jday = time.gmtime(t)[-2] diff = abs(jday - julian) if jday > julian: if diff < day: day = day - diff else: month = month - 1 day = 31 elif jday < julian: if day + diff < 28: day = day + diff else: month = month + 1 return (year, month, day) month = m.group('month') day = 1 if month is None: month = 1 else: month = int(month) day = m.group('day') if day: day = int(day) else: day = 1 return (year, month, day) def __extract_time(m): if not m: return (0, 0, 0) hours = m.group('hours') if not hours: return (0, 0, 0) hours = int(hours) minutes = int(m.group('minutes')) seconds = m.group('seconds') if seconds: seconds = int(seconds) else: seconds = 0 return (hours, minutes, seconds) def __extract_tzd(m): """Return the Time Zone Designator as an offset in seconds from UTC.""" if not m: return 0 tzd = m.group('tzd') if not tzd: return 0 if tzd == 'Z': return 0 hours = int(m.group('tzdhours')) minutes = m.group('tzdminutes') if minutes: minutes = int(minutes) else: minutes = 0 offset = (hours * 60 + minutes) * 60 if tzd[0] == '+': return -offset return offset __date_re = \ '(?P<year>\\d\\d\\d\\d)(?:(?P<dsep>-|)(?:(?P<julian>\\d\\d\\d)|(?P<month>\\d\\d)(?:(?P=dsep)(?P<day>\\d\\d))?))?' __tzd_re = \ '(?P<tzd>[-+](?P<tzdhours>\d\d)(?::?(?P<tzdminutes>\d\d))|Z)' __tzd_rx = re.compile(__tzd_re) __time_re = \ '(?P<hours>\\d\\d)(?P<tsep>:|)(?P<minutes>\\d\\d)(?:(?P=tsep)(?P<seconds>\\d\\d(?:[.,]\\d+)?))?'\ + __tzd_re __datetime_re = '%s(?:T%s)?' % (__date_re, __time_re) __datetime_rx = re.compile(__datetime_re) m = __datetime_rx.match(dateString) if m is None or m.group() != dateString: return gmt = __extract_date(m) + __extract_time(m) + (0, 0, 0) if gmt[0] == 0: return return time.gmtime((time.mktime(gmt) + __extract_tzd(m)) - time.timezone) registerDateHandler(_parse_date_w3dtf) def _parse_date_rfc822(dateString): """Parse an RFC822, RFC1123, RFC2822, or asctime-style date""" data = dateString.split() if data[0][-1] in (',', '.') or data[0].lower() in rfc822._daynames: del data[0] if len(data) == 4: s = data[3] i = s.find('+') if i > 0: data[3:] = [s[:i], s[i + 1:]] else: data.append('') dateString = ' '.join(data) if len(data) < 5: dateString += ' 00:00:00 GMT' tm = rfc822.parsedate_tz(dateString) if tm: return time.gmtime(rfc822.mktime_tz(tm)) # rfc822.py defines several time zones, but we define some extra ones. # 'ET' is equivalent to 'EST', etc. _additional_timezones = { 'AT': -400, 'ET': -500, 'CT': -600, 'MT': -700, 'PT': -800, } rfc822._timezones.update(_additional_timezones) registerDateHandler(_parse_date_rfc822) def _parse_date(dateString): """Parses a variety of date formats into a 9-tuple in GMT""" for handler in _date_handlers: try: date9tuple = handler(dateString) if not date9tuple: continue if len(date9tuple) != 9: if _debug: sys.stderr.write('date handler function must return 9-tuple\n' ) raise ValueError, 'date handler function must return 9-tuple' map(int, date9tuple) return date9tuple except Exception, e: if _debug: sys.stderr.write('%s raised %s\n' % (handler.__name__, repr(e))) pass return None def _getCharacterEncoding(http_headers, xml_data): """Get the character encoding of the XML document http_headers is a dictionary xml_data is a raw string (not Unicode) This is so much trickier than it sounds, it's not even funny. According to RFC 3023 ('XML Media Types'), if the HTTP Content-Type is application/xml, application/*+xml, application/xml-external-parsed-entity, or application/xml-dtd, the encoding given in the charset parameter of the HTTP Content-Type takes precedence over the encoding given in the XML prefix within the document, and defaults to 'utf-8' if neither are specified. But, if the HTTP Content-Type is text/xml, text/*+xml, or text/xml-external-parsed-entity, the encoding given in the XML prefix within the document is ALWAYS IGNORED and only the encoding given in the charset parameter of the HTTP Content-Type header should be respected, and it defaults to 'us-ascii' if not specified. Furthermore, discussion on the atom-syntax mailing list with the author of RFC 3023 leads me to the conclusion that any document served with a Content-Type of text/* and no charset parameter must be treated as us-ascii. (We now do this.) And also that it must always be flagged as non-well-formed. (We now do this too.) If Content-Type is unspecified (input was local file or non-HTTP source) or unrecognized (server just got it totally wrong), then go by the encoding given in the XML prefix of the document and default to 'iso-8859-1' as per the HTTP specification (RFC 2616). Then, assuming we didn't find a character encoding in the HTTP headers (and the HTTP Content-type allowed us to look in the body), we need to sniff the first few bytes of the XML data and try to determine whether the encoding is ASCII-compatible. Section F of the XML specification shows the way here: http://www.w3.org/TR/REC-xml/#sec-guessing-no-ext-info If the sniffed encoding is not ASCII-compatible, we need to make it ASCII compatible so that we can sniff further into the XML declaration to find the encoding attribute, which will tell us the true encoding. Of course, none of this guarantees that we will be able to parse the feed in the declared character encoding (assuming it was declared correctly, which many are not). CJKCodecs and iconv_codec help a lot; you should definitely install them if you can. http://cjkpython.i18n.org/ """ def _parseHTTPContentType(content_type): """takes HTTP Content-Type header and returns (content type, charset) If no charset is specified, returns (content type, '') If no content type is specified, returns ('', '') Both return parameters are guaranteed to be lowercase strings """ content_type = content_type or '' (content_type, params) = cgi.parse_header(content_type) return (content_type, params.get('charset', '').replace("'", '' )) sniffed_xml_encoding = '' xml_encoding = '' true_encoding = '' (http_content_type, http_encoding) = \ _parseHTTPContentType(http_headers.get('content-type')) # Must sniff for non-ASCII-compatible character encodings before # searching for XML declaration. This heuristic is defined in # section F of the XML specification: # http://www.w3.org/TR/REC-xml/#sec-guessing-no-ext-info try: if xml_data[:4] == '\x4c\x6f\xa7\x94': # EBCDIC xml_data = _ebcdic_to_ascii(xml_data) elif xml_data[:4] == '\x00\x3c\x00\x3f': # UTF-16BE sniffed_xml_encoding = 'utf-16be' xml_data = unicode(xml_data, 'utf-16be').encode('utf-8') elif len(xml_data) >= 4 and xml_data[:2] == '\xfe\xff'\ and xml_data[2:4] != '\x00\x00': # UTF-16BE with BOM sniffed_xml_encoding = 'utf-16be' xml_data = unicode(xml_data[2:], 'utf-16be').encode('utf-8') elif xml_data[:4] == '\x3c\x00\x3f\x00': # UTF-16LE sniffed_xml_encoding = 'utf-16le' xml_data = unicode(xml_data, 'utf-16le').encode('utf-8') elif len(xml_data) >= 4 and xml_data[:2] == '\xff\xfe'\ and xml_data[2:4] != '\x00\x00': # UTF-16LE with BOM sniffed_xml_encoding = 'utf-16le' xml_data = unicode(xml_data[2:], 'utf-16le').encode('utf-8') elif xml_data[:4] == '\x00\x00\x00\x3c': # UTF-32BE sniffed_xml_encoding = 'utf-32be' xml_data = unicode(xml_data, 'utf-32be').encode('utf-8') elif xml_data[:4] == '\x3c\x00\x00\x00': # UTF-32LE sniffed_xml_encoding = 'utf-32le' xml_data = unicode(xml_data, 'utf-32le').encode('utf-8') elif xml_data[:4] == '\x00\x00\xfe\xff': # UTF-32BE with BOM sniffed_xml_encoding = 'utf-32be' xml_data = unicode(xml_data[4:], 'utf-32be').encode('utf-8') elif xml_data[:4] == '\xff\xfe\x00\x00': # UTF-32LE with BOM sniffed_xml_encoding = 'utf-32le' xml_data = unicode(xml_data[4:], 'utf-32le').encode('utf-8') elif xml_data[:3] == '\xef\xbb\xbf': # UTF-8 with BOM sniffed_xml_encoding = 'utf-8' xml_data = unicode(xml_data[3:], 'utf-8').encode('utf-8') else: # ASCII-compatible pass xml_encoding_match = \ re.compile('^<\?.*encoding=[\'"](.*?)[\'"].*\?>' ).match(xml_data) except: xml_encoding_match = None if xml_encoding_match: xml_encoding = xml_encoding_match.groups()[0].lower() if sniffed_xml_encoding and xml_encoding in ( 'iso-10646-ucs-2', 'ucs-2', 'csunicode', 'iso-10646-ucs-4', 'ucs-4', 'csucs4', 'utf-16', 'utf-32', 'utf_16', 'utf_32', 'utf16', 'u16', ): xml_encoding = sniffed_xml_encoding acceptable_content_type = 0 application_content_types = ('application/xml', 'application/xml-dtd', 'application/xml-external-parsed-entity' ) text_content_types = ('text/xml', 'text/xml-external-parsed-entity') if http_content_type in application_content_types\ or http_content_type.startswith('application/')\ and http_content_type.endswith('+xml'): acceptable_content_type = 1 true_encoding = http_encoding or xml_encoding or 'utf-8' elif http_content_type in text_content_types\ or http_content_type.startswith('text/')\ and http_content_type.endswith('+xml'): acceptable_content_type = 1 true_encoding = http_encoding or 'us-ascii' elif http_content_type.startswith('text/'): true_encoding = http_encoding or 'us-ascii' elif http_headers and not http_headers.has_key('content-type'): true_encoding = xml_encoding or 'iso-8859-1' else: true_encoding = xml_encoding or 'utf-8' return (true_encoding, http_encoding, xml_encoding, sniffed_xml_encoding, acceptable_content_type) def _toUTF8(data, encoding): """Changes an XML data stream on the fly to specify a new encoding data is a raw sequence of bytes (not Unicode) that is presumed to be in %encoding already encoding is a string recognized by encodings.aliases """ if _debug: sys.stderr.write('entering _toUTF8, trying encoding %s\n' % encoding) # strip Byte Order Mark (if present) if len(data) >= 4 and data[:2] == '\xfe\xff' and data[2:4]\ != '\x00\x00': if _debug: sys.stderr.write('stripping BOM\n') if encoding != 'utf-16be': sys.stderr.write('trying utf-16be instead\n') encoding = 'utf-16be' data = data[2:] elif len(data) >= 4 and data[:2] == '\xff\xfe' and data[2:4]\ != '\x00\x00': if _debug: sys.stderr.write('stripping BOM\n') if encoding != 'utf-16le': sys.stderr.write('trying utf-16le instead\n') encoding = 'utf-16le' data = data[2:] elif data[:3] == '\xef\xbb\xbf': if _debug: sys.stderr.write('stripping BOM\n') if encoding != 'utf-8': sys.stderr.write('trying utf-8 instead\n') encoding = 'utf-8' data = data[3:] elif data[:4] == '\x00\x00\xfe\xff': if _debug: sys.stderr.write('stripping BOM\n') if encoding != 'utf-32be': sys.stderr.write('trying utf-32be instead\n') encoding = 'utf-32be' data = data[4:] elif data[:4] == '\xff\xfe\x00\x00': if _debug: sys.stderr.write('stripping BOM\n') if encoding != 'utf-32le': sys.stderr.write('trying utf-32le instead\n') encoding = 'utf-32le' data = data[4:] newdata = unicode(data, encoding) if _debug: sys.stderr.write('successfully converted %s data to unicode\n' % encoding) declmatch = re.compile('^<\?xml[^>]*?>') newdecl = '''<?xml version='1.0' encoding='utf-8'?>''' if declmatch.search(newdata): newdata = declmatch.sub(newdecl, newdata) else: newdata = newdecl + u'\n' + newdata return newdata.encode('utf-8') def _stripDoctype(data): """Strips DOCTYPE from XML document, returns (rss_version, stripped_data) rss_version may be 'rss091n' or None stripped_data is the same XML document, minus the DOCTYPE """ entity_pattern = re.compile(r'<!ENTITY([^>]*?)>', re.MULTILINE) data = entity_pattern.sub('', data) doctype_pattern = re.compile(r'<!DOCTYPE([^>]*?)>', re.MULTILINE) doctype_results = doctype_pattern.findall(data) doctype = doctype_results and doctype_results[0] or '' if doctype.lower().count('netscape'): version = 'rss091n' else: version = None data = doctype_pattern.sub('', data) return (version, data) def parse( url_file_stream_or_string, etag=None, modified=None, agent=None, referrer=None, handlers=[], ): """Parse a feed from a URL, file, stream, or string""" result = FeedParserDict() result['feed'] = FeedParserDict() result['entries'] = [] if _XML_AVAILABLE: result['bozo'] = 0 if type(handlers) == types.InstanceType: handlers = [handlers] try: f = _open_resource( url_file_stream_or_string, etag, modified, agent, referrer, handlers, ) data = f.read() except Exception, e: result['bozo'] = 1 result['bozo_exception'] = e data = '' f = None # if feed is gzip-compressed, decompress it if f and data and hasattr(f, 'headers'): if gzip and f.headers.get('content-encoding', '') == 'gzip': try: data = gzip.GzipFile(fileobj=_StringIO(data)).read() except Exception, e: # Some feeds claim to be gzipped but they're not, so # we get garbage. Ideally, we should re-request the # feed without the 'Accept-encoding: gzip' header, # but we don't. result['bozo'] = 1 result['bozo_exception'] = e data = '' elif zlib and f.headers.get('content-encoding', '')\ == 'deflate': try: data = zlib.decompress(data, -zlib.MAX_WBITS) except Exception, e: result['bozo'] = 1 result['bozo_exception'] = e data = '' # save HTTP headers if hasattr(f, 'info'): info = f.info() result['etag'] = info.getheader('ETag') last_modified = info.getheader('Last-Modified') if last_modified: result['modified'] = _parse_date(last_modified) if hasattr(f, 'url'): result['href'] = f.url result['status'] = 200 if hasattr(f, 'status'): result['status'] = f.status if hasattr(f, 'headers'): result['headers'] = f.headers.dict if hasattr(f, 'close'): f.close() # there are four encodings to keep track of: # - http_encoding is the encoding declared in the Content-Type HTTP header # - xml_encoding is the encoding declared in the <?xml declaration # - sniffed_encoding is the encoding sniffed from the first 4 bytes of the XML data # - result['encoding'] is the actual encoding, as per RFC 3023 and a variety of other conflicting specifications http_headers = result.get('headers', {}) (result['encoding'], http_encoding, xml_encoding, sniffed_xml_encoding, acceptable_content_type) = \ _getCharacterEncoding(http_headers, data) if http_headers and not acceptable_content_type: if http_headers.has_key('content-type'): bozo_message = '%s is not an XML media type'\ % http_headers['content-type'] else: bozo_message = 'no Content-type specified' result['bozo'] = 1 result['bozo_exception'] = NonXMLContentType(bozo_message) (result['version'], data) = _stripDoctype(data) baseuri = http_headers.get('content-location', result.get('href')) baselang = http_headers.get('content-language', None) # if server sent 304, we're done if result.get('status', 0) == 304: result['version'] = '' result['debug_message'] = \ 'The feed has not changed since you last checked, '\ + 'so the server sent no data. This is a feature, not a bug!' return result # if there was a problem downloading, we're done if not data: return result # determine character encoding use_strict_parser = 0 known_encoding = 0 tried_encodings = [] # try: HTTP encoding, declared XML encoding, encoding sniffed from BOM for proposed_encoding in (result['encoding'], xml_encoding, sniffed_xml_encoding): if not proposed_encoding: continue if proposed_encoding in tried_encodings: continue tried_encodings.append(proposed_encoding) try: data = _toUTF8(data, proposed_encoding) known_encoding = use_strict_parser = 1 break except: pass # if no luck and we have auto-detection library, try that if not known_encoding and chardet: try: proposed_encoding = chardet.detect(data)['encoding'] if proposed_encoding and proposed_encoding\ not in tried_encodings: tried_encodings.append(proposed_encoding) data = _toUTF8(data, proposed_encoding) known_encoding = use_strict_parser = 1 except: pass # if still no luck and we haven't tried utf-8 yet, try that if not known_encoding and 'utf-8' not in tried_encodings: try: proposed_encoding = 'utf-8' tried_encodings.append(proposed_encoding) data = _toUTF8(data, proposed_encoding) known_encoding = use_strict_parser = 1 except: pass # if still no luck and we haven't tried windows-1252 yet, try that if not known_encoding and 'windows-1252' not in tried_encodings: try: proposed_encoding = 'windows-1252' tried_encodings.append(proposed_encoding) data = _toUTF8(data, proposed_encoding) known_encoding = use_strict_parser = 1 except: pass # if still no luck, give up if not known_encoding: result['bozo'] = 1 result['bozo_exception'] = \ CharacterEncodingUnknown('document encoding unknown, I tried ' + '%s, %s, utf-8, and windows-1252 but nothing worked' % (result['encoding'], xml_encoding)) result['encoding'] = '' elif proposed_encoding != result['encoding']: result['bozo'] = 1 result['bozo_exception'] = \ CharacterEncodingOverride('documented declared as %s, but parsed as %s' % (result['encoding'], proposed_encoding)) result['encoding'] = proposed_encoding if not _XML_AVAILABLE: use_strict_parser = 0 if use_strict_parser: # initialize the SAX parser feedparser = _StrictFeedParser(baseuri, baselang, 'utf-8') saxparser = xml.sax.make_parser(PREFERRED_XML_PARSERS) saxparser.setFeature(xml.sax.handler.feature_namespaces, 1) saxparser.setContentHandler(feedparser) saxparser.setErrorHandler(feedparser) source = xml.sax.xmlreader.InputSource() source.setByteStream(_StringIO(data)) if hasattr(saxparser, '_ns_stack'): # work around bug in built-in SAX parser (doesn't recognize xml: namespace) # PyXML doesn't have this problem, and it doesn't have _ns_stack either saxparser._ns_stack.append({'http://www.w3.org/XML/1998/namespace' : 'xml'}) try: saxparser.parse(source) except Exception, e: if _debug: import traceback traceback.print_stack() traceback.print_exc() sys.stderr.write('xml parsing failed\n') result['bozo'] = 1 result['bozo_exception'] = feedparser.exc or e use_strict_parser = 0 if not use_strict_parser: feedparser = _LooseFeedParser(baseuri, baselang, known_encoding and 'utf-8' or '') feedparser.feed(data) result['feed'] = feedparser.feeddata result['entries'] = feedparser.entries result['version'] = result['version'] or feedparser.version result['namespaces'] = feedparser.namespacesInUse return result if __name__ == '__main__': if not sys.argv[1:]: print __doc__ sys.exit(0) else: urls = sys.argv[1:] zopeCompatibilityHack() from pprint import pprint for url in urls: print url print result = parse(url) pprint(result) print # REVISION HISTORY # 1.0 - 9/27/2002 - MAP - fixed namespace processing on prefixed RSS 2.0 elements, # added Simon Fell's test suite # 1.1 - 9/29/2002 - MAP - fixed infinite loop on incomplete CDATA sections # 2.0 - 10/19/2002 # JD - use inchannel to watch out for image and textinput elements which can # also contain title, link, and description elements # JD - check for isPermaLink='false' attribute on guid elements # JD - replaced openAnything with open_resource supporting ETag and # If-Modified-Since request headers # JD - parse now accepts etag, modified, agent, and referrer optional # arguments # JD - modified parse to return a dictionary instead of a tuple so that any # etag or modified information can be returned and cached by the caller # 2.0.1 - 10/21/2002 - MAP - changed parse() so that if we don't get anything # because of etag/modified, return the old etag/modified to the caller to # indicate why nothing is being returned # 2.0.2 - 10/21/2002 - JB - added the inchannel to the if statement, otherwise its # useless. Fixes the problem JD was addressing by adding it. # 2.1 - 11/14/2002 - MAP - added gzip support # 2.2 - 1/27/2003 - MAP - added attribute support, admin:generatorAgent. # start_admingeneratoragent is an example of how to handle elements with # only attributes, no content. # 2.3 - 6/11/2003 - MAP - added USER_AGENT for default (if caller doesn't specify); # also, make sure we send the User-Agent even if urllib2 isn't available. # Match any variation of backend.userland.com/rss namespace. # 2.3.1 - 6/12/2003 - MAP - if item has both link and guid, return both as-is. # 2.4 - 7/9/2003 - MAP - added preliminary Pie/Atom/Echo support based on Sam Ruby's # snapshot of July 1 <http://www.intertwingly.net/blog/1506.html>; changed # project name # 2.5 - 7/25/2003 - MAP - changed to Python license (all contributors agree); # removed unnecessary urllib code -- urllib2 should always be available anyway; # return actual url, status, and full HTTP headers (as result['url'], # result['status'], and result['headers']) if parsing a remote feed over HTTP -- # this should pass all the HTTP tests at <http://diveintomark.org/tests/client/http/>; # added the latest namespace-of-the-week for RSS 2.0 # 2.5.1 - 7/26/2003 - RMK - clear opener.addheaders so we only send our custom # User-Agent (otherwise urllib2 sends two, which confuses some servers) # 2.5.2 - 7/28/2003 - MAP - entity-decode inline xml properly; added support for # inline <xhtml:body> and <xhtml:div> as used in some RSS 2.0 feeds # 2.5.3 - 8/6/2003 - TvdV - patch to track whether we're inside an image or # textInput, and also to return the character encoding (if specified) # 2.6 - 1/1/2004 - MAP - dc:author support (MarekK); fixed bug tracking # nested divs within content (JohnD); fixed missing sys import (JohanS); # fixed regular expression to capture XML character encoding (Andrei); # added support for Atom 0.3-style links; fixed bug with textInput tracking; # added support for cloud (MartijnP); added support for multiple # category/dc:subject (MartijnP); normalize content model: 'description' gets # description (which can come from description, summary, or full content if no # description), 'content' gets dict of base/language/type/value (which can come # from content:encoded, xhtml:body, content, or fullitem); # fixed bug matching arbitrary Userland namespaces; added xml:base and xml:lang # tracking; fixed bug tracking unknown tags; fixed bug tracking content when # <content> element is not in default namespace (like Pocketsoap feed); # resolve relative URLs in link, guid, docs, url, comments, wfw:comment, # wfw:commentRSS; resolve relative URLs within embedded HTML markup in # description, xhtml:body, content, content:encoded, title, subtitle, # summary, info, tagline, and copyright; added support for pingback and # trackback namespaces # 2.7 - 1/5/2004 - MAP - really added support for trackback and pingback # namespaces, as opposed to 2.6 when I said I did but didn't really; # sanitize HTML markup within some elements; added mxTidy support (if # installed) to tidy HTML markup within some elements; fixed indentation # bug in _parse_date (FazalM); use socket.setdefaulttimeout if available # (FazalM); universal date parsing and normalization (FazalM): 'created', modified', # 'issued' are parsed into 9-tuple date format and stored in 'created_parsed', # 'modified_parsed', and 'issued_parsed'; 'date' is duplicated in 'modified' # and vice-versa; 'date_parsed' is duplicated in 'modified_parsed' and vice-versa # 2.7.1 - 1/9/2004 - MAP - fixed bug handling &quot; and &apos;. fixed memory # leak not closing url opener (JohnD); added dc:publisher support (MarekK); # added admin:errorReportsTo support (MarekK); Python 2.1 dict support (MarekK) # 2.7.4 - 1/14/2004 - MAP - added workaround for improperly formed <br/> tags in # encoded HTML (skadz); fixed unicode handling in normalize_attrs (ChrisL); # fixed relative URI processing for guid (skadz); added ICBM support; added # base64 support # 2.7.5 - 1/15/2004 - MAP - added workaround for malformed DOCTYPE (seen on many # blogspot.com sites); added _debug variable # 2.7.6 - 1/16/2004 - MAP - fixed bug with StringIO importing # 3.0b3 - 1/23/2004 - MAP - parse entire feed with real XML parser (if available); # added several new supported namespaces; fixed bug tracking naked markup in # description; added support for enclosure; added support for source; re-added # support for cloud which got dropped somehow; added support for expirationDate # 3.0b4 - 1/26/2004 - MAP - fixed xml:lang inheritance; fixed multiple bugs tracking # xml:base URI, one for documents that don't define one explicitly and one for # documents that define an outer and an inner xml:base that goes out of scope # before the end of the document # 3.0b5 - 1/26/2004 - MAP - fixed bug parsing multiple links at feed level # 3.0b6 - 1/27/2004 - MAP - added feed type and version detection, result['version'] # will be one of SUPPORTED_VERSIONS.keys() or empty string if unrecognized; # added support for creativeCommons:license and cc:license; added support for # full Atom content model in title, tagline, info, copyright, summary; fixed bug # with gzip encoding (not always telling server we support it when we do) # 3.0b7 - 1/28/2004 - MAP - support Atom-style author element in author_detail # (dictionary of 'name', 'url', 'email'); map author to author_detail if author # contains name + email address # 3.0b8 - 1/28/2004 - MAP - added support for contributor # 3.0b9 - 1/29/2004 - MAP - fixed check for presence of dict function; added # support for summary # 3.0b10 - 1/31/2004 - MAP - incorporated ISO-8601 date parsing routines from # xml.util.iso8601 # 3.0b11 - 2/2/2004 - MAP - added 'rights' to list of elements that can contain # dangerous markup; fiddled with decodeEntities (not right); liberalized # date parsing even further # 3.0b12 - 2/6/2004 - MAP - fiddled with decodeEntities (still not right); # added support to Atom 0.2 subtitle; added support for Atom content model # in copyright; better sanitizing of dangerous HTML elements with end tags # (script, frameset) # 3.0b13 - 2/8/2004 - MAP - better handling of empty HTML tags (br, hr, img, # etc.) in embedded markup, in either HTML or XHTML form (<br>, <br/>, <br />) # 3.0b14 - 2/8/2004 - MAP - fixed CDATA handling in non-wellformed feeds under # Python 2.1 # 3.0b15 - 2/11/2004 - MAP - fixed bug resolving relative links in wfw:commentRSS; # fixed bug capturing author and contributor URL; fixed bug resolving relative # links in author and contributor URL; fixed bug resolvin relative links in # generator URL; added support for recognizing RSS 1.0; passed Simon Fell's # namespace tests, and included them permanently in the test suite with his # permission; fixed namespace handling under Python 2.1 # 3.0b16 - 2/12/2004 - MAP - fixed support for RSS 0.90 (broken in b15) # 3.0b17 - 2/13/2004 - MAP - determine character encoding as per RFC 3023 # 3.0b18 - 2/17/2004 - MAP - always map description to summary_detail (Andrei); # use libxml2 (if available) # 3.0b19 - 3/15/2004 - MAP - fixed bug exploding author information when author # name was in parentheses; removed ultra-problematic mxTidy support; patch to # workaround crash in PyXML/expat when encountering invalid entities # (MarkMoraes); support for textinput/textInput # 3.0b20 - 4/7/2004 - MAP - added CDF support # 3.0b21 - 4/14/2004 - MAP - added Hot RSS support # 3.0b22 - 4/19/2004 - MAP - changed 'channel' to 'feed', 'item' to 'entries' in # results dict; changed results dict to allow getting values with results.key # as well as results[key]; work around embedded illformed HTML with half # a DOCTYPE; work around malformed Content-Type header; if character encoding # is wrong, try several common ones before falling back to regexes (if this # works, bozo_exception is set to CharacterEncodingOverride); fixed character # encoding issues in BaseHTMLProcessor by tracking encoding and converting # from Unicode to raw strings before feeding data to sgmllib.SGMLParser; # convert each value in results to Unicode (if possible), even if using # regex-based parsing # 3.0b23 - 4/21/2004 - MAP - fixed UnicodeDecodeError for feeds that contain # high-bit characters in attributes in embedded HTML in description (thanks # Thijs van de Vossen); moved guid, date, and date_parsed to mapped keys in # FeedParserDict; tweaked FeedParserDict.has_key to return True if asking # about a mapped key # 3.0fc1 - 4/23/2004 - MAP - made results.entries[0].links[0] and # results.entries[0].enclosures[0] into FeedParserDict; fixed typo that could # cause the same encoding to be tried twice (even if it failed the first time); # fixed DOCTYPE stripping when DOCTYPE contained entity declarations; # better textinput and image tracking in illformed RSS 1.0 feeds # 3.0fc2 - 5/10/2004 - MAP - added and passed Sam's amp tests; added and passed # my blink tag tests # 3.0fc3 - 6/18/2004 - MAP - fixed bug in _changeEncodingDeclaration that # failed to parse utf-16 encoded feeds; made source into a FeedParserDict; # duplicate admin:generatorAgent/@rdf:resource in generator_detail.url; # added support for image; refactored parse() fallback logic to try other # encodings if SAX parsing fails (previously it would only try other encodings # if re-encoding failed); remove unichr madness in normalize_attrs now that # we're properly tracking encoding in and out of BaseHTMLProcessor; set # feed.language from root-level xml:lang; set entry.id from rdf:about; # send Accept header # 3.0 - 6/21/2004 - MAP - don't try iso-8859-1 (can't distinguish between # iso-8859-1 and windows-1252 anyway, and most incorrectly marked feeds are # windows-1252); fixed regression that could cause the same encoding to be # tried twice (even if it failed the first time) # 3.0.1 - 6/22/2004 - MAP - default to us-ascii for all text/* content types; # recover from malformed content-type header parameter with no equals sign # ('text/xml; charset:iso-8859-1') # 3.1 - 6/28/2004 - MAP - added and passed tests for converting HTML entities # to Unicode equivalents in illformed feeds (aaronsw); added and # passed tests for converting character entities to Unicode equivalents # in illformed feeds (aaronsw); test for valid parsers when setting # XML_AVAILABLE; make version and encoding available when server returns # a 304; add handlers parameter to pass arbitrary urllib2 handlers (like # digest auth or proxy support); add code to parse username/password # out of url and send as basic authentication; expose downloading-related # exceptions in bozo_exception (aaronsw); added __contains__ method to # FeedParserDict (aaronsw); added publisher_detail (aaronsw) # 3.2 - 7/3/2004 - MAP - use cjkcodecs and iconv_codec if available; always # convert feed to UTF-8 before passing to XML parser; completely revamped # logic for determining character encoding and attempting XML parsing # (much faster); increased default timeout to 20 seconds; test for presence # of Location header on redirects; added tests for many alternate character # encodings; support various EBCDIC encodings; support UTF-16BE and # UTF16-LE with or without a BOM; support UTF-8 with a BOM; support # UTF-32BE and UTF-32LE with or without a BOM; fixed crashing bug if no # XML parsers are available; added support for 'Content-encoding: deflate'; # send blank 'Accept-encoding: ' header if neither gzip nor zlib modules # are available # 3.3 - 7/15/2004 - MAP - optimize EBCDIC to ASCII conversion; fix obscure # problem tracking xml:base and xml:lang if element declares it, child # doesn't, first grandchild redeclares it, and second grandchild doesn't; # refactored date parsing; defined public registerDateHandler so callers # can add support for additional date formats at runtime; added support # for OnBlog, Nate, MSSQL, Greek, and Hungarian dates (ytrewq1); added # zopeCompatibilityHack() which turns FeedParserDict into a regular # dictionary, required for Zope compatibility, and also makes command- # line debugging easier because pprint module formats real dictionaries # better than dictionary-like objects; added NonXMLContentType exception, # which is stored in bozo_exception when a feed is served with a non-XML # media type such as 'text/plain'; respect Content-Language as default # language if not xml:lang is present; cloud dict is now FeedParserDict; # generator dict is now FeedParserDict; better tracking of xml:lang, # including support for xml:lang='' to unset the current language; # recognize RSS 1.0 feeds even when RSS 1.0 namespace is not the default # namespace; don't overwrite final status on redirects (scenarios: # redirecting to a URL that returns 304, redirecting to a URL that # redirects to another URL with a different type of redirect); add # support for HTTP 303 redirects # 4.0 - MAP - support for relative URIs in xml:base attribute; fixed # encoding issue with mxTidy (phopkins); preliminary support for RFC 3229; # support for Atom 1.0; support for iTunes extensions; new 'tags' for # categories/keywords/etc. as array of dict # {'term': term, 'scheme': scheme, 'label': label} to match Atom 1.0 # terminology; parse RFC 822-style dates with no time; lots of other # bug fixes # 4.1 - MAP - removed socket timeout; added support for chardet library
Python
# Copyright (c) 2002, 2003, 2005, 2006 Allan Saddi <allan@saddi.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # $Id$ """ fcgi - a FastCGI/WSGI gateway. For more information about FastCGI, see <http://www.fastcgi.com/>. For more information about the Web Server Gateway Interface, see <http://www.python.org/peps/pep-0333.html>. Example usage: #!/usr/bin/env python from myapplication import app # Assume app is your WSGI application object from fcgi import WSGIServer WSGIServer(app).run() See the documentation for WSGIServer/Server for more information. On most platforms, fcgi will fallback to regular CGI behavior if run in a non-FastCGI context. If you want to force CGI behavior, set the environment variable FCGI_FORCE_CGI to "Y" or "y". """ __author__ = 'Allan Saddi <allan@saddi.com>' __version__ = '$Revision$' import sys import os import signal import struct import cStringIO as StringIO import select import socket import errno import traceback try: import thread import threading thread_available = True except ImportError: import dummy_thread as thread import dummy_threading as threading thread_available = False # Apparently 2.3 doesn't define SHUT_WR? Assume it is 1 in this case. if not hasattr(socket, 'SHUT_WR'): socket.SHUT_WR = 1 __all__ = ['WSGIServer'] # Constants from the spec. FCGI_LISTENSOCK_FILENO = 0 FCGI_HEADER_LEN = 8 FCGI_VERSION_1 = 1 FCGI_BEGIN_REQUEST = 1 FCGI_ABORT_REQUEST = 2 FCGI_END_REQUEST = 3 FCGI_PARAMS = 4 FCGI_STDIN = 5 FCGI_STDOUT = 6 FCGI_STDERR = 7 FCGI_DATA = 8 FCGI_GET_VALUES = 9 FCGI_GET_VALUES_RESULT = 10 FCGI_UNKNOWN_TYPE = 11 FCGI_MAXTYPE = FCGI_UNKNOWN_TYPE FCGI_NULL_REQUEST_ID = 0 FCGI_KEEP_CONN = 1 FCGI_RESPONDER = 1 FCGI_AUTHORIZER = 2 FCGI_FILTER = 3 FCGI_REQUEST_COMPLETE = 0 FCGI_CANT_MPX_CONN = 1 FCGI_OVERLOADED = 2 FCGI_UNKNOWN_ROLE = 3 FCGI_MAX_CONNS = 'FCGI_MAX_CONNS' FCGI_MAX_REQS = 'FCGI_MAX_REQS' FCGI_MPXS_CONNS = 'FCGI_MPXS_CONNS' FCGI_Header = '!BBHHBx' FCGI_BeginRequestBody = '!HB5x' FCGI_EndRequestBody = '!LB3x' FCGI_UnknownTypeBody = '!B7x' FCGI_EndRequestBody_LEN = struct.calcsize(FCGI_EndRequestBody) FCGI_UnknownTypeBody_LEN = struct.calcsize(FCGI_UnknownTypeBody) if __debug__: import time # Set non-zero to write debug output to a file. DEBUG = 0 DEBUGLOG = '/tmp/fcgi.log' def _debug(level, msg): if DEBUG < level: return try: f = open(DEBUGLOG, 'a') f.write('%sfcgi: %s\n' % (time.ctime()[4:-4], msg)) f.close() except: pass class InputStream(object): """ File-like object representing FastCGI input streams (FCGI_STDIN and FCGI_DATA). Supports the minimum methods required by WSGI spec. """ def __init__(self, conn): self._conn = conn # See Server. self._shrinkThreshold = conn.server.inputStreamShrinkThreshold self._buf = '' self._bufList = [] self._pos = 0 # Current read position. self._avail = 0 # Number of bytes currently available. self._eof = False # True when server has sent EOF notification. def _shrinkBuffer(self): """Gets rid of already read data (since we can't rewind).""" if self._pos >= self._shrinkThreshold: self._buf = self._buf[self._pos:] self._avail -= self._pos self._pos = 0 assert self._avail >= 0 def _waitForData(self): """Waits for more data to become available.""" self._conn.process_input() def read(self, n=-1): if self._pos == self._avail and self._eof: return '' while True: if n < 0 or (self._avail - self._pos) < n: # Not enough data available. if self._eof: # And there's no more coming. newPos = self._avail break else: # Wait for more data. self._waitForData() continue else: newPos = self._pos + n break # Merge buffer list, if necessary. if self._bufList: self._buf += ''.join(self._bufList) self._bufList = [] r = self._buf[self._pos:newPos] self._pos = newPos self._shrinkBuffer() return r def readline(self, length=None): if self._pos == self._avail and self._eof: return '' while True: # Unfortunately, we need to merge the buffer list early. if self._bufList: self._buf += ''.join(self._bufList) self._bufList = [] # Find newline. i = self._buf.find('\n', self._pos) if i < 0: # Not found? if self._eof: # No more data coming. newPos = self._avail break else: # Wait for more to come. self._waitForData() continue else: newPos = i + 1 break if length is not None: if self._pos + length < newPos: newPos = self._pos + length r = self._buf[self._pos:newPos] self._pos = newPos self._shrinkBuffer() return r def readlines(self, sizehint=0): total = 0 lines = [] line = self.readline() while line: lines.append(line) total += len(line) if 0 < sizehint <= total: break line = self.readline() return lines def __iter__(self): return self def next(self): r = self.readline() if not r: raise StopIteration return r def add_data(self, data): if not data: self._eof = True else: self._bufList.append(data) self._avail += len(data) class MultiplexedInputStream(InputStream): """ A version of InputStream meant to be used with MultiplexedConnections. Assumes the MultiplexedConnection (the producer) and the Request (the consumer) are running in different threads. """ def __init__(self, conn): super(MultiplexedInputStream, self).__init__(conn) # Arbitrates access to this InputStream (it's used simultaneously # by a Request and its owning Connection object). lock = threading.RLock() # Notifies Request thread that there is new data available. self._lock = threading.Condition(lock) def _waitForData(self): # Wait for notification from add_data(). self._lock.wait() def read(self, n=-1): self._lock.acquire() try: return super(MultiplexedInputStream, self).read(n) finally: self._lock.release() def readline(self, length=None): self._lock.acquire() try: return super(MultiplexedInputStream, self).readline(length) finally: self._lock.release() def add_data(self, data): self._lock.acquire() try: super(MultiplexedInputStream, self).add_data(data) self._lock.notify() finally: self._lock.release() class OutputStream(object): """ FastCGI output stream (FCGI_STDOUT/FCGI_STDERR). By default, calls to write() or writelines() immediately result in Records being sent back to the server. Buffering should be done in a higher level! """ def __init__(self, conn, req, type, buffered=False): self._conn = conn self._req = req self._type = type self._buffered = buffered self._bufList = [] # Used if buffered is True self.dataWritten = False self.closed = False def _write(self, data): length = len(data) while length: toWrite = min(length, self._req.server.maxwrite - FCGI_HEADER_LEN) rec = Record(self._type, self._req.requestId) rec.contentLength = toWrite rec.contentData = data[:toWrite] self._conn.writeRecord(rec) data = data[toWrite:] length -= toWrite def write(self, data): assert not self.closed if not data: return self.dataWritten = True if self._buffered: self._bufList.append(data) else: self._write(data) def writelines(self, lines): assert not self.closed for line in lines: self.write(line) def flush(self): # Only need to flush if this OutputStream is actually buffered. if self._buffered: data = ''.join(self._bufList) self._bufList = [] self._write(data) # Though available, the following should NOT be called by WSGI apps. def close(self): """Sends end-of-stream notification, if necessary.""" if not self.closed and self.dataWritten: self.flush() rec = Record(self._type, self._req.requestId) self._conn.writeRecord(rec) self.closed = True class TeeOutputStream(object): """ Simple wrapper around two or more output file-like objects that copies written data to all streams. """ def __init__(self, streamList): self._streamList = streamList def write(self, data): for f in self._streamList: f.write(data) def writelines(self, lines): for line in lines: self.write(line) def flush(self): for f in self._streamList: f.flush() class StdoutWrapper(object): """ Wrapper for sys.stdout so we know if data has actually been written. """ def __init__(self, stdout): self._file = stdout self.dataWritten = False def write(self, data): if data: self.dataWritten = True self._file.write(data) def writelines(self, lines): for line in lines: self.write(line) def __getattr__(self, name): return getattr(self._file, name) def decode_pair(s, pos=0): """ Decodes a name/value pair. The number of bytes decoded as well as the name/value pair are returned. """ nameLength = ord(s[pos]) if nameLength & 128: nameLength = struct.unpack('!L', s[pos:pos+4])[0] & 0x7fffffff pos += 4 else: pos += 1 valueLength = ord(s[pos]) if valueLength & 128: valueLength = struct.unpack('!L', s[pos:pos+4])[0] & 0x7fffffff pos += 4 else: pos += 1 name = s[pos:pos+nameLength] pos += nameLength value = s[pos:pos+valueLength] pos += valueLength return (pos, (name, value)) def encode_pair(name, value): """ Encodes a name/value pair. The encoded string is returned. """ nameLength = len(name) if nameLength < 128: s = chr(nameLength) else: s = struct.pack('!L', nameLength | 0x80000000L) valueLength = len(value) if valueLength < 128: s += chr(valueLength) else: s += struct.pack('!L', valueLength | 0x80000000L) return s + name + value class Record(object): """ A FastCGI Record. Used for encoding/decoding records. """ def __init__(self, type=FCGI_UNKNOWN_TYPE, requestId=FCGI_NULL_REQUEST_ID): self.version = FCGI_VERSION_1 self.type = type self.requestId = requestId self.contentLength = 0 self.paddingLength = 0 self.contentData = '' def _recvall(sock, length): """ Attempts to receive length bytes from a socket, blocking if necessary. (Socket may be blocking or non-blocking.) """ dataList = [] recvLen = 0 while length: try: data = sock.recv(length) except socket.error, e: if e[0] == errno.EAGAIN: select.select([sock], [], []) continue else: raise if not data: # EOF break dataList.append(data) dataLen = len(data) recvLen += dataLen length -= dataLen return ''.join(dataList), recvLen _recvall = staticmethod(_recvall) def read(self, sock): """Read and decode a Record from a socket.""" try: header, length = self._recvall(sock, FCGI_HEADER_LEN) except: raise EOFError if length < FCGI_HEADER_LEN: raise EOFError self.version, self.type, self.requestId, self.contentLength, \ self.paddingLength = struct.unpack(FCGI_Header, header) if __debug__: _debug(9, 'read: fd = %d, type = %d, requestId = %d, ' 'contentLength = %d' % (sock.fileno(), self.type, self.requestId, self.contentLength)) if self.contentLength: try: self.contentData, length = self._recvall(sock, self.contentLength) except: raise EOFError if length < self.contentLength: raise EOFError if self.paddingLength: try: self._recvall(sock, self.paddingLength) except: raise EOFError def _sendall(sock, data): """ Writes data to a socket and does not return until all the data is sent. """ length = len(data) while length: try: sent = sock.send(data) except socket.error, e: if e[0] == errno.EAGAIN: select.select([], [sock], []) continue else: raise data = data[sent:] length -= sent _sendall = staticmethod(_sendall) def write(self, sock): """Encode and write a Record to a socket.""" self.paddingLength = -self.contentLength & 7 if __debug__: _debug(9, 'write: fd = %d, type = %d, requestId = %d, ' 'contentLength = %d' % (sock.fileno(), self.type, self.requestId, self.contentLength)) header = struct.pack(FCGI_Header, self.version, self.type, self.requestId, self.contentLength, self.paddingLength) self._sendall(sock, header) if self.contentLength: self._sendall(sock, self.contentData) if self.paddingLength: self._sendall(sock, '\x00'*self.paddingLength) class Request(object): """ Represents a single FastCGI request. These objects are passed to your handler and is the main interface between your handler and the fcgi module. The methods should not be called by your handler. However, server, params, stdin, stdout, stderr, and data are free for your handler's use. """ def __init__(self, conn, inputStreamClass): self._conn = conn self.server = conn.server self.params = {} self.stdin = inputStreamClass(conn) self.stdout = OutputStream(conn, self, FCGI_STDOUT) self.stderr = OutputStream(conn, self, FCGI_STDERR, buffered=True) self.data = inputStreamClass(conn) def run(self): """Runs the handler, flushes the streams, and ends the request.""" try: protocolStatus, appStatus = self.server.handler(self) except: traceback.print_exc(file=self.stderr) self.stderr.flush() if not self.stdout.dataWritten: self.server.error(self) protocolStatus, appStatus = FCGI_REQUEST_COMPLETE, 0 if __debug__: _debug(1, 'protocolStatus = %d, appStatus = %d' % (protocolStatus, appStatus)) self._flush() self._end(appStatus, protocolStatus) def _end(self, appStatus=0L, protocolStatus=FCGI_REQUEST_COMPLETE): self._conn.end_request(self, appStatus, protocolStatus) def _flush(self): self.stdout.close() self.stderr.close() class CGIRequest(Request): """A normal CGI request disguised as a FastCGI request.""" def __init__(self, server): # These are normally filled in by Connection. self.requestId = 1 self.role = FCGI_RESPONDER self.flags = 0 self.aborted = False self.server = server self.params = dict(os.environ) self.stdin = sys.stdin self.stdout = StdoutWrapper(sys.stdout) # Oh, the humanity! self.stderr = sys.stderr self.data = StringIO.StringIO() def _end(self, appStatus=0L, protocolStatus=FCGI_REQUEST_COMPLETE): sys.exit(appStatus) def _flush(self): # Not buffered, do nothing. pass class Connection(object): """ A Connection with the web server. Each Connection is associated with a single socket (which is connected to the web server) and is responsible for handling all the FastCGI message processing for that socket. """ _multiplexed = False _inputStreamClass = InputStream def __init__(self, sock, addr, server): self._sock = sock self._addr = addr self.server = server # Active Requests for this Connection, mapped by request ID. self._requests = {} def _cleanupSocket(self): """Close the Connection's socket.""" try: self._sock.shutdown(socket.SHUT_WR) except: return try: while True: r, w, e = select.select([self._sock], [], []) if not r or not self._sock.recv(1024): break except: pass self._sock.close() def run(self): """Begin processing data from the socket.""" self._keepGoing = True while self._keepGoing: try: self.process_input() except EOFError: break except (select.error, socket.error), e: if e[0] == errno.EBADF: # Socket was closed by Request. break raise self._cleanupSocket() def process_input(self): """Attempt to read a single Record from the socket and process it.""" # Currently, any children Request threads notify this Connection # that it is no longer needed by closing the Connection's socket. # We need to put a timeout on select, otherwise we might get # stuck in it indefinitely... (I don't like this solution.) while self._keepGoing: try: r, w, e = select.select([self._sock], [], [], 1.0) except ValueError: # Sigh. ValueError gets thrown sometimes when passing select # a closed socket. raise EOFError if r: break if not self._keepGoing: return rec = Record() rec.read(self._sock) if rec.type == FCGI_GET_VALUES: self._do_get_values(rec) elif rec.type == FCGI_BEGIN_REQUEST: self._do_begin_request(rec) elif rec.type == FCGI_ABORT_REQUEST: self._do_abort_request(rec) elif rec.type == FCGI_PARAMS: self._do_params(rec) elif rec.type == FCGI_STDIN: self._do_stdin(rec) elif rec.type == FCGI_DATA: self._do_data(rec) elif rec.requestId == FCGI_NULL_REQUEST_ID: self._do_unknown_type(rec) else: # Need to complain about this. pass def writeRecord(self, rec): """ Write a Record to the socket. """ rec.write(self._sock) def end_request(self, req, appStatus=0L, protocolStatus=FCGI_REQUEST_COMPLETE, remove=True): """ End a Request. Called by Request objects. An FCGI_END_REQUEST Record is sent to the web server. If the web server no longer requires the connection, the socket is closed, thereby ending this Connection (run() returns). """ rec = Record(FCGI_END_REQUEST, req.requestId) rec.contentData = struct.pack(FCGI_EndRequestBody, appStatus, protocolStatus) rec.contentLength = FCGI_EndRequestBody_LEN self.writeRecord(rec) if remove: del self._requests[req.requestId] if __debug__: _debug(2, 'end_request: flags = %d' % req.flags) if not (req.flags & FCGI_KEEP_CONN) and not self._requests: self._cleanupSocket() self._keepGoing = False def _do_get_values(self, inrec): """Handle an FCGI_GET_VALUES request from the web server.""" outrec = Record(FCGI_GET_VALUES_RESULT) pos = 0 while pos < inrec.contentLength: pos, (name, value) = decode_pair(inrec.contentData, pos) cap = self.server.capability.get(name) if cap is not None: outrec.contentData += encode_pair(name, str(cap)) outrec.contentLength = len(outrec.contentData) self.writeRecord(outrec) def _do_begin_request(self, inrec): """Handle an FCGI_BEGIN_REQUEST from the web server.""" role, flags = struct.unpack(FCGI_BeginRequestBody, inrec.contentData) req = self.server.request_class(self, self._inputStreamClass) req.requestId, req.role, req.flags = inrec.requestId, role, flags req.aborted = False if not self._multiplexed and self._requests: # Can't multiplex requests. self.end_request(req, 0L, FCGI_CANT_MPX_CONN, remove=False) else: self._requests[inrec.requestId] = req def _do_abort_request(self, inrec): """ Handle an FCGI_ABORT_REQUEST from the web server. We just mark a flag in the associated Request. """ req = self._requests.get(inrec.requestId) if req is not None: req.aborted = True def _start_request(self, req): """Run the request.""" # Not multiplexed, so run it inline. req.run() def _do_params(self, inrec): """ Handle an FCGI_PARAMS Record. If the last FCGI_PARAMS Record is received, start the request. """ req = self._requests.get(inrec.requestId) if req is not None: if inrec.contentLength: pos = 0 while pos < inrec.contentLength: pos, (name, value) = decode_pair(inrec.contentData, pos) req.params[name] = value else: self._start_request(req) def _do_stdin(self, inrec): """Handle the FCGI_STDIN stream.""" req = self._requests.get(inrec.requestId) if req is not None: req.stdin.add_data(inrec.contentData) def _do_data(self, inrec): """Handle the FCGI_DATA stream.""" req = self._requests.get(inrec.requestId) if req is not None: req.data.add_data(inrec.contentData) def _do_unknown_type(self, inrec): """Handle an unknown request type. Respond accordingly.""" outrec = Record(FCGI_UNKNOWN_TYPE) outrec.contentData = struct.pack(FCGI_UnknownTypeBody, inrec.type) outrec.contentLength = FCGI_UnknownTypeBody_LEN self.writeRecord(rec) class MultiplexedConnection(Connection): """ A version of Connection capable of handling multiple requests simultaneously. """ _multiplexed = True _inputStreamClass = MultiplexedInputStream def __init__(self, sock, addr, server): super(MultiplexedConnection, self).__init__(sock, addr, server) # Used to arbitrate access to self._requests. lock = threading.RLock() # Notification is posted everytime a request completes, allowing us # to quit cleanly. self._lock = threading.Condition(lock) def _cleanupSocket(self): # Wait for any outstanding requests before closing the socket. self._lock.acquire() while self._requests: self._lock.wait() self._lock.release() super(MultiplexedConnection, self)._cleanupSocket() def writeRecord(self, rec): # Must use locking to prevent intermingling of Records from different # threads. self._lock.acquire() try: # Probably faster than calling super. ;) rec.write(self._sock) finally: self._lock.release() def end_request(self, req, appStatus=0L, protocolStatus=FCGI_REQUEST_COMPLETE, remove=True): self._lock.acquire() try: super(MultiplexedConnection, self).end_request(req, appStatus, protocolStatus, remove) self._lock.notify() finally: self._lock.release() def _do_begin_request(self, inrec): self._lock.acquire() try: super(MultiplexedConnection, self)._do_begin_request(inrec) finally: self._lock.release() def _do_abort_request(self, inrec): self._lock.acquire() try: super(MultiplexedConnection, self)._do_abort_request(inrec) finally: self._lock.release() def _start_request(self, req): thread.start_new_thread(req.run, ()) def _do_params(self, inrec): self._lock.acquire() try: super(MultiplexedConnection, self)._do_params(inrec) finally: self._lock.release() def _do_stdin(self, inrec): self._lock.acquire() try: super(MultiplexedConnection, self)._do_stdin(inrec) finally: self._lock.release() def _do_data(self, inrec): self._lock.acquire() try: super(MultiplexedConnection, self)._do_data(inrec) finally: self._lock.release() class Server(object): """ The FastCGI server. Waits for connections from the web server, processing each request. If run in a normal CGI context, it will instead instantiate a CGIRequest and run the handler through there. """ request_class = Request cgirequest_class = CGIRequest # Limits the size of the InputStream's string buffer to this size + the # server's maximum Record size. Since the InputStream is not seekable, # we throw away already-read data once this certain amount has been read. inputStreamShrinkThreshold = 102400 - 8192 def __init__(self, handler=None, maxwrite=8192, bindAddress=None, umask=None, multiplexed=False): """ handler, if present, must reference a function or method that takes one argument: a Request object. If handler is not specified at creation time, Server *must* be subclassed. (The handler method below is abstract.) maxwrite is the maximum number of bytes (per Record) to write to the server. I've noticed mod_fastcgi has a relatively small receive buffer (8K or so). bindAddress, if present, must either be a string or a 2-tuple. If present, run() will open its own listening socket. You would use this if you wanted to run your application as an 'external' FastCGI app. (i.e. the webserver would no longer be responsible for starting your app) If a string, it will be interpreted as a filename and a UNIX socket will be opened. If a tuple, the first element, a string, is the interface name/IP to bind to, and the second element (an int) is the port number. Set multiplexed to True if you want to handle multiple requests per connection. Some FastCGI backends (namely mod_fastcgi) don't multiplex requests at all, so by default this is off (which saves on thread creation/locking overhead). If threads aren't available, this keyword is ignored; it's not possible to multiplex requests at all. """ if handler is not None: self.handler = handler self.maxwrite = maxwrite if thread_available: try: import resource # Attempt to glean the maximum number of connections # from the OS. maxConns = resource.getrlimit(resource.RLIMIT_NOFILE)[0] except ImportError: maxConns = 100 # Just some made up number. maxReqs = maxConns if multiplexed: self._connectionClass = MultiplexedConnection maxReqs *= 5 # Another made up number. else: self._connectionClass = Connection self.capability = { FCGI_MAX_CONNS: maxConns, FCGI_MAX_REQS: maxReqs, FCGI_MPXS_CONNS: multiplexed and 1 or 0 } else: self._connectionClass = Connection self.capability = { # If threads aren't available, these are pretty much correct. FCGI_MAX_CONNS: 1, FCGI_MAX_REQS: 1, FCGI_MPXS_CONNS: 0 } self._bindAddress = bindAddress self._umask = umask def _setupSocket(self): if self._bindAddress is None: # Run as a normal FastCGI? isFCGI = True sock = socket.fromfd(FCGI_LISTENSOCK_FILENO, socket.AF_INET, socket.SOCK_STREAM) try: sock.getpeername() except socket.error, e: if e[0] == errno.ENOTSOCK: # Not a socket, assume CGI context. isFCGI = False elif e[0] != errno.ENOTCONN: raise # FastCGI/CGI discrimination is broken on Mac OS X. # Set the environment variable FCGI_FORCE_CGI to "Y" or "y" # if you want to run your app as a simple CGI. (You can do # this with Apache's mod_env [not loaded by default in OS X # client, ha ha] and the SetEnv directive.) if not isFCGI or \ os.environ.get('FCGI_FORCE_CGI', 'N').upper().startswith('Y'): req = self.cgirequest_class(self) req.run() sys.exit(0) else: # Run as a server oldUmask = None if type(self._bindAddress) is str: # Unix socket sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) try: os.unlink(self._bindAddress) except OSError: pass if self._umask is not None: oldUmask = os.umask(self._umask) else: # INET socket assert type(self._bindAddress) is tuple assert len(self._bindAddress) == 2 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(self._bindAddress) sock.listen(socket.SOMAXCONN) if oldUmask is not None: os.umask(oldUmask) return sock def _cleanupSocket(self, sock): """Closes the main socket.""" sock.close() def _installSignalHandlers(self): self._oldSIGs = [(x,signal.getsignal(x)) for x in (signal.SIGHUP, signal.SIGINT, signal.SIGTERM)] signal.signal(signal.SIGHUP, self._hupHandler) signal.signal(signal.SIGINT, self._intHandler) signal.signal(signal.SIGTERM, self._intHandler) def _restoreSignalHandlers(self): for signum,handler in self._oldSIGs: signal.signal(signum, handler) def _hupHandler(self, signum, frame): self._hupReceived = True self._keepGoing = False def _intHandler(self, signum, frame): self._keepGoing = False def run(self, timeout=1.0): """ The main loop. Exits on SIGHUP, SIGINT, SIGTERM. Returns True if SIGHUP was received, False otherwise. """ web_server_addrs = os.environ.get('FCGI_WEB_SERVER_ADDRS') if web_server_addrs is not None: web_server_addrs = map(lambda x: x.strip(), web_server_addrs.split(',')) sock = self._setupSocket() self._keepGoing = True self._hupReceived = False # Install signal handlers. self._installSignalHandlers() while self._keepGoing: try: r, w, e = select.select([sock], [], [], timeout) except select.error, e: if e[0] == errno.EINTR: continue raise if r: try: clientSock, addr = sock.accept() except socket.error, e: if e[0] in (errno.EINTR, errno.EAGAIN): continue raise if web_server_addrs and \ (len(addr) != 2 or addr[0] not in web_server_addrs): clientSock.close() continue # Instantiate a new Connection and begin processing FastCGI # messages (either in a new thread or this thread). conn = self._connectionClass(clientSock, addr, self) thread.start_new_thread(conn.run, ()) self._mainloopPeriodic() # Restore signal handlers. self._restoreSignalHandlers() self._cleanupSocket(sock) return self._hupReceived def _mainloopPeriodic(self): """ Called with just about each iteration of the main loop. Meant to be overridden. """ pass def _exit(self, reload=False): """ Protected convenience method for subclasses to force an exit. Not really thread-safe, which is why it isn't public. """ if self._keepGoing: self._keepGoing = False self._hupReceived = reload def handler(self, req): """ Default handler, which just raises an exception. Unless a handler is passed at initialization time, this must be implemented by a subclass. """ raise NotImplementedError, self.__class__.__name__ + '.handler' def error(self, req): """ Called by Request if an exception occurs within the handler. May and should be overridden. """ import cgitb req.stdout.write('Content-Type: text/html\r\n\r\n' + cgitb.html(sys.exc_info())) class WSGIServer(Server): """ FastCGI server that supports the Web Server Gateway Interface. See <http://www.python.org/peps/pep-0333.html>. """ def __init__(self, application, environ=None, multithreaded=True, **kw): """ environ, if present, must be a dictionary-like object. Its contents will be copied into application's environ. Useful for passing application-specific variables. Set multithreaded to False if your application is not MT-safe. """ if kw.has_key('handler'): del kw['handler'] # Doesn't make sense to let this through super(WSGIServer, self).__init__(**kw) if environ is None: environ = {} self.application = application self.environ = environ self.multithreaded = multithreaded # Used to force single-threadedness self._app_lock = thread.allocate_lock() def handler(self, req): """Special handler for WSGI.""" if req.role != FCGI_RESPONDER: return FCGI_UNKNOWN_ROLE, 0 # Mostly taken from example CGI gateway. environ = req.params environ.update(self.environ) environ['wsgi.version'] = (1,0) environ['wsgi.input'] = req.stdin if self._bindAddress is None: stderr = req.stderr else: stderr = TeeOutputStream((sys.stderr, req.stderr)) environ['wsgi.errors'] = stderr environ['wsgi.multithread'] = not isinstance(req, CGIRequest) and \ thread_available and self.multithreaded # Rationale for the following: If started by the web server # (self._bindAddress is None) in either FastCGI or CGI mode, the # possibility of being spawned multiple times simultaneously is quite # real. And, if started as an external server, multiple copies may be # spawned for load-balancing/redundancy. (Though I don't think # mod_fastcgi supports this?) environ['wsgi.multiprocess'] = True environ['wsgi.run_once'] = isinstance(req, CGIRequest) if environ.get('HTTPS', 'off') in ('on', '1'): environ['wsgi.url_scheme'] = 'https' else: environ['wsgi.url_scheme'] = 'http' self._sanitizeEnv(environ) headers_set = [] headers_sent = [] result = None def write(data): assert type(data) is str, 'write() argument must be string' assert headers_set, 'write() before start_response()' if not headers_sent: status, responseHeaders = headers_sent[:] = headers_set found = False for header,value in responseHeaders: if header.lower() == 'content-length': found = True break if not found and result is not None: try: if len(result) == 1: responseHeaders.append(('Content-Length', str(len(data)))) except: pass s = 'Status: %s\r\n' % status for header in responseHeaders: s += '%s: %s\r\n' % header s += '\r\n' req.stdout.write(s) req.stdout.write(data) req.stdout.flush() def start_response(status, response_headers, exc_info=None): if exc_info: try: if headers_sent: # Re-raise if too late raise exc_info[0], exc_info[1], exc_info[2] finally: exc_info = None # avoid dangling circular ref else: assert not headers_set, 'Headers already set!' assert type(status) is str, 'Status must be a string' assert len(status) >= 4, 'Status must be at least 4 characters' assert int(status[:3]), 'Status must begin with 3-digit code' assert status[3] == ' ', 'Status must have a space after code' assert type(response_headers) is list, 'Headers must be a list' if __debug__: for name,val in response_headers: assert type(name) is str, 'Header names must be strings' assert type(val) is str, 'Header values must be strings' headers_set[:] = [status, response_headers] return write if not self.multithreaded: self._app_lock.acquire() try: try: result = self.application(environ, start_response) try: for data in result: if data: write(data) if not headers_sent: write('') # in case body was empty finally: if hasattr(result, 'close'): result.close() except socket.error, e: if e[0] != errno.EPIPE: raise # Don't let EPIPE propagate beyond server finally: if not self.multithreaded: self._app_lock.release() return FCGI_REQUEST_COMPLETE, 0 def _sanitizeEnv(self, environ): """Ensure certain values are present, if required by WSGI.""" if not environ.has_key('SCRIPT_NAME'): environ['SCRIPT_NAME'] = '' if not environ.has_key('PATH_INFO'): environ['PATH_INFO'] = '' # If any of these are missing, it probably signifies a broken # server... for name,default in [('REQUEST_METHOD', 'GET'), ('SERVER_NAME', 'localhost'), ('SERVER_PORT', '80'), ('SERVER_PROTOCOL', 'HTTP/1.0')]: if not environ.has_key(name): environ['wsgi.errors'].write('%s: missing FastCGI param %s ' 'required by WSGI!\n' % (self.__class__.__name__, name)) environ[name] = default if __name__ == '__main__': def test_app(environ, start_response): """Probably not the most efficient example.""" import cgi start_response('200 OK', [('Content-Type', 'text/html')]) yield '<html><head><title>Hello World!</title></head>\n' \ '<body>\n' \ '<p>Hello World!</p>\n' \ '<table border="1">' names = environ.keys() names.sort() for name in names: yield '<tr><td>%s</td><td>%s</td></tr>\n' % ( name, cgi.escape(`environ[name]`)) form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ, keep_blank_values=1) if form.list: yield '<tr><th colspan="2">Form data</th></tr>' for field in form.list: yield '<tr><td>%s</td><td>%s</td></tr>\n' % ( field.name, field.value) yield '</table>\n' \ '</body></html>\n' WSGIServer(test_app).run()
Python
#!/usr/bin/env python # coding: utf8 """ RPX Authentication for web2py Developed by Nathan Freeze (Copyright © 2009) Email <nathan@freezable.com> Modified by Massimo Di Pierro This file contains code to allow using RPXNow.com (now Jainrain.com) services with web2py """ import re import urllib from gluon.html import * from gluon.tools import fetch from gluon.storage import Storage import gluon.contrib.simplejson as json class RPXAccount(object): """ from gluon.contrib.login_methods.rpx_account import RPXAccount auth.settings.actions_disabled=['register','change_password','request_reset_password'] auth.settings.login_form = RPXAccount(request, api_key="...", domain="...", url = "http://localhost:8000/%s/default/user/login" % request.application) """ def __init__(self, request, api_key = "", domain = "", url = "", embed = True, auth_url = "https://rpxnow.com/api/v2/auth_info", language= "en", prompt='rpx', on_login_failure = None, ): self.request=request self.api_key=api_key self.embed = embed self.auth_url = auth_url self.domain = domain self.token_url = url self.language = language self.profile = None self.prompt = prompt self.on_login_failure = on_login_failure self.mappings = Storage() self.mappings.Facebook = lambda profile:\ dict(registration_id = profile.get("identifier",""), username = profile.get("preferredUsername",""), email = profile.get("email",""), first_name = profile.get("name","").get("givenName",""), last_name = profile.get("name","").get("familyName","")) self.mappings.Google = lambda profile:\ dict(registration_id=profile.get("identifier",""), username=profile.get("preferredUsername",""), email=profile.get("email",""), first_name=profile.get("name","").get("givenName",""), last_name=profile.get("name","").get("familyName","")) self.mappings.default = lambda profile:\ dict(registration_id=profile.get("identifier",""), username=profile.get("preferredUsername",""), email=profile.get("email",""), first_name=profile.get("preferredUsername",""), last_name='') def get_user(self): request = self.request if request.vars.token: user = Storage() data = urllib.urlencode(dict(apiKey = self.api_key, token=request.vars.token)) auth_info_json = fetch(self.auth_url+'?'+data) auth_info = json.loads(auth_info_json) if auth_info['stat'] == 'ok': self.profile = auth_info['profile'] provider = re.sub('[^\w\-]','',self.profile['providerName']) user = self.mappings.get(provider,self.mappings.default)(self.profile) return user elif self.on_login_failure: redirect(self.on_login_failure) return None def login_form(self): request = self.request args = request.args if self.embed: JANRAIN_URL = \ "https://%s.rpxnow.com/openid/embed?token_url=%s&language_preference=%s" rpxform = IFRAME(_src=JANRAIN_URL % (self.domain,self.token_url,self.language), _scrolling="no", _frameborder="no", _style="width:400px;height:240px;") else: JANRAIN_URL = \ "https://%s.rpxnow.com/openid/v2/signin?token_url=%s" rpxform = DIV(SCRIPT(_src="https://rpxnow.com/openid/v2/widget", _type="text/javascript"), SCRIPT("RPXNOW.overlay = true;", "RPXNOW.language_preference = '%s';" % self.language, "RPXNOW.realm = '%s';" % self.domain, "RPXNOW.token_url = '%s';" % self.token_url, "RPXNOW.show();", _type="text/javascript")) return rpxform
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2 Thanks to Hans Donner <hans.donner@pobox.com> for GaeGoogleAccount. """ from google.appengine.api import users class GaeGoogleAccount(object): """ Login will be done via Google's Appengine login object, instead of web2py's login form. Include in your model (eg db.py):: from gluon.contrib.login_methods.gae_google_account import \ GaeGoogleAccount auth.settings.login_form=GaeGoogleAccount() """ def login_url(self, next="/"): return users.create_login_url(next) def logout_url(self, next="/"): return users.create_logout_url(next) def get_user(self): user = users.get_current_user() if user: return dict(nickname=user.nickname(), email=user.email(), user_id=user.user_id(), source="google account")
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2 Thanks to Hans Donner <hans.donner@pobox.com> for GaeGoogleAccount. """ from gluon.http import HTTP try: import linkedin except ImportError: raise HTTP(400,"linkedin module not found") class LinkedInAccount(object): """ Login will be done via Google's Appengine login object, instead of web2py's login form. Include in your model (eg db.py):: from gluon.contrib.login_methods.linkedin_account import LinkedInAccount auth.settings.login_form=LinkedInAccount(request,KEY,SECRET,RETURN_URL) """ def __init__(self,request,key,secret,return_url): self.request = request self.api = linkedin.LinkedIn(key,secret,return_url) self.token = result = self.api.requestToken() def login_url(self, next="/"): return self.api.getAuthorizeURL(self.token) def logout_url(self, next="/"): return '' def get_user(self): result = self.request.vars.verifier and self.api.accessToken(verifier = self.request.vars.verifier ) if result: profile = self.api.GetProfile() profile = self.api.GetProfile(profile).public_url = "http://www.linkedin.com/in/ozgurv" return dict(first_name = profile.first_name, last_name = profile.last_name, username = profile.id)
Python
import sys import logging try: import ldap ldap.set_option(ldap.OPT_REFERRALS, 0) except Exception, e: logging.error('missing ldap, try "easy_install python-ldap"') raise e def ldap_auth(server='ldap', port=None, base_dn='ou=users,dc=domain,dc=com', mode='uid', secure=False, cert_path=None, bind_dn=None, bind_pw=None, filterstr='objectClass=*'): """ to use ldap login with MS Active Directory:: from gluon.contrib.login_methods.ldap_auth import ldap_auth auth.settings.login_methods.append(ldap_auth( mode='ad', server='my.domain.controller', base_dn='ou=Users,dc=domain,dc=com')) to use ldap login with Notes Domino:: auth.settings.login_methods.append(ldap_auth( mode='domino',server='my.domino.server')) to use ldap login with OpenLDAP:: auth.settings.login_methods.append(ldap_auth( server='my.ldap.server', base_dn='ou=Users,dc=domain,dc=com')) to use ldap login with OpenLDAP and subtree search and (optionally) multiple DNs: auth.settings.login_methods.append(ldap_auth( mode='uid_r', server='my.ldap.server', base_dn=['ou=Users,dc=domain,dc=com','ou=Staff,dc=domain,dc=com'])) or (if using CN):: auth.settings.login_methods.append(ldap_auth( mode='cn', server='my.ldap.server', base_dn='ou=Users,dc=domain,dc=com')) If using secure ldaps:// pass secure=True and cert_path="..." If you need to bind to the directory with an admin account in order to search it then specify bind_dn & bind_pw to use for this. - currently only implemented for Active Directory If you need to restrict the set of allowed users (e.g. to members of a department) then specify a rfc4515 search filter string. - currently only implemented for mode in ['ad', 'company', 'uid_r'] """ def ldap_auth_aux(username, password, ldap_server=server, ldap_port=port, ldap_basedn=base_dn, ldap_mode=mode, ldap_binddn=bind_dn, ldap_bindpw=bind_pw, secure=secure, cert_path=cert_path, filterstr=filterstr): try: if secure: if not ldap_port: ldap_port = 636 con = ldap.initialize( "ldaps://" + ldap_server + ":" + str(ldap_port)) if cert_path: con.set_option(ldap.OPT_X_TLS_CACERTDIR, cert_path) else: if not ldap_port: ldap_port = 389 con = ldap.initialize( "ldap://" + ldap_server + ":" + str(ldap_port)) if ldap_mode == 'ad': # Microsoft Active Directory if '@' not in username: domain = [] for x in ldap_basedn.split(','): if "DC=" in x.upper(): domain.append(x.split('=')[-1]) username = "%s@%s" % (username, '.'.join(domain)) username_bare = username.split("@")[0] con.set_option(ldap.OPT_PROTOCOL_VERSION, 3) if ldap_binddn: # need to search directory with an admin account 1st con.simple_bind_s(ldap_binddn, ldap_bindpw) else: # credentials should be in the form of username@domain.tld con.simple_bind_s(username, password) # this will throw an index error if the account is not found # in the ldap_basedn result = con.search_ext_s( ldap_basedn, ldap.SCOPE_SUBTREE, "(&(sAMAccountName=%s)(%s))" % (username_bare, filterstr), ["sAMAccountName"])[0][1] if ldap_binddn: # We know the user exists & is in the correct OU # so now we just check the password con.simple_bind_s(username, password) if ldap_mode == 'domino': # Notes Domino if "@" in username: username = username.split("@")[0] con.simple_bind_s(username, password) if ldap_mode == 'cn': # OpenLDAP (CN) dn = "cn=" + username + "," + ldap_basedn con.simple_bind_s(dn, password) if ldap_mode == 'uid': # OpenLDAP (UID) dn = "uid=" + username + "," + ldap_basedn con.simple_bind_s(dn, password) if ldap_mode == 'company': # no DNs or password needed to search directory dn = "" pw = "" # bind anonymously con.simple_bind_s(dn, pw) # search by e-mail address filter = '(&(mail=' + username + ')(' + filterstr + '))' # find the uid attrs = ['uid'] # perform the actual search company_search_result=con.search_s(ldap_basedn, ldap.SCOPE_SUBTREE, filter, attrs) dn = company_search_result[0][0] # perform the real authentication test con.simple_bind_s(dn, password) if ldap_mode == 'uid_r': # OpenLDAP (UID) with subtree search and multiple DNs if type(ldap_basedn) == type([]): basedns = ldap_basedn else: basedns = [ldap_basedn] filter = '(&(uid=%s)(%s))' % (username, filterstr) for basedn in basedns: try: result = con.search_s(basedn, ldap.SCOPE_SUBTREE, filter) if result: user_dn = result[0][0] # Check the password con.simple_bind_s(user_dn, password) con.unbind() return True except ldap.LDAPError, detail: (exc_type, exc_value) = sys.exc_info()[:2] sys.stderr.write("ldap_auth: searching %s for %s resulted in %s: %s\n" % (basedn, filter, exc_type, exc_value)) return False con.unbind() return True except ldap.LDAPError, e: return False except IndexError, ex: # for AD membership test return False if filterstr[0] == '(' and filterstr[-1] == ')': # rfc4515 syntax filterstr = filterstr[1:-1] # parens added again where used return ldap_auth_aux
Python
#!/usr/bin/env python # coding: utf8 """ OpenID authentication for web2py Allowed using OpenID login together with web2py built-in login. By default, to support OpenID login, put this in your db.py >>> from gluon.contrib.login_methods.openid_auth import OpenIDAuth >>> auth.settings.login_form = OpenIDAuth(auth) To show OpenID list in user profile, you can add the following code before the end of function user() of your_app/controllers/default.py + if (request.args and request.args(0) == "profile"): + form = DIV(form, openid_login_form.list_user_openids()) return dict(form=form, login_form=login_form, register_form=register_form, self_registration=self_registration) More detail in the description of the class OpenIDAuth. Requirements: python-openid version 2.2.5 or later Reference: * w2p openID http://w2popenid.appspot.com/init/default/wiki/w2popenid * RPX and web2py auth module http://www.web2pyslices.com/main/slices/take_slice/28 * built-in file: gluon/contrib/login_methods/rpx_account.py * built-in file: gluon/tools.py (Auth class) """ import time from datetime import datetime, timedelta from gluon import * from gluon.storage import Storage, Messages try: import openid.consumer.consumer from openid.association import Association from openid.store.interface import OpenIDStore from openid.extensions.sreg import SRegRequest, SRegResponse from openid.store import nonce from openid.consumer.discover import DiscoveryFailure except ImportError, err: raise ImportError("OpenIDAuth requires python-openid package") DEFAULT = lambda: None class OpenIDAuth(object): """ OpenIDAuth It supports the logout_url, implementing the get_user and login_form for cas usage of gluon.tools.Auth. It also uses the ExtendedLoginForm to allow the OpenIDAuth login_methods combined with the standard logon/register procedure. It uses OpenID Consumer when render the form and begins the OpenID authentication. Example: (put these code after auth.define_tables() in your models.) auth = Auth(globals(), db) # authentication/authorization ... auth.define_tables() # creates all needed tables ... #include in your model after auth has been defined from gluon.contrib.login_methods.openid_auth import OpenIDAuth openid_login_form = OpenIDAuth(request, auth, db) from gluon.contrib.login_methods.extended_login_form import ExtendedLoginForm extended_login_form = ExtendedLoginForm(request, auth, openid_login_form, signals=['oid','janrain_nonce']) auth.settings.login_form = extended_login_form """ def __init__(self, auth): self.auth = auth self.db = auth.db request = current.request self.nextvar = '_next' self.realm = 'http://%s' % request.env.http_host self.login_url = URL(r=request, f='user', args=['login']) self.return_to_url = self.realm + self.login_url self.table_alt_logins_name = "alt_logins" if not auth.settings.table_user: raise self.table_user = self.auth.settings.table_user self.openid_expiration = 15 #minutes self.messages = self._define_messages() if not self.table_alt_logins_name in self.db.tables: self._define_alt_login_table() def _define_messages(self): messages = Messages(current.T) messages.label_alt_login_username = 'Sign-in with OpenID: ' messages.label_add_alt_login_username = 'Add a new OpenID: ' messages.submit_button = 'Sign in' messages.submit_button_add = 'Add' messages.a_delete = 'Delete' messages.comment_openid_signin = 'What is OpenID?' messages.comment_openid_help_title = 'Start using your OpenID' messages.comment_openid_help_url = 'http://openid.net/get-an-openid/start-using-your-openid/' messages.openid_fail_discover = 'Failed to discover OpenID service. Check your OpenID or "More about OpenID"?' messages.flash_openid_expired = 'OpenID expired. Please login or authenticate OpenID again. Sorry for the inconvenient.' messages.flash_openid_associated = 'OpenID associated' messages.flash_associate_openid = 'Please login or register an account for this OpenID.' messages.p_openid_not_registered = "This Open ID haven't be registered. " \ + "Please login to associate with it or register an account for it." messages.flash_openid_authenticated = 'OpenID authenticated successfully.' messages.flash_openid_fail_authentication = 'OpenID authentication failed. (Error message: %s)' messages.flash_openid_canceled = 'OpenID authentication canceled by user.' messages.flash_openid_need_setup = 'OpenID authentication needs to be setup by the user with the provider first.' messages.h_openid_login = 'OpenID Login' messages.h_openid_list = 'OpenID List' return messages def _define_alt_login_table(self): """ Define the OpenID login table. Note: type is what I used for our project. We're going to support 'fackbook' and 'plurk' alternate login methods. Otherwise it's always 'openid' and you may not need it. This should be easy to changed. (Just remove the field of "type" and remove the "and db.alt_logins.type == type_" in _find_matched_openid function) """ db = self.db table = db.define_table( self.table_alt_logins_name, Field('username', length=512, default=''), Field('type', length=128, default='openid', readable=False), Field('user', self.table_user, readable=False), ) table.username.requires = IS_NOT_IN_DB(db, table.username) self.table_alt_logins = table def logout_url(self, next): """ Delete the w2popenid record in session as logout """ if current.session.w2popenid: del(current.session.w2popenid) return next def login_form(self): """ Start to process the OpenID response if 'janrain_nonce' in request parameters and not processed yet. Else return the OpenID form for login. """ request = current.request if request.vars.has_key('janrain_nonce') and not self._processed(): self._process_response() return self.auth() return self._form() def get_user(self): """ It supports the logout_url, implementing the get_user and login_form for cas usage of gluon.tools.Auth. """ request = current.request args = request.args if args[0] == 'logout': return True # Let logout_url got called if current.session.w2popenid: w2popenid = current.session.w2popenid db = self.db if (w2popenid.ok is True and w2popenid.oid): # OpenID authenticated if self._w2popenid_expired(w2popenid): del(current.session.w2popenid) flash = self.messages.flash_openid_expired current.session.warning = flash redirect(self.auth.settings.login_url) oid = self._remove_protocol(w2popenid.oid) alt_login = self._find_matched_openid(db, oid) nextvar = self.nextvar # This OpenID not in the database. If user logged in then add it # into database, else ask user to login or register. if not alt_login: if self.auth.is_logged_in(): # TODO: ask first maybe self._associate_user_openid(self.auth.user, oid) if current.session.w2popenid: del(current.session.w2popenid) current.session.flash = self.messages.flash_openid_associated if request.vars.has_key(nextvar): redirect(request.vars[nextvar]) redirect(self.auth.settings.login_next) if not request.vars.has_key(nextvar): # no next var, add it and do login again # so if user login or register can go back here to associate the OpenID redirect(URL(r=request, args=['login'], vars={nextvar:self.login_url})) self.login_form = self._form_with_notification() current.session.flash = self.messages.flash_associate_openid return None # need to login or register to associate this openid # Get existed OpenID user user = db(self.table_user.id==alt_login.user).select().first() if user: if current.session.w2popenid: del(current.session.w2popenid) if 'username' in self.table_user.fields(): username = 'username' elif 'email' in self.table_user.fields(): username = 'email' return {username: user[username]} if user else None # login success (almost) return None # just start to login def _find_matched_openid(self, db, oid, type_='openid'): """ Get the matched OpenID for given """ query = ((db.alt_logins.username == oid) & (db.alt_logins.type == type_)) alt_login = db(query).select().first() # Get the OpenID record return alt_login def _associate_user_openid(self, user, oid): """ Associate the user logged in with given OpenID """ # print "[DB] %s authenticated" % oid self.db.alt_logins.insert(username=oid, user=user.id) def _form_with_notification(self): """ Render the form for normal login with a notice of OpenID authenticated """ form = DIV() # TODO: check when will happen if self.auth.settings.login_form in (self.auth, self): self.auth.settings.login_form = self.auth form = DIV(self.auth()) register_note = DIV(P(self.messages.p_openid_not_registered)) form.components.append(register_note) return lambda: form def _remove_protocol(self, oid): """ Remove https:// or http:// from oid url """ protocol = 'https://' if oid.startswith(protocol): oid = oid[len(protocol):] return oid protocol = 'http://' if oid.startswith(protocol): oid = oid[len(protocol):] return oid return oid def _init_consumerhelper(self): """ Initialize the ConsumerHelper """ if not hasattr(self, "consumerhelper"): self.consumerhelper = ConsumerHelper(current.session, self.db) return self.consumerhelper def _form(self, style=None): form = DIV(H3(self.messages.h_openid_login), self._login_form(style)) return form def _login_form(self, openid_field_label=None, submit_button=None, _next=None, style=None): """ Render the form for OpenID login """ def warning_openid_fail(session): session.warning = messages.openid_fail_discover style = style or """ background-attachment: scroll; background-repeat: no-repeat; background-image: url("http://wiki.openid.net/f/openid-16x16.gif"); background-position: 0% 50%; background-color: transparent; padding-left: 18px; width: 400px; """ style = style.replace("\n","") request = current.request session = current.session messages = self.messages hidden_next_input = "" if _next == 'profile': profile_url = URL(r=request, f='user', args=['profile']) hidden_next_input = INPUT(_type="hidden", _name="_next", _value=profile_url) form = FORM(openid_field_label or self.messages.label_alt_login_username, INPUT(_type="input", _name="oid", requires=IS_NOT_EMPTY(error_message=messages.openid_fail_discover), _style=style), hidden_next_input, INPUT(_type="submit", _value=submit_button or messages.submit_button), " ", A(messages.comment_openid_signin, _href=messages.comment_openid_help_url, _title=messages.comment_openid_help_title, _class='openid-identifier', _target="_blank"), _action=self.login_url ) if form.accepts(request.vars, session): oid = request.vars.oid consumerhelper = self._init_consumerhelper() url = self.login_url return_to_url = self.return_to_url if not oid: warning_openid_fail(session) redirect(url) try: if request.vars.has_key('_next'): return_to_url = self.return_to_url + '?_next=' + request.vars._next url = consumerhelper.begin(oid, self.realm, return_to_url) except DiscoveryFailure: warning_openid_fail(session) redirect(url) return form def _processed(self): """ Check if w2popenid authentication is processed. Return True if processed else False. """ processed = (hasattr(current.session, 'w2popenid') and current.session.w2popenid.ok is True) return processed def _set_w2popenid_expiration(self, w2popenid): """ Set expiration for OpenID authentication. """ w2popenid.expiration = datetime.now() + timedelta(minutes=self.openid_expiration) def _w2popenid_expired(self, w2popenid): """ Check if w2popenid authentication is expired. Return True if expired else False. """ return (not w2popenid.expiration) or (datetime.now() > w2popenid.expiration) def _process_response(self): """ Process the OpenID by ConsumerHelper. """ request = current.request request_vars = request.vars consumerhelper = self._init_consumerhelper() process_status = consumerhelper.process_response(request_vars, self.return_to_url) if process_status == "success": w2popenid = current.session.w2popenid user_data = self.consumerhelper.sreg() current.session.w2popenid.ok = True self._set_w2popenid_expiration(w2popenid) w2popenid.user_data = user_data current.session.flash = self.messages.flash_openid_authenticated elif process_status == "failure": flash = self.messages.flash_openid_fail_authentication % consumerhelper.error_message current.session.warning = flash elif process_status == "cancel": current.session.warning = self.messages.flash_openid_canceled elif process_status == "setup_needed": current.session.warning = self.messages.flash_openid_need_setup def list_user_openids(self): messages = self.messages request = current.request if request.vars.has_key('delete_openid'): self.remove_openid(request.vars.delete_openid) query = self.db.alt_logins.user == self.auth.user.id alt_logins = self.db(query).select() l = [] for alt_login in alt_logins: username = alt_login.username delete_href = URL(r=request, f='user', args=['profile'], vars={'delete_openid': username}) delete_link = A(messages.a_delete, _href=delete_href) l.append(LI(username, " ", delete_link)) profile_url = URL(r=request, f='user', args=['profile']) #return_to_url = self.return_to_url + '?' + self.nextvar + '=' + profile_url openid_list = DIV(H3(messages.h_openid_list), UL(l), self._login_form( _next='profile', submit_button=messages.submit_button_add, openid_field_label=messages.label_add_alt_login_username) ) return openid_list def remove_openid(self, openid): query = self.db.alt_logins.username == openid self.db(query).delete() class ConsumerHelper(object): """ ConsumerHelper knows the python-openid and """ def __init__(self, session, db): self.session = session store = self._init_store(db) self.consumer = openid.consumer.consumer.Consumer(session, store) def _init_store(self, db): """ Initialize Web2pyStore """ if not hasattr(self, "store"): store = Web2pyStore(db) session = self.session if not session.has_key('w2popenid'): session.w2popenid = Storage() self.store = store return self.store def begin(self, oid, realm, return_to_url): """ Begin the OpenID authentication """ w2popenid = self.session.w2popenid w2popenid.oid = oid auth_req = self.consumer.begin(oid) auth_req.addExtension(SRegRequest(required=['email','nickname'])) url = auth_req.redirectURL(return_to=return_to_url, realm=realm) return url def process_response(self, request_vars, return_to_url): """ Complete the process and """ resp = self.consumer.complete(request_vars, return_to_url) if resp: if resp.status == openid.consumer.consumer.SUCCESS: self.resp = resp if hasattr(resp, "identity_url"): self.session.w2popenid.oid = resp.identity_url return "success" if resp.status == openid.consumer.consumer.FAILURE: self.error_message = resp.message return "failure" if resp.status == openid.consumer.consumer.CANCEL: return "cancel" if resp.status == openid.consumer.consumer.SETUP_NEEDED: return "setup_needed" return "no resp" def sreg(self): """ Try to get OpenID Simple Registation http://openid.net/specs/openid-simple-registration-extension-1_0.html """ if self.resp: resp = self.resp sreg_resp = SRegResponse.fromSuccessResponse(resp) return sreg_resp.data if sreg_resp else None else: return None class Web2pyStore(OpenIDStore): """ Web2pyStore This class implements the OpenIDStore interface. OpenID stores take care of persisting nonces and associations. The Janrain Python OpenID library comes with implementations for file and memory storage. Web2pyStore uses the web2py db abstration layer. See the source code docs of OpenIDStore for a comprehensive description of this interface. """ def __init__(self, database): self.database = database self.table_oid_associations_name = 'oid_associations' self.table_oid_nonces_name = 'oid_nonces' self._initDB() def _initDB(self): if self.table_oid_associations_name not in self.database: self.database.define_table(self.table_oid_associations_name, Field('server_url', 'string', length=2047, required=True), Field('handle', 'string', length=255, required=True), Field('secret', 'blob', required=True), Field('issued', 'integer', required=True), Field('lifetime', 'integer', required=True), Field('assoc_type', 'string', length=64, required=True) ) if self.table_oid_nonces_name not in self.database: self.database.define_table(self.table_oid_nonces_name, Field('server_url', 'string', length=2047, required=True), Field('timestamp', 'integer', required=True), Field('salt', 'string', length=40, required=True) ) def storeAssociation(self, server_url, association): """ Store associations. If there already is one with the same server_url and handle in the table replace it. """ db = self.database query = (db.oid_associations.server_url == server_url) & (db.oid_associations.handle == association.handle) db(query).delete() db.oid_associations.insert(server_url = server_url, handle = association.handle, secret = association.secret, issued = association.issued, lifetime = association.lifetime, assoc_type = association.assoc_type), 'insert '*10 def getAssociation(self, server_url, handle=None): """ Return the association for server_url and handle. If handle is not None return the latests associations for that server_url. Return None if no association can be found. """ db = self.database query = (db.oid_associations.server_url == server_url) if handle: query &= (db.oid_associations.handle == handle) rows = db(query).select(orderby=db.oid_associations.issued) keep_assoc, _ = self._removeExpiredAssocations(rows) if len(keep_assoc) == 0: return None else: assoc = keep_assoc.pop() # pop the last one as it should be the latest one return Association(assoc['handle'], assoc['secret'], assoc['issued'], assoc['lifetime'], assoc['assoc_type']) def removeAssociation(self, server_url, handle): db = self.database query = (db.oid_associations.server_url == server_url) & (db.oid_associations.handle == handle) return db(query).delete() != None def useNonce(self, server_url, timestamp, salt): """ This method returns Falase if a nonce has been used before or its timestamp is not current. """ db = self.database if abs(timestamp - time.time()) > nonce.SKEW: return False query = (db.oid_nonces.server_url == server_url) & (db.oid_nonces.timestamp == timestamp) & (db.oid_nonces.salt == salt) if db(query).count() > 0: return False else: db.oid_nonces.insert(server_url = server_url, timestamp = timestamp, salt = salt) return True def _removeExpiredAssocations(self, rows): """ This helper function is not part of the interface. Given a list of association rows it checks which associations have expired and deletes them from the db. It returns a tuple of the form ([valid_assoc], no_of_expired_assoc_deleted). """ db = self.database keep_assoc = [] remove_assoc = [] t1970 = time.time() for r in rows: if r['issued'] + r['lifetime'] < t1970: remove_assoc.append(r) else: keep_assoc.append(r) for r in remove_assoc: del db.oid_associations[r['id']] return (keep_assoc, len(remove_assoc)) # return tuple (list of valid associations, number of deleted associations) def cleanupNonces(self): """ Remove expired nonce entries from DB and return the number of entries deleted. """ db = self.database query = (db.oid_nonces.timestamp < time.time() - nonce.SKEW) return db(query).delete() def cleanupAssociations(self): """ Remove expired associations from db and return the number of entries deleted. """ db = self.database query = (db.oid_associations.id > 0) return self._removeExpiredAssocations(db(query).select())[1] #return number of assoc removed def cleanup(self): """ This method should be run periodically to free the db from expired nonce and association entries. """ return self.cleanupNonces(), self.cleanupAssociations()
Python
#!/usr/bin/env python # coding: utf8 """ ExtendedLoginForm is used to extend normal login form in web2py with one more login method. So user can choose the built-in login or extended login methods. """ from gluon.html import DIV class ExtendedLoginForm(object): """ Put extended_login_form under web2py/gluon/contrib/login_methods folder. Then inside your model where defines the auth: auth = Auth(globals(),db) # authentication/authorization ... auth.define_tables() # You might like to put the code after auth.define_tables ... # if the alt_login_form deals with tables of auth. alt_login_form = RPXAccount(request, api_key="...", domain="...", url = "http://localhost:8000/%s/default/user/login" % request.application) extended_login_form = ExtendedLoginForm(auth, alt_login_form, signals=['token']) auth.settings.login_form = extended_login_form Note: Since rpx_account doesn't create the password for the user, you might need to provide a way for user to create password to do normal login. """ def __init__(self, auth, alt_login_form, signals=[], login_arg = 'login' ): self.auth = auth self.alt_login_form = alt_login_form self.signals = signals self.login_arg = login_arg def get_user(self): """ Delegate the get_user to alt_login_form.get_user. """ if hasattr(self.alt_login_form, 'get_user'): return self.alt_login_form.get_user() return None # let gluon.tools.Auth.get_or_create_user do the rest def login_url(self, next): """ Optional implement for alt_login_form. In normal case, this should be replaced by get_user, and never get called. """ if hasattr(self.alt_login_form, 'login_url'): return self.alt_login_form.login_url(next) return self.auth.settings.login_url def logout_url(self, next): """ Optional implement for alt_login_form. Called if bool(alt_login_form.get_user) is True. If alt_login_form implemented logout_url function, it will return that function call. """ if hasattr(self.alt_login_form, 'logout_url'): return self.alt_login_form.logout_url(next) return next def login_form(self): """ Combine the auth() form with alt_login_form. If signals are set and a parameter in request matches any signals, it will return the call of alt_login_form.login_form instead. So alt_login_form can handle some particular situations, for example, multiple steps of OpenID login inside alt_login_form.login_form. Otherwise it will render the normal login form combined with alt_login_form.login_form. """ request = self.auth.environment.request args = request.args if (self.signals and any([True for signal in self.signals if request.vars.has_key(signal)]) ): return self.alt_login_form.login_form() self.auth.settings.login_form = self.auth form = DIV(self.auth()) self.auth.settings.login_form = self form.components.append(self.alt_login_form.login_form()) return form
Python
import urllib import urllib2 import base64 def basic_auth(server="http://127.0.0.1"): """ to use basic login with a different server from gluon.contrib.login_methods.basic_auth import basic_auth auth.settings.login_methods.append(basic_auth('http://server')) """ def basic_login_aux(username, password, server=server): key = base64.b64encode(username+':'+password) headers = {'Authorization': 'Basic ' + key} request = urllib2.Request(server, None, headers) try: urllib2.urlopen(request) return True except (urllib2.URLError, urllib2.HTTPError): return False return basic_login_aux
Python
from gluon.contrib.pam import authenticate def pam_auth(): """ to use pam_login: from gluon.contrib.login_methods.pam_auth import pam_auth auth.settings.login_methods.append(pam_auth()) """ def pam_auth_aux(username, password): return authenticate(username, password) return pam_auth_aux
Python
import smtplib def email_auth(server="smtp.gmail.com:587", domain="@gmail.com"): """ to use email_login: from gluon.contrib.login_methods.email_auth import email_auth auth.settings.login_methods.append(email_auth("smtp.gmail.com:587", "@gmail.com")) """ def email_auth_aux(email, password, server=server, domain=domain): if domain: if not isinstance(domain,(list,tuple)): domain=[str(domain)] if not [d for d in domain if email[-len(d):]==d]: return False (host, port) = server.split(':') try: server = None server = smtplib.SMTP(host, port) server.ehlo() server.starttls() server.ehlo() server.login(email, password) server.quit() return True except: if server: server.quit() return False return email_auth_aux
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2 Tinkered by Szabolcs Gyuris < szimszo n @ o regpreshaz dot eu> """ from gluon import current, redirect class CasAuth( object ): """ Login will be done via Web2py's CAS application, instead of web2py's login form. Include in your model (eg db.py):: from gluon.contrib.login_methods.cas_auth import CasAuth auth.define_tables(username=True) auth.settings.login_form=CasAuth( urlbase = "https://[your CAS provider]/app/default/user/cas", actions=['login','validate','logout']) where urlbase is the actual CAS server url without the login,logout... Enjoy. ###UPDATE### if you want to connect to a CAS version 2 JASIG Server use this: auth.settings.login_form=CasAuth( urlbase = "https://[Your CAS server]/cas", actions = ['login','serviceValidate','logout'], casversion = 2, casusername = "cas:user") where casusername is the xml node returned by CAS server which contains user's username. """ def __init__(self, g=None, ### g for backward compatibility ### urlbase = "https://web2py.com/cas/cas", actions=['login','check','logout'], maps=dict(username=lambda v:v.get('username',v['user']), email=lambda v:v.get('email',None), user_id=lambda v:v['user']), casversion = 1, casusername = 'cas:user' ): self.urlbase=urlbase self.cas_login_url="%s/%s"%(self.urlbase,actions[0]) self.cas_check_url="%s/%s"%(self.urlbase,actions[1]) self.cas_logout_url="%s/%s"%(self.urlbase,actions[2]) self.maps=maps self.casversion = casversion self.casusername = casusername http_host=current.request.env.http_x_forwarded_host if not http_host: http_host=current.request.env.http_host if current.request.env.wsgi_url_scheme in [ 'https', 'HTTPS' ]: scheme = 'https' else: scheme = 'http' self.cas_my_url='%s://%s%s'%( scheme, http_host, current.request.env.path_info ) def login_url( self, next = "/" ): current.session.token=self._CAS_login() return next def logout_url( self, next = "/" ): current.session.token=None current.session.auth=None self._CAS_logout() return next def get_user( self ): user=current.session.token if user: d = {'source':'web2py cas'} for key in self.maps: d[key]=self.maps[key](user) return d return None def _CAS_login( self ): """ exposed as CAS.login(request) returns a token on success, None on failed authentication """ import urllib self.ticket=current.request.vars.ticket if not current.request.vars.ticket: redirect( "%s?service=%s"% (self.cas_login_url, self.cas_my_url)) else: url="%s?service=%s&ticket=%s" % (self.cas_check_url, self.cas_my_url, self.ticket ) data=urllib.urlopen( url ).read() if data.startswith('yes') or data.startswith('no'): data = data.split('\n') if data[0]=='yes': a,b,c = data[1].split( ':' )+[None,None] return dict(user=a,email=b,username=c) return None import xml.dom.minidom as dom import xml.parsers.expat as expat try: dxml=dom.parseString(data) envelop = dxml.getElementsByTagName("cas:authenticationSuccess") if len(envelop)>0: res = dict() for x in envelop[0].childNodes: if x.nodeName.startswith('cas:') and len(x.childNodes): key = x.nodeName[4:].encode('utf8') value = x.childNodes[0].nodeValue.encode('utf8') if not key in res: res[key]=value else: if not isinstance(res[key],list): res[key]=[res[key]] res[key].append(value) return res except expat.ExpatError: pass return None # fallback def _CAS_logout( self ): """ exposed CAS.logout() redirects to the CAS logout page """ import urllib redirect("%s?service=%s" % (self.cas_logout_url,self.cas_my_url))
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Loginza.ru authentication for web2py Developed by Vladimir Dronnikov (Copyright © 2011) Email <dronnikov@gmail.com> """ import urllib from gluon.html import * from gluon.tools import fetch from gluon.storage import Storage import gluon.contrib.simplejson as json class Loginza(object): """ from gluon.contrib.login_methods.loginza import Loginza auth.settings.login_form = Loginza(request, url = "http://localhost:8000/%s/default/user/login" % request.application) """ def __init__(self, request, url = "", embed = True, auth_url = "http://loginza.ru/api/authinfo", language = "en", prompt = "loginza", on_login_failure = None, ): self.request = request self.token_url = url self.embed = embed self.auth_url = auth_url self.language = language self.prompt = prompt self.profile = None self.on_login_failure = on_login_failure self.mappings = Storage() # TODO: profile.photo is the URL to the picture # Howto download and store it locally? # FIXME: what if email is unique=True self.mappings["http://twitter.com/"] = lambda profile:\ dict(registration_id = profile.get("identity",""), username = profile.get("nickname",""), email = profile.get("email",""), last_name = profile.get("name","").get("full_name",""), #avatar = profile.get("photo",""), ) self.mappings["https://www.google.com/accounts/o8/ud"] = lambda profile:\ dict(registration_id = profile.get("identity",""), username = profile.get("name","").get("full_name",""), email = profile.get("email",""), first_name = profile.get("name","").get("first_name",""), last_name = profile.get("name","").get("last_name",""), #avatar = profile.get("photo",""), ) self.mappings["http://vkontakte.ru/"] = lambda profile:\ dict(registration_id=profile.get("identity",""), username = profile.get("name","").get("full_name",""), email = profile.get("email",""), first_name = profile.get("name","").get("first_name",""), last_name = profile.get("name","").get("last_name",""), #avatar = profile.get("photo",""), ) self.mappings.default = lambda profile:\ dict(registration_id = profile.get("identity",""), username = profile.get("name","").get("full_name"), email = profile.get("email",""), first_name = profile.get("name","").get("first_name",""), last_name = profile.get("name","").get("last_name",""), #avatar = profile.get("photo",""), ) def get_user(self): request = self.request if request.vars.token: user = Storage() data = urllib.urlencode(dict(token = request.vars.token)) auth_info_json = fetch(self.auth_url+'?'+data) #print auth_info_json auth_info = json.loads(auth_info_json) if auth_info["identity"] != None: self.profile = auth_info provider = self.profile["provider"] user = self.mappings.get(provider, self.mappings.default)(self.profile) #user["password"] = ??? #user["avatar"] = ??? return user elif self.on_login_failure: redirect(self.on_login_failure) return None def login_form(self): request = self.request args = request.args LOGINZA_URL = "https://loginza.ru/api/widget?lang=%s&token_url=%s&overlay=loginza" if self.embed: form = IFRAME(_src=LOGINZA_URL % (self.language, self.token_url), _scrolling="no", _frameborder="no", _style="width:359px;height:300px;") else: form = DIV(A(self.prompt, _href=LOGINZA_URL % (self.language, self.token_url), _class="loginza"), SCRIPT(_src="https://s3-eu-west-1.amazonaws.com/s1.loginza.ru/js/widget.js", _type="text/javascript")) return form
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Written by Michele Comitini <mcm@glisco.it> License: GPL v3 Adds support for OAuth 2.0 authentication to web2py. OAuth 2.0 Draft: http://tools.ietf.org/html/draft-ietf-oauth-v2-10 """ import time import cgi from urllib2 import urlopen import urllib2 from urllib import urlencode class OAuthAccount(object): """ Login will be done via OAuth Framework, instead of web2py's login form. Include in your model (eg db.py):: # define the auth_table before call to auth.define_tables() auth_table = db.define_table( auth.settings.table_user_name, Field('first_name', length=128, default=""), Field('last_name', length=128, default=""), Field('username', length=128, default="", unique=True), Field('password', 'password', length=256, readable=False, label='Password'), Field('registration_key', length=128, default= "", writable=False, readable=False)) auth_table.username.requires = IS_NOT_IN_DB(db, auth_table.username) . . . auth.define_tables() . . . CLIENT_ID=\"<put your fb application id here>\" CLIENT_SECRET=\"<put your fb application secret here>\" AUTH_URL="http://..." TOKEN_URL="http://..." from gluon.contrib.login_methods.oauth20_account import OAuthAccount auth.settings.login_form=OAuthAccount(globals(),CLIENT_ID,CLIENT_SECRET,AUTH_URL, TOKEN_URL, **args ) Any optional arg will be passed as is to remote server for requests. It can be used for the optional "scope" parameters for Facebook. """ def __redirect_uri(self, next=None): """Build the uri used by the authenticating server to redirect the client back to the page originating the auth request. Appends the _next action to the generated url so the flows continues. """ r = self.request http_host=r.env.http_x_forwarded_for if not http_host: http_host=r.env.http_host url_scheme = r.env.wsgi_url_scheme if next: path_info = next else: path_info = r.env.path_info uri = '%s://%s%s' %(url_scheme, http_host, path_info) if r.get_vars and not next: uri += '?' + urlencode(r.get_vars) return uri def __build_url_opener(self, uri): """Build the url opener for managing HTTP Basic Athentication""" # Create an OpenerDirector with support for Basic HTTP Authentication... auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password(None, uri, self.client_id, self.client_secret) opener = urllib2.build_opener(auth_handler) return opener def accessToken(self): """Return the access token generated by the authenticating server. If token is already in the session that one will be used. Otherwise the token is fetched from the auth server. """ if self.session.token and self.session.token.has_key('expires'): expires = self.session.token['expires'] # reuse token until expiration if expires == 0 or expires > time.time(): return self.session.token['access_token'] if self.session.code: data = dict(client_id=self.client_id, client_secret=self.client_secret, redirect_uri=self.session.redirect_uri, response_type='token', code=self.session.code) if self.args: data.update(self.args) open_url = None opener = self.__build_url_opener(self.token_url) try: open_url = opener.open(self.token_url, urlencode(data)) except urllib2.HTTPError, e: raise Exception(e.read()) finally: del self.session.code # throw it away if open_url: try: tokendata = cgi.parse_qs(open_url.read()) self.session.token = dict([(k,v[-1]) for k,v in tokendata.items()]) # set expiration absolute time try to avoid broken # implementations where "expires_in" becomes "expires" if self.session.token.has_key('expires_in'): exps = 'expires_in' else: exps = 'expires' self.session.token['expires'] = int(self.session.token[exps]) + \ time.time() finally: opener.close() return self.session.token['access_token'] self.session.token = None return None def __init__(self, g, client_id, client_secret, auth_url, token_url, **args): self.globals = g self.client_id = client_id self.client_secret = client_secret self.request = g['request'] self.session = g['session'] self.auth_url = auth_url self.token_url = token_url self.args = args def login_url(self, next="/"): self.__oauth_login(next) return next def logout_url(self, next="/"): del self.session.token return next def get_user(self): '''Returns the user using the Graph API. ''' raise NotImplementedError, "Must override get_user()" if not self.accessToken(): return None if not self.graph: self.graph = GraphAPI((self.accessToken())) user = None try: user = self.graph.get_object("me") except GraphAPIError: self.session.token = None self.graph = None if user: return dict(first_name = user['first_name'], last_name = user['last_name'], username = user['id']) def __oauth_login(self, next): '''This method redirects the user to the authenticating form on authentication server if the authentication code and the authentication token are not available to the application yet. Once the authentication code has been received this method is called to set the access token into the session by calling accessToken() ''' if not self.accessToken(): if not self.request.vars.code: self.session.redirect_uri=self.__redirect_uri(next) data = dict(redirect_uri=self.session.redirect_uri, response_type='code', client_id=self.client_id) if self.args: data.update(self.args) auth_request_url = self.auth_url + "?" +urlencode(data) HTTP = self.globals['HTTP'] raise HTTP(307, "You are not authenticated: you are being redirected to the <a href='" + auth_request_url + "'> authentication server</a>", Location=auth_request_url) else: self.session.code = self.request.vars.code self.accessToken() return self.session.code return None
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Written by Michele Comitini <mcm@glisco.it> License: GPL v3 Adds support for OAuth1.0a authentication to web2py. Dependencies: - python-oauth2 (http://github.com/simplegeo/python-oauth2) """ import oauth2 as oauth import cgi from urllib2 import urlopen import urllib2 from urllib import urlencode class OAuthAccount(object): """ Login will be done via OAuth Framework, instead of web2py's login form. Include in your model (eg db.py):: # define the auth_table before call to auth.define_tables() auth_table = db.define_table( auth.settings.table_user_name, Field('first_name', length=128, default=""), Field('last_name', length=128, default=""), Field('username', length=128, default="", unique=True), Field('password', 'password', length=256, readable=False, label='Password'), Field('registration_key', length=128, default= "", writable=False, readable=False)) auth_table.username.requires = IS_NOT_IN_DB(db, auth_table.username) . . . auth.define_tables() . . . CLIENT_ID=\"<put your fb application id here>\" CLIENT_SECRET=\"<put your fb application secret here>\" AUTH_URL="..." TOKEN_URL="..." ACCESS_TOKEN_URL="..." from gluon.contrib.login_methods.oauth10a_account import OAuthAccount auth.settings.login_form=OAuthAccount(globals(),CLIENT_ID,CLIENT_SECRET, AUTH_URL, TOKEN_URL, ACCESS_TOKEN_URL) """ def __redirect_uri(self, next=None): """Build the uri used by the authenticating server to redirect the client back to the page originating the auth request. Appends the _next action to the generated url so the flows continues. """ r = self.request http_host=r.env.http_x_forwarded_for if not http_host: http_host=r.env.http_host url_scheme = r.env.wsgi_url_scheme if next: path_info = next else: path_info = r.env.path_info uri = '%s://%s%s' %(url_scheme, http_host, path_info) if r.get_vars and not next: uri += '?' + urlencode(r.get_vars) return uri def accessToken(self): """Return the access token generated by the authenticating server. If token is already in the session that one will be used. Otherwise the token is fetched from the auth server. """ if self.session.access_token: # return the token (TODO: does it expire?) return self.session.access_token if self.session.request_token: # Exchange the request token with an authorization token. token = self.session.request_token self.session.request_token = None # Build an authorized client # OAuth1.0a put the verifier! token.set_verifier(self.request.vars.oauth_verifier) client = oauth.Client(self.consumer, token) resp, content = client.request(self.access_token_url, "POST") if str(resp['status']) != '200': self.session.request_token = None self.globals['redirect'](self.globals['URL'](f='user',args='logout')) self.session.access_token = oauth.Token.from_string(content) return self.session.access_token self.session.access_token = None return None def __init__(self, g, client_id, client_secret, auth_url, token_url, access_token_url): self.globals = g self.client_id = client_id self.client_secret = client_secret self.code = None self.request = g['request'] self.session = g['session'] self.auth_url = auth_url self.token_url = token_url self.access_token_url = access_token_url # consumer init self.consumer = oauth.Consumer(self.client_id, self.client_secret) def login_url(self, next="/"): self.__oauth_login(next) return next def logout_url(self, next="/"): self.session.request_token = None self.session.access_token = None return next def get_user(self): '''Get user data. Since OAuth does not specify what a user is, this function must be implemented for the specific provider. ''' raise NotImplementedError, "Must override get_user()" def __oauth_login(self, next): '''This method redirects the user to the authenticating form on authentication server if the authentication code and the authentication token are not available to the application yet. Once the authentication code has been received this method is called to set the access token into the session by calling accessToken() ''' if not self.accessToken(): # setup the client client = oauth.Client(self.consumer, None) # Get a request token. # oauth_callback *is REQUIRED* for OAuth1.0a # putting it in the body seems to work. callback_url = self.__redirect_uri(next) data = urlencode(dict(oauth_callback=callback_url)) resp, content = client.request(self.token_url, "POST", body=data) if resp['status'] != '200': self.session.request_token = None self.globals['redirect'](self.globals['URL'](f='user',args='logout')) # Store the request token in session. request_token = self.session.request_token = oauth.Token.from_string(content) # Redirect the user to the authentication URL and pass the callback url. data = urlencode(dict(oauth_token=request_token.key, oauth_callback=callback_url)) auth_request_url = self.auth_url + '?' +data HTTP = self.globals['HTTP'] raise HTTP(307, "You are not authenticated: you are being redirected to the <a href='" + auth_request_url + "'> authentication server</a>", Location=auth_request_url) return None
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu> and Robin B <robi123@gmail.com>. License: GPL v2 """ __all__ = ['MEMDB', 'Field'] import re import sys import os import types import datetime import thread import cStringIO import csv import copy import gluon.validators as validators from gluon.storage import Storage import random SQL_DIALECTS = {'memcache': { 'boolean': bool, 'string': unicode, 'text': unicode, 'password': unicode, 'blob': unicode, 'upload': unicode, 'integer': long, 'double': float, 'date': datetime.date, 'time': datetime.time, 'datetime': datetime.datetime, 'id': int, 'reference': int, 'lower': None, 'upper': None, 'is null': 'IS NULL', 'is not null': 'IS NOT NULL', 'extract': None, 'left join': None, }} def cleanup(text): if re.compile('[^0-9a-zA-Z_]').findall(text): raise SyntaxError, \ 'Can\'t cleanup \'%s\': only [0-9a-zA-Z_] allowed in table and field names' % text return text def assert_filter_fields(*fields): for field in fields: if isinstance(field, (Field, Expression)) and field.type\ in ['text', 'blob']: raise SyntaxError, 'AppEngine does not index by: %s'\ % field.type def dateobj_to_datetime(object): # convert dates,times to datetimes for AppEngine if isinstance(object, datetime.date): object = datetime.datetime(object.year, object.month, object.day) if isinstance(object, datetime.time): object = datetime.datetime( 1970, 1, 1, object.hour, object.minute, object.second, object.microsecond, ) return object def sqlhtml_validators(field_type, length): v = { 'boolean': [], 'string': validators.IS_LENGTH(length), 'text': [], 'password': validators.IS_LENGTH(length), 'blob': [], 'upload': [], 'double': validators.IS_FLOAT_IN_RANGE(-1e100, 1e100), 'integer': validators.IS_INT_IN_RANGE(-1e100, 1e100), 'date': validators.IS_DATE(), 'time': validators.IS_TIME(), 'datetime': validators.IS_DATETIME(), 'reference': validators.IS_INT_IN_RANGE(0, 1e100), } try: return v[field_type[:9]] except KeyError: return [] class DALStorage(dict): """ a dictionary that let you do d['a'] as well as d.a """ def __getattr__(self, key): return self[key] def __setattr__(self, key, value): if key in self: raise SyntaxError, 'Object \'%s\'exists and cannot be redefined' % key self[key] = value def __repr__(self): return '<DALStorage ' + dict.__repr__(self) + '>' class SQLCallableList(list): def __call__(self): return copy.copy(self) class MEMDB(DALStorage): """ an instance of this class represents a database connection Example:: db=MEMDB(Client()) db.define_table('tablename',Field('fieldname1'), Field('fieldname2')) """ def __init__(self, client): self._dbname = 'memdb' self['_lastsql'] = '' self.tables = SQLCallableList() self._translator = SQL_DIALECTS['memcache'] self.client = client def define_table( self, tablename, *fields, **args ): tablename = cleanup(tablename) if tablename in dir(self) or tablename[0] == '_': raise SyntaxError, 'invalid table name: %s' % tablename if not tablename in self.tables: self.tables.append(tablename) else: raise SyntaxError, 'table already defined: %s' % tablename t = self[tablename] = Table(self, tablename, *fields) t._create() return t def __call__(self, where=''): return Set(self, where) class SQLALL(object): def __init__(self, table): self.table = table class Table(DALStorage): """ an instance of this class represents a database table Example:: db=MEMDB(Client()) db.define_table('users',Field('name')) db.users.insert(name='me') """ def __init__( self, db, tablename, *fields ): self._db = db self._tablename = tablename self.fields = SQLCallableList() self._referenced_by = [] fields = list(fields) fields.insert(0, Field('id', 'id')) for field in fields: self.fields.append(field.name) self[field.name] = field field._tablename = self._tablename field._table = self field._db = self._db self.ALL = SQLALL(self) def _create(self): fields = [] myfields = {} for k in self.fields: field = self[k] attr = {} if not field.type[:9] in ['id', 'reference']: if field.notnull: attr = dict(required=True) if field.type[:2] == 'id': continue if field.type[:9] == 'reference': referenced = field.type[10:].strip() if not referenced: raise SyntaxError, \ 'Table %s: reference \'%s\' to nothing!' % (self._tablename, k) if not referenced in self._db: raise SyntaxError, \ 'Table: table %s does not exist' % referenced referee = self._db[referenced] ftype = \ self._db._translator[field.type[:9]]( self._db[referenced]._tableobj) if self._tablename in referee.fields: # ## THIS IS OK raise SyntaxError, \ 'Field: table \'%s\' has same name as a field ' \ 'in referenced table \'%s\'' % (self._tablename, referenced) self._db[referenced]._referenced_by.append((self._tablename, field.name)) elif not field.type in self._db._translator\ or not self._db._translator[field.type]: raise SyntaxError, 'Field: unkown field type %s' % field.type self._tableobj = self._db.client return None def create(self): # nothing to do, here for backward compatility pass def drop(self): # nothing to do, here for backward compatibility self._db(self.id > 0).delete() def insert(self, **fields): id = self._create_id() if self.update(id, **fields): return long(id) else: return None def get(self, id): val = self._tableobj.get(self._id_to_key(id)) if val: return Storage(val) else: return None def update(self, id, **fields): for field in fields: if not field in fields and self[field].default\ != None: fields[field] = self[field].default if field in fields: fields[field] = obj_represent(fields[field], self[field].type, self._db) return self._tableobj.set(self._id_to_key(id), fields) def delete(self, id): return self._tableobj.delete(self._id_to_key(id)) def _shard_key(self, shard): return self._id_to_key('s/%s' % shard) def _id_to_key(self, id): return '__memdb__/t/%s/k/%s' % (self._tablename, str(id)) def _create_id(self): shard = random.randint(10, 99) shard_id = self._shard_key(shard) id = self._tableobj.incr(shard_id) if not id: if self._tableobj.set(shard_id, '0'): id = 0 else: raise Exception, 'cannot set memcache' return long(str(shard) + str(id)) def __str__(self): return self._tablename class Expression(object): def __init__( self, name, type='string', db=None, ): (self.name, self.type, self._db) = (name, type, db) def __str__(self): return self.name def __or__(self, other): # for use in sortby assert_filter_fields(self, other) return Expression(self.name + '|' + other.name, None, None) def __invert__(self): assert_filter_fields(self) return Expression('-' + self.name, self.type, None) # for use in Query def __eq__(self, value): return Query(self, '=', value) def __ne__(self, value): return Query(self, '!=', value) def __lt__(self, value): return Query(self, '<', value) def __le__(self, value): return Query(self, '<=', value) def __gt__(self, value): return Query(self, '>', value) def __ge__(self, value): return Query(self, '>=', value) # def like(self,value): return Query(self,' LIKE ',value) # def belongs(self,value): return Query(self,' IN ',value) # for use in both Query and sortby def __add__(self, other): return Expression('%s+%s' % (self, other), 'float', None) def __sub__(self, other): return Expression('%s-%s' % (self, other), 'float', None) def __mul__(self, other): return Expression('%s*%s' % (self, other), 'float', None) def __div__(self, other): return Expression('%s/%s' % (self, other), 'float', None) class Field(Expression): """ an instance of this class represents a database field example:: a = Field(name, 'string', length=32, required=False, default=None, requires=IS_NOT_EMPTY(), notnull=False, unique=False, uploadfield=True) to be used as argument of GQLDB.define_table allowed field types: string, boolean, integer, double, text, blob, date, time, datetime, upload, password strings must have a length or 512 by default. fields should have a default or they will be required in SQLFORMs the requires argument are used to validate the field input in SQLFORMs """ def __init__( self, fieldname, type='string', length=None, default=None, required=False, requires=sqlhtml_validators, ondelete='CASCADE', notnull=False, unique=False, uploadfield=True, ): self.name = cleanup(fieldname) if fieldname in dir(Table) or fieldname[0] == '_': raise SyntaxError, 'Field: invalid field name: %s' % fieldname if isinstance(type, Table): type = 'reference ' + type._tablename if not length: length = 512 self.type = type # 'string', 'integer' self.length = length # the length of the string self.default = default # default value for field self.required = required # is this field required self.ondelete = ondelete.upper() # this is for reference fields only self.notnull = notnull self.unique = unique self.uploadfield = uploadfield if requires == sqlhtml_validators: requires = sqlhtml_validators(type, length) elif requires is None: requires = [] self.requires = requires # list of validators def formatter(self, value): if value is None or not self.requires: return value if not isinstance(self.requires, (list, tuple)): requires = [self.requires] else: requires = copy.copy(self.requires) requires.reverse() for item in requires: if hasattr(item, 'formatter'): value = item.formatter(value) return value def __str__(self): return '%s.%s' % (self._tablename, self.name) MEMDB.Field = Field # ## required by gluon/globals.py session.connect def obj_represent(object, fieldtype, db): if object != None: if fieldtype == 'date' and not isinstance(object, datetime.date): (y, m, d) = [int(x) for x in str(object).strip().split('-')] object = datetime.date(y, m, d) elif fieldtype == 'time' and not isinstance(object, datetime.time): time_items = [int(x) for x in str(object).strip().split(':')[:3]] if len(time_items) == 3: (h, mi, s) = time_items else: (h, mi, s) = time_items + [0] object = datetime.time(h, mi, s) elif fieldtype == 'datetime' and not isinstance(object, datetime.datetime): (y, m, d) = [int(x) for x in str(object)[:10].strip().split('-')] time_items = [int(x) for x in str(object)[11:].strip().split(':')[:3]] if len(time_items) == 3: (h, mi, s) = time_items else: (h, mi, s) = time_items + [0] object = datetime.datetime( y, m, d, h, mi, s, ) elif fieldtype == 'integer' and not isinstance(object, long): object = long(object) return object class QueryException: def __init__(self, **a): self.__dict__ = a class Query(object): """ A query object necessary to define a set. It can be stored or can be passed to GQLDB.__call__() to obtain a Set Example: query=db.users.name=='Max' set=db(query) records=set.select() """ def __init__( self, left, op=None, right=None, ): if isinstance(right, (Field, Expression)): raise SyntaxError, \ 'Query: right side of filter must be a value or entity' if isinstance(left, Field) and left.name == 'id': if op == '=': self.get_one = \ QueryException(tablename=left._tablename, id=long(right)) return else: raise SyntaxError, 'only equality by id is supported' raise SyntaxError, 'not supported' def __str__(self): return str(self.left) class Set(object): """ As Set represents a set of records in the database, the records are identified by the where=Query(...) object. normally the Set is generated by GQLDB.__call__(Query(...)) given a set, for example set=db(db.users.name=='Max') you can: set.update(db.users.name='Massimo') set.delete() # all elements in the set set.select(orderby=db.users.id,groupby=db.users.name,limitby=(0,10)) and take subsets: subset=set(db.users.id<5) """ def __init__(self, db, where=None): self._db = db self._tables = [] self.filters = [] if hasattr(where, 'get_all'): self.where = where self._tables.insert(0, where.get_all) elif hasattr(where, 'get_one') and isinstance(where.get_one, QueryException): self.where = where.get_one else: # find out which tables are involved if isinstance(where, Query): self.filters = where.left self.where = where self._tables = [field._tablename for (field, op, val) in self.filters] def __call__(self, where): if isinstance(self.where, QueryException) or isinstance(where, QueryException): raise SyntaxError, \ 'neither self.where nor where can be a QueryException instance' if self.where: return Set(self._db, self.where & where) else: return Set(self._db, where) def _get_table_or_raise(self): tablenames = list(set(self._tables)) # unique if len(tablenames) < 1: raise SyntaxError, 'Set: no tables selected' if len(tablenames) > 1: raise SyntaxError, 'Set: no join in appengine' return self._db[tablenames[0]]._tableobj def _getitem_exception(self): (tablename, id) = (self.where.tablename, self.where.id) fields = self._db[tablename].fields self.colnames = ['%s.%s' % (tablename, t) for t in fields] item = self._db[tablename].get(id) return (item, fields, tablename, id) def _select_except(self): (item, fields, tablename, id) = self._getitem_exception() if not item: return [] new_item = [] for t in fields: if t == 'id': new_item.append(long(id)) else: new_item.append(getattr(item, t)) r = [new_item] return Rows(self._db, r, *self.colnames) def select(self, *fields, **attributes): """ Always returns a Rows object, even if it may be empty """ if isinstance(self.where, QueryException): return self._select_except() else: raise SyntaxError, 'select arguments not supported' def count(self): return len(self.select()) def delete(self): if isinstance(self.where, QueryException): (item, fields, tablename, id) = self._getitem_exception() if not item: return self._db[tablename].delete(id) else: raise Exception, 'deletion not implemented' def update(self, **update_fields): if isinstance(self.where, QueryException): (item, fields, tablename, id) = self._getitem_exception() if not item: return for (key, value) in update_fields.items(): setattr(item, key, value) self._db[tablename].update(id, **item) else: raise Exception, 'update not implemented' def update_record( t, s, id, a, ): item = s.get(id) for (key, value) in a.items(): t[key] = value setattr(item, key, value) s.update(id, **item) class Rows(object): """ A wrapper for the return value of a select. It basically represents a table. It has an iterator and each row is represented as a dictionary. """ # ## this class still needs some work to care for ID/OID def __init__( self, db, response, *colnames ): self._db = db self.colnames = colnames self.response = response def __len__(self): return len(self.response) def __getitem__(self, i): if i >= len(self.response) or i < 0: raise SyntaxError, 'Rows: no such row: %i' % i if len(self.response[0]) != len(self.colnames): raise SyntaxError, 'Rows: internal error' row = DALStorage() for j in xrange(len(self.colnames)): value = self.response[i][j] if isinstance(value, unicode): value = value.encode('utf-8') packed = self.colnames[j].split('.') try: (tablename, fieldname) = packed except: if not '_extra' in row: row['_extra'] = DALStorage() row['_extra'][self.colnames[j]] = value continue table = self._db[tablename] field = table[fieldname] if not tablename in row: row[tablename] = DALStorage() if field.type[:9] == 'reference': referee = field.type[10:].strip() rid = value row[tablename][fieldname] = rid elif field.type == 'boolean' and value != None: # row[tablename][fieldname]=Set(self._db[referee].id==rid) if value == True or value == 'T': row[tablename][fieldname] = True else: row[tablename][fieldname] = False elif field.type == 'date' and value != None\ and not isinstance(value, datetime.date): (y, m, d) = [int(x) for x in str(value).strip().split('-')] row[tablename][fieldname] = datetime.date(y, m, d) elif field.type == 'time' and value != None\ and not isinstance(value, datetime.time): time_items = [int(x) for x in str(value).strip().split(':')[:3]] if len(time_items) == 3: (h, mi, s) = time_items else: (h, mi, s) = time_items + [0] row[tablename][fieldname] = datetime.time(h, mi, s) elif field.type == 'datetime' and value != None\ and not isinstance(value, datetime.datetime): (y, m, d) = [int(x) for x in str(value)[:10].strip().split('-')] time_items = [int(x) for x in str(value)[11:].strip().split(':')[:3]] if len(time_items) == 3: (h, mi, s) = time_items else: (h, mi, s) = time_items + [0] row[tablename][fieldname] = datetime.datetime( y, m, d, h, mi, s, ) else: row[tablename][fieldname] = value if fieldname == 'id': id = row[tablename].id row[tablename].update_record = lambda t = row[tablename], \ s = self._db[tablename], id = id, **a: update_record(t, s, id, a) for (referee_table, referee_name) in \ table._referenced_by: s = self._db[referee_table][referee_name] row[tablename][referee_table] = Set(self._db, s == id) if len(row.keys()) == 1: return row[row.keys()[0]] return row def __iter__(self): """ iterator over records """ for i in xrange(len(self)): yield self[i] def __str__(self): """ serializes the table into a csv file """ s = cStringIO.StringIO() writer = csv.writer(s) writer.writerow(self.colnames) c = len(self.colnames) for i in xrange(len(self)): row = [self.response[i][j] for j in xrange(c)] for k in xrange(c): if isinstance(row[k], unicode): row[k] = row[k].encode('utf-8') writer.writerow(row) return s.getvalue() def xml(self): """ serializes the table using sqlhtml.SQLTABLE (if present) """ return sqlhtml.SQLTABLE(self).xml() def test_all(): """ How to run from web2py dir: export PYTHONPATH=.:YOUR_PLATFORMS_APPENGINE_PATH python gluon/contrib/memdb.py Setup the UTC timezone and database stubs >>> import os >>> os.environ['TZ'] = 'UTC' >>> import time >>> if hasattr(time, 'tzset'): ... time.tzset() >>> >>> from google.appengine.api import apiproxy_stub_map >>> from google.appengine.api.memcache import memcache_stub >>> apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap() >>> apiproxy_stub_map.apiproxy.RegisterStub('memcache', memcache_stub.MemcacheServiceStub()) Create a table with all possible field types >>> from google.appengine.api.memcache import Client >>> db=MEMDB(Client()) >>> tmp=db.define_table('users', Field('stringf','string',length=32,required=True), Field('booleanf','boolean',default=False), Field('passwordf','password',notnull=True), Field('blobf','blob'), Field('uploadf','upload'), Field('integerf','integer',unique=True), Field('doublef','double',unique=True,notnull=True), Field('datef','date',default=datetime.date.today()), Field('timef','time'), Field('datetimef','datetime'), migrate='test_user.table') Insert a field >>> user_id = db.users.insert(stringf='a',booleanf=True,passwordf='p',blobf='0A', uploadf=None, integerf=5,doublef=3.14, datef=datetime.date(2001,1,1), timef=datetime.time(12,30,15), datetimef=datetime.datetime(2002,2,2,12,30,15)) >>> user_id != None True Select all # >>> all = db().select(db.users.ALL) Drop the table # >>> db.users.drop() Select many entities >>> tmp = db.define_table(\"posts\", Field('body','text'), Field('total','integer'), Field('created_at','datetime')) >>> many = 20 #2010 # more than 1000 single fetch limit (it can be slow) >>> few = 5 >>> most = many - few >>> 0 < few < most < many True >>> for i in range(many): ... f=db.posts.insert(body='', total=i,created_at=datetime.datetime(2008, 7, 6, 14, 15, 42, i)) >>> # test timezones >>> class TZOffset(datetime.tzinfo): ... def __init__(self,offset=0): ... self.offset = offset ... def utcoffset(self, dt): return datetime.timedelta(hours=self.offset) ... def dst(self, dt): return datetime.timedelta(0) ... def tzname(self, dt): return 'UTC' + str(self.offset) ... >>> SERVER_OFFSET = -8 >>> >>> stamp = datetime.datetime(2008, 7, 6, 14, 15, 42, 828201) >>> post_id = db.posts.insert(created_at=stamp,body='body1') >>> naive_stamp = db(db.posts.id==post_id).select()[0].created_at >>> utc_stamp=naive_stamp.replace(tzinfo=TZOffset()) >>> server_stamp = utc_stamp.astimezone(TZOffset(SERVER_OFFSET)) >>> stamp == naive_stamp True >>> utc_stamp == server_stamp True >>> rows = db(db.posts.id==post_id).select() >>> len(rows) == 1 True >>> rows[0].body == 'body1' True >>> db(db.posts.id==post_id).delete() >>> rows = db(db.posts.id==post_id).select() >>> len(rows) == 0 True >>> id = db.posts.insert(total='0') # coerce str to integer >>> rows = db(db.posts.id==id).select() >>> len(rows) == 1 True >>> rows[0].total == 0 True Examples of insert, select, update, delete >>> tmp=db.define_table('person', Field('name'), Field('birth','date'), migrate='test_person.table') >>> marco_id=db.person.insert(name=\"Marco\",birth='2005-06-22') >>> person_id=db.person.insert(name=\"Massimo\",birth='1971-12-21') >>> me=db(db.person.id==person_id).select()[0] # test select >>> me.name 'Massimo' >>> db(db.person.id==person_id).update(name='massimo') # test update >>> me = db(db.person.id==person_id).select()[0] >>> me.name 'massimo' >>> str(me.birth) '1971-12-21' # resave date to ensure it comes back the same >>> me=db(db.person.id==person_id).update(birth=me.birth) # test update >>> me = db(db.person.id==person_id).select()[0] >>> me.birth datetime.date(1971, 12, 21) >>> db(db.person.id==marco_id).delete() # test delete >>> len(db(db.person.id==marco_id).select()) 0 Update a single record >>> me.update_record(name=\"Max\") >>> me.name 'Max' >>> me = db(db.person.id == person_id).select()[0] >>> me.name 'Max' """ SQLField = Field SQLTable = Table SQLXorable = Expression SQLQuery = Query SQLSet = Set SQLRows = Rows SQLStorage = DALStorage if __name__ == '__main__': import doctest doctest.testmod()
Python
SMSCODES = { 'Aliant':'@chat.wirefree.ca', 'Alltel':'@message.alltel.com', 'Ameritech':'@paging.acswireless.com', 'AT&T':'@txt.att.net', 'AU by KDDI':'@ezweb.ne.jp', 'BeeLine GSM':'@sms.beemail.ru', 'Bell Mobility Canada':'@txt.bellmobility.ca', 'Bellsouth':'@bellsouth.cl', 'BellSouth Mobility':'@blsdcs.net', 'Blue Sky Frog':'@blueskyfrog.com', 'Boost':'@myboostmobile.com', 'Cellular South':'@csouth1.com', 'CellularOne':'@mobile.celloneusa.com', 'CellularOne West':'@mycellone.com', 'Cincinnati Bell':'@gocbw.com', 'Claro':'@clarotorpedo.com.br', 'Comviq':'@sms.comviq.se', 'Dutchtone/Orange-NL':'@sms.orange.nl', 'Edge Wireless':'@sms.edgewireless.com', 'EinsteinPCS / Airadigm Communications':'@einsteinsms.com', 'EPlus':'@smsmail.eplus.de', 'Fido Canada':'@fido.ca', 'Golden Telecom':'@sms.goldentele.com', 'Idea Cellular':'@ideacellular.net', 'Kyivstar':'@sms.kyivstar.net', 'LMT':'@sms.lmt.lv', 'Manitoba Telecom Systems':'@text.mtsmobility.com', 'Meteor':'@sms.mymeteor.ie', 'Metro PCS':'@mymetropcs.com', 'Metrocall Pager':'@page.metrocall.com', 'MobileOne':'@m1.com.sg', 'Mobilfone':'@page.mobilfone.com', 'Mobility Bermuda':'@ml.bm', 'Netcom':'@sms.netcom.no', 'Nextel':'@messaging.nextel.com', 'NPI Wireless':'@npiwireless.com', 'O2':'@o2.co.uk', 'O2 M-mail':'@mmail.co.uk', 'Optus':'@optusmobile.com.au', 'Orange':'@orange.net', 'Oskar':'@mujoskar.cz', 'Pagenet':'@pagenet.net', 'PCS Rogers':'@pcs.rogers.com', 'Personal Communication':'@pcom.ru', 'Plus GSM Poland':'@text.plusgsm.pl', 'Powertel':'@ptel.net', 'Primtel':'@sms.primtel.ru', 'PSC Wireless':'@sms.pscel.com', 'Qualcomm':'@pager.qualcomm.com', 'Qwest':'@qwestmp.com', 'Safaricom':'@safaricomsms.com', 'Satelindo GSM':'@satelindogsm.com', 'SCS-900':'@scs-900.ru', 'Simple Freedom':'@text.simplefreedom.net', 'Skytel - Alphanumeric':'@skytel.com', 'Smart Telecom':'@mysmart.mymobile.ph', 'Southern Linc':'@page.southernlinc.com', 'Sprint PCS':'@messaging.sprintpcs.com', 'Sprint PCS - Short Mail':'@sprintpcs.com', 'SunCom':'@tms.suncom.com', 'SureWest Communications':'@mobile.surewest.com', 'SwissCom Mobile':'@bluewin.ch', 'T-Mobile Germany':'@T-D1-SMS.de', 'T-Mobile Netherlands':'@gin.nl', 'T-Mobile UK':'@t-mobile.uk.net', 'T-Mobile USA (tmail)':'@tmail.com', 'T-Mobile USA (tmomail)':'@tmomail.net', 'Tele2 Latvia':'@sms.tele2.lv', 'Telefonica Movistar':'@movistar.net', 'Telenor':'@mobilpost.no', 'Telia Denmark':'@gsm1800.telia.dk', 'Telus Mobility':'@msg.telus.com', 'The Phone House':'@sms.phonehouse.de', 'TIM':'@timnet.com', 'UMC':'@sms.umc.com.ua', 'Unicel':'@utext.com', 'US Cellular':'@email.uscc.net', 'Verizon Wireless (vtext)':'@vtext.com', 'Verizon Wireless (airtouchpaging)':'@airtouchpaging.com', 'Verizon Wireless (myairmail)':'@myairmail.com', 'Vessotel':'@pager.irkutsk.ru', 'Virgin Mobile Canada':'@vmobile.ca', 'Virgin Mobile USA':'@vmobl.com', 'Vodafone Italy':'@sms.vodafone.it', 'Vodafone Japan (n)':'@n.vodafone.ne.jp', 'Vodafone Japan (d)':'@d.vodafone.ne.jp', 'Vodafone Japan (r)':'@r.vodafone.ne.jp', 'Vodafone Japan (k)':'@k.vodafone.ne.jp', 'Vodafone Japan (t)':'@t.vodafone.ne.jp', 'Vodafone Japan (q)':'@q.vodafone.ne.jp', 'Vodafone Japan (s)':'@s.vodafone.ne.jp', 'Vodafone Japan (h)':'@h.vodafone.ne.jp', 'Vodafone Japan (c)':'@c.vodafone.ne.jp', 'Vodafone Spain':'@vodafone.es', 'Vodafone UK':'@vodafone.net', 'Weblink Wireless':'@airmessage.net', 'WellCom':'@sms.welcome2well.com', 'WyndTell':'@wyndtell.com', } def sms_email(number,provider): """ >>> print sms_email('1 (312) 375-6536','T-Mobile USA (tmail)') print 13123756536@tmail.com """ import re if number[0]=='+1': number=number[1:] elif number[0]=='+': number=number[3:] elif number[:2]=='00': number=number[3:] number=re.sub('[^\d]','',number) return number+SMSCODES[provider]
Python
#!/usr/bin/python # -*- coding: latin-1 -*- # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by the # Free Software Foundation; either version 3, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License # for more details. "Visual Template designer for PyFPDF (using wxPython OGL library)" __author__ = "Mariano Reingart <reingart@gmail.com>" __copyright__ = "Copyright (C) 2011 Mariano Reingart" __license__ = "GPL 3.0" __version__ = "1.01a" # Based on: # * pySjetch.py wxPython sample application # * OGL.py and other wxPython demo modules import os, sys import wx import wx.lib.ogl as ogl from wx.lib.wordwrap import wordwrap DEBUG = True class CustomDialog(wx.Dialog): "A dinamyc dialog to ask user about arbitrary fields" def __init__( self, parent, ID, title, size=wx.DefaultSize, pos=wx.DefaultPosition, style=wx.DEFAULT_DIALOG_STYLE, fields=None, data=None, ): wx.Dialog.__init__ (self, parent, ID, title, pos, size, style) sizer = wx.BoxSizer(wx.VERTICAL) self.textctrls = {} for field in fields: box = wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, -1, field) label.SetHelpText("This is the help text for the label") box.Add(label, 1, wx.ALIGN_CENTRE|wx.ALL, 5) text = wx.TextCtrl(self, -1, "", size=(80,-1)) text.SetHelpText("Here's some help text for field #1") if field in data: text.SetValue(repr(data[field])) box.Add(text, 1, wx.ALIGN_CENTRE|wx.ALL, 1) sizer.Add(box, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 1) self.textctrls[field] = text line = wx.StaticLine(self, -1, size=(20,-1), style=wx.LI_HORIZONTAL) sizer.Add(line, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.RIGHT|wx.TOP, 5) btnsizer = wx.StdDialogButtonSizer() btn = wx.Button(self, wx.ID_OK) btn.SetHelpText("The OK button completes the dialog") btn.SetDefault() btnsizer.AddButton(btn) btn = wx.Button(self, wx.ID_CANCEL) btn.SetHelpText("The Cancel button cancels the dialog. (Cool, huh?)") btnsizer.AddButton(btn) btnsizer.Realize() sizer.Add(btnsizer, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5) self.SetSizer(sizer) sizer.Fit(self) @classmethod def do_input(Class, parent, title, fields, data): dlg = Class(parent, -1, title, size=(350, 200), style=wx.DEFAULT_DIALOG_STYLE, # & ~wx.CLOSE_BOX, fields=fields, data=data ) dlg.CenterOnScreen() while 1: val = dlg.ShowModal() if val == wx.ID_OK: values = {} for field in fields: try: values[field] = eval(dlg.textctrls[field].GetValue()) except Exception, e: msg = wx.MessageDialog(parent, unicode(e), "Error in field %s" % field, wx.OK | wx.ICON_INFORMATION ) msg.ShowModal() msg.Destroy() break else: return dict([(field, values[field]) for field in fields]) else: return None class MyEvtHandler(ogl.ShapeEvtHandler): "Custom Event Handler for Shapes" def __init__(self, callback): ogl.ShapeEvtHandler.__init__(self) self.callback = callback def OnLeftClick(self, x, y, keys=0, attachment=0): shape = self.GetShape() canvas = shape.GetCanvas() dc = wx.ClientDC(canvas) canvas.PrepareDC(dc) if shape.Selected() and keys & ogl.KEY_SHIFT: shape.Select(False, dc) #canvas.Redraw(dc) canvas.Refresh(False) else: redraw = False shapeList = canvas.GetDiagram().GetShapeList() toUnselect = [] for s in shapeList: if s.Selected() and not keys & ogl.KEY_SHIFT: # If we unselect it now then some of the objects in # shapeList will become invalid (the control points are # shapes too!) and bad things will happen... toUnselect.append(s) shape.Select(True, dc) if toUnselect: for s in toUnselect: s.Select(False, dc) ##canvas.Redraw(dc) canvas.Refresh(False) self.callback() def OnEndDragLeft(self, x, y, keys=0, attachment=0): shape = self.GetShape() ogl.ShapeEvtHandler.OnEndDragLeft(self, x, y, keys, attachment) if not shape.Selected(): self.OnLeftClick(x, y, keys, attachment) self.callback() def OnSizingEndDragLeft(self, pt, x, y, keys, attch): ogl.ShapeEvtHandler.OnSizingEndDragLeft(self, pt, x, y, keys, attch) self.callback() def OnMovePost(self, dc, x, y, oldX, oldY, display): shape = self.GetShape() ogl.ShapeEvtHandler.OnMovePost(self, dc, x, y, oldX, oldY, display) self.callback() if "wxMac" in wx.PlatformInfo: shape.GetCanvas().Refresh(False) def OnLeftDoubleClick(self, x, y, keys = 0, attachment = 0): self.callback("LeftDoubleClick") def OnRightClick(self, *dontcare): self.callback("RightClick") class Element(object): "Visual class that represent a placeholder in the template" fields = ['name', 'type', 'x1', 'y1', 'x2', 'y2', 'font', 'size', 'bold', 'italic', 'underline', 'foreground', 'background', 'align', 'text', 'priority',] def __init__(self, canvas=None, frame=None, zoom=5.0, static=False, **kwargs): self.kwargs = kwargs self.zoom = zoom self.frame = frame self.canvas = canvas self.static = static name = kwargs['name'] kwargs['type'] type = kwargs['type'] x, y, w, h = self.set_coordinates(kwargs['x1'], kwargs['y1'], kwargs['x2'], kwargs['y2']) text = kwargs['text'] shape = self.shape = ogl.RectangleShape(w, h) if not static: shape.SetDraggable(True, True) shape.SetX(x) shape.SetY(y) #if pen: shape.SetPen(pen) #if brush: shape.SetBrush(brush) shape.SetBrush(wx.TRANSPARENT_BRUSH) if type not in ('L', 'B', 'BC'): if not static: pen = wx.LIGHT_GREY_PEN else: pen = wx.RED_PEN shape.SetPen(pen) self.text = kwargs['text'] evthandler = MyEvtHandler(self.evt_callback) evthandler.SetShape(shape) evthandler.SetPreviousHandler(shape.GetEventHandler()) shape.SetEventHandler(evthandler) shape.SetCentreResize(False) shape.SetMaintainAspectRatio(False) canvas.AddShape( shape ) @classmethod def new(Class, parent): data = dict(name='some_name', type='T', x1=5.0, y1=5.0, x2=100.0, y2=10.0, font="Arial", size=12, bold=False, italic=False, underline=False, foreground= 0x000000, background=0xFFFFFF, align="L", text="", priority=0) data = CustomDialog.do_input(parent, 'New element', Class.fields, data) if data: return Class(canvas=parent.canvas, frame=parent, **data) def edit(self): "Edit current element (show a dialog box with all fields)" data = self.kwargs.copy() x1, y1, x2, y2 = self.get_coordinates() data.update(dict(name=self.name, text=self.text, x1=x1, y1=y1, x2=x2, y2=y2, )) data = CustomDialog.do_input(self.frame, 'Edit element', self.fields, data) if data: self.kwargs.update(data) self.name = data['name'] self.text = data['text'] x,y, w, h = self.set_coordinates(data['x1'], data['y1'], data['x2'], data['y2']) self.shape.SetX(x) self.shape.SetY(y) self.shape.SetWidth(w) self.shape.SetHeight(h) self.canvas.Refresh(False) self.canvas.GetDiagram().ShowAll(1) def edit_text(self): "Allow text edition (i.e. for doubleclick)" dlg = wx.TextEntryDialog( self.frame, 'Text for %s' % self.name, 'Edit Text', '') if self.text: dlg.SetValue(self.text) if dlg.ShowModal() == wx.ID_OK: self.text = dlg.GetValue().encode("latin1") dlg.Destroy() def copy(self): "Return an identical duplicate" kwargs = self.as_dict() element = Element(canvas=self.canvas, frame=self.frame, zoom=self.zoom, static=self.static, **kwargs) return element def remove(self): "Erases visual shape from OGL canvas (element must be deleted manually)" self.canvas.RemoveShape(self.shape) def move(self, dx, dy): "Change pdf coordinates (converting to wx internal values)" x1, y1, x2, y2 = self.get_coordinates() x1 += dx x2 += dx y1 += dy y2 += dy x, y, w, h = self.set_coordinates(x1, y1, x2, y2) self.shape.SetX(x) self.shape.SetY(y) def evt_callback(self, evt_type=None): "Event dispatcher" if evt_type=="LeftDoubleClick": self.edit_text() if evt_type=='RightClick': self.edit() # update the status bar x1, y1, x2, y2 = self.get_coordinates() self.frame.SetStatusText("%s (%0.2f, %0.2f) - (%0.2f, %0.2f)" % (self.name, x1, y1, x2, y2)) def get_coordinates(self): "Convert from wx to pdf coordinates" x, y = self.shape.GetX(), self.shape.GetY() w, h = self.shape.GetBoundingBoxMax() w -= 1 h -= 1 x1 = x/self.zoom - w/self.zoom/2.0 x2 = x/self.zoom + w/self.zoom/2.0 y1 = y/self.zoom - h/self.zoom/2.0 y2 = y/self.zoom + h/self.zoom/2.0 return x1, y1, x2, y2 def set_coordinates(self, x1, y1, x2, y2): "Convert from pdf to wx coordinates" x1 = x1 * self.zoom x2 = x2 * self.zoom y1 = y1 * self.zoom y2 = y2 * self.zoom # shapes seems to be centred, pdf coord not w = max(x1, x2) - min(x1, x2) + 1 h = max(y1, y2) - min(y1, y2) + 1 x = (min(x1, x2) + w/2.0) y = (min(y1, y2) + h/2.0) return x, y, w, h def text(self, txt=None): if txt is not None: if not isinstance(txt,str): txt = str(txt) self.kwargs['text'] = txt self.shape.ClearText() for line in txt.split('\n'): self.shape.AddText(unicode(line, "latin1")) self.canvas.Refresh(False) return self.kwargs['text'] text = property(text, text) def set_x(self, x): self.shape.SetX(x) self.canvas.Refresh(False) self.evt_callback() def set_y(self, y): self.shape.SetY(y) self.canvas.Refresh(False) self.evt_callback() def get_x(self): return self.shape.GetX() def get_y(self): return self.shape.GetY() x = property(get_x, set_x) y = property(get_y, set_y) def selected(self, sel=None): if sel is not None: print "Setting Select(%s)" % sel self.shape.Select(sel) return self.shape.Selected() selected = property(selected, selected) def name(self, name=None): if name is not None: self.kwargs['name'] = name return self.kwargs['name'] name = property(name, name) def __contains__(self, k): "Implement in keyword for searchs" return k in self.name.lower() or self.text and k in self.text.lower() def as_dict(self): "Return a dictionary representation, used by pyfpdf" d = self.kwargs x1, y1, x2, y2 = self.get_coordinates() d.update({ 'x1': x1, 'y1': y1, 'x2': x2, 'y2': y2, 'text': self.text}) return d class AppFrame(wx.Frame): "OGL Designer main window" title = "PyFPDF Template Designer (wx OGL)" def __init__(self): wx.Frame.__init__( self, None, -1, self.title, size=(640,480), style=wx.DEFAULT_FRAME_STYLE ) sys.excepthook = self.except_hook self.filename = "" # Create a toolbar: tsize = (16,16) self.toolbar = self.CreateToolBar(wx.TB_HORIZONTAL | wx.NO_BORDER | wx.TB_FLAT) artBmp = wx.ArtProvider.GetBitmap self.toolbar.AddSimpleTool( wx.ID_NEW, artBmp(wx.ART_NEW, wx.ART_TOOLBAR, tsize), "New") self.toolbar.AddSimpleTool( wx.ID_OPEN, artBmp(wx.ART_FILE_OPEN, wx.ART_TOOLBAR, tsize), "Open") self.toolbar.AddSimpleTool( wx.ID_SAVE, artBmp(wx.ART_FILE_SAVE, wx.ART_TOOLBAR, tsize), "Save") self.toolbar.AddSimpleTool( wx.ID_SAVEAS, artBmp(wx.ART_FILE_SAVE_AS, wx.ART_TOOLBAR, tsize), "Save As...") #------- self.toolbar.AddSeparator() self.toolbar.AddSimpleTool( wx.ID_UNDO, artBmp(wx.ART_UNDO, wx.ART_TOOLBAR, tsize), "Undo") self.toolbar.AddSimpleTool( wx.ID_REDO, artBmp(wx.ART_REDO, wx.ART_TOOLBAR, tsize), "Redo") self.toolbar.AddSeparator() #------- self.toolbar.AddSimpleTool( wx.ID_CUT, artBmp(wx.ART_CUT, wx.ART_TOOLBAR, tsize), "Remove") self.toolbar.AddSimpleTool( wx.ID_COPY, artBmp(wx.ART_COPY, wx.ART_TOOLBAR, tsize), "Duplicate") self.toolbar.AddSimpleTool( wx.ID_PASTE, artBmp(wx.ART_PASTE, wx.ART_TOOLBAR, tsize), "Insert") self.toolbar.AddSeparator() self.toolbar.AddSimpleTool( wx.ID_FIND, artBmp(wx.ART_FIND, wx.ART_TOOLBAR, tsize), "Find") self.toolbar.AddSeparator() self.toolbar.AddSimpleTool( wx.ID_PRINT, artBmp(wx.ART_PRINT, wx.ART_TOOLBAR, tsize), "Print") self.toolbar.AddSimpleTool( wx.ID_ABOUT, artBmp(wx.ART_HELP, wx.ART_TOOLBAR, tsize), "About") self.toolbar.Realize() self.toolbar.EnableTool(wx.ID_SAVEAS, False) self.toolbar.EnableTool(wx.ID_UNDO, False) self.toolbar.EnableTool(wx.ID_REDO, False) menu_handlers = [ (wx.ID_NEW, self.do_new), (wx.ID_OPEN, self.do_open), (wx.ID_SAVE, self.do_save), (wx.ID_PRINT, self.do_print), (wx.ID_FIND, self.do_find), (wx.ID_CUT, self.do_cut), (wx.ID_COPY, self.do_copy), (wx.ID_PASTE, self.do_paste), (wx.ID_ABOUT, self.do_about), ] for menu_id, handler in menu_handlers: self.Bind(wx.EVT_MENU, handler, id = menu_id) sizer = wx.BoxSizer(wx.VERTICAL) # put stuff into sizer self.CreateStatusBar() canvas = self.canvas = ogl.ShapeCanvas( self ) maxWidth = 1500 maxHeight = 2000 canvas.SetScrollbars(20, 20, maxWidth/20, maxHeight/20) sizer.Add( canvas, 1, wx.GROW ) canvas.SetBackgroundColour("WHITE") # diagram = self.diagram = ogl.Diagram() canvas.SetDiagram( diagram ) diagram.SetCanvas( canvas ) diagram.SetSnapToGrid( False ) # apply sizer self.SetSizer(sizer) self.SetAutoLayout(1) self.Show(1) self.Bind(wx.EVT_CHAR_HOOK, self.on_key_event) self.elements = [] def on_key_event(self, event): """ Respond to a keypress event. We make the arrow keys move the selected object(s) by one pixel in the given direction. """ step = 1 if event.ControlDown(): step = 20 if event.GetKeyCode() == wx.WXK_UP: self.move_elements(0, -step) elif event.GetKeyCode() == wx.WXK_DOWN: self.move_elements(0, step) elif event.GetKeyCode() == wx.WXK_LEFT: self.move_elements(-step, 0) elif event.GetKeyCode() == wx.WXK_RIGHT: self.move_elements(step, 0) elif event.GetKeyCode() == wx.WXK_DELETE: self.do_cut() else: event.Skip() def do_new(self, evt=None): for element in self.elements: element.remove() self.elements = [] # draw paper size guides for k, (w, h) in [('legal', (216, 356)), ('A4', (210, 297)), ('letter', (216, 279))]: self.create_elements( k, 'R', 0, 0, w, h, size=70, foreground=0x808080, priority=-100, canvas=self.canvas, frame=self, static=True) self.diagram.ShowAll( 1 ) def do_open(self, evt): dlg = wx.FileDialog( self, message="Choose a file", defaultDir=os.getcwd(), defaultFile="invoice.csv", wildcard="CSV Files (*.csv)|*.csv", style=wx.OPEN ) if dlg.ShowModal() == wx.ID_OK: # This returns a Python list of files that were selected. self.filename = dlg.GetPaths()[0] dlg.Destroy() self.SetTitle(self.filename + " - " + self.title) self.do_new() tmp = [] f = open(self.filename) try: filedata = f.readlines() finally: f.close() for lno, linea in enumerate(filedata): if DEBUG: print "processing line", lno, linea args = [] for i,v in enumerate(linea.split(";")): if not v.startswith("'"): v = v.replace(",",".") else: v = v#.decode('latin1') if v.strip()=='': v = None else: v = eval(v.strip()) args.append(v) tmp.append(args) # sort by z-order (priority) for args in sorted(tmp, key=lambda t: t[-1]): if DEBUG: print args self.create_elements(*args) self.diagram.ShowAll( 1 ) # return True def do_save(self, evt, filename=None): try: from time import gmtime, strftime ts = strftime("%Y%m%d%H%M%S", gmtime()) os.rename(self.filename, self.filename + ts + ".bak") except Exception, e: if DEBUG: print e pass def csv_repr(v, decimal_sep="."): if isinstance(v, float): return ("%0.2f" % v).replace(".", decimal_sep) else: return repr(v) f = open(self.filename, "w") try: for element in sorted(self.elements, key=lambda e:e.name): if element.static: continue d = element.as_dict() l = [d['name'], d['type'], d['x1'], d['y1'], d['x2'], d['y2'], d['font'], d['size'], d['bold'], d['italic'], d['underline'], d['foreground'], d['background'], d['align'], d['text'], d['priority'], ] f.write(";".join([csv_repr(v) for v in l])) f.write("\n") finally: f.close() def do_print(self, evt): # genero el renderizador con propiedades del PDF from template import Template t = Template(elements=[e.as_dict() for e in self.elements if not e.static]) t.add_page() if not t['logo'] or not os.path.exists(t['logo']): # put a default logo so it doesn't trow an exception logo = os.path.join(os.path.dirname(__file__), 'tutorial','logo.png') t.set('logo', logo) try: t.render(self.filename +".pdf") except: if DEBUG and False: import pdb; pdb.pm() else: raise if sys.platform=="linux2": os.system("evince ""%s""" % self.filename +".pdf") else: os.startfile(self.filename +".pdf") def do_find(self, evt): # busco nombre o texto dlg = wx.TextEntryDialog( self, 'Enter text to search for', 'Find Text', '') if dlg.ShowModal() == wx.ID_OK: txt = dlg.GetValue().encode("latin1").lower() for element in self.elements: if txt in element: element.selected = True print "Found:", element.name self.canvas.Refresh(False) dlg.Destroy() def do_cut(self, evt=None): "Delete selected elements" new_elements = [] for element in self.elements: if element.selected: print "Erasing:", element.name element.selected = False self.canvas.Refresh(False) element.remove() else: new_elements.append(element) self.elements = new_elements self.canvas.Refresh(False) self.diagram.ShowAll( 1 ) def do_copy(self, evt): "Duplicate selected elements" fields = ['qty', 'dx', 'dy'] data = {'qty': 1, 'dx': 0.0, 'dy': 5.0} data = CustomDialog.do_input(self, 'Copy elements', fields, data) if data: new_elements = [] for i in range(1, data['qty']+1): for element in self.elements: if element.selected: print "Copying:", element.name new_element = element.copy() name = new_element.name if len(name)>2 and name[-2:].isdigit(): new_element.name = name[:-2] + "%02d" % (int(name[-2:])+i) else: new_element.name = new_element.name + "_copy" new_element.selected = False new_element.move(data['dx']*i, data['dy']*i) new_elements.append(new_element) self.elements.extend(new_elements) self.canvas.Refresh(False) self.diagram.ShowAll( 1 ) def do_paste(self, evt): "Insert new elements" element = Element.new(self) if element: self.canvas.Refresh(False) self.elements.append(element) self.diagram.ShowAll( 1 ) def create_elements(self, name, type, x1, y1, x2, y2, font="Arial", size=12, bold=False, italic=False, underline=False, foreground= 0x000000, background=0xFFFFFF, align="L", text="", priority=0, canvas=None, frame=None, static=False, **kwargs): element = Element(name=name, type=type, x1=x1, y1=y1, x2=x2, y2=y2, font=font, size=size, bold=bold, italic=italic, underline=underline, foreground= foreground, background=background, align=align, text=text, priority=priority, canvas=canvas or self.canvas, frame=frame or self, static=static) self.elements.append(element) def move_elements(self, x, y): for element in self.elements: if element.selected: print "moving", element.name, x, y element.x = element.x + x element.y = element.y + y def do_about(self, evt): info = wx.AboutDialogInfo() info.Name = self.title info.Version = __version__ info.Copyright = __copyright__ info.Description = ( "Visual Template designer for PyFPDF (using wxPython OGL library)\n" "Input files are CSV format describing the layout, separated by ;\n" "Use toolbar buttons to open, save, print (preview) your template, " "and there are buttons to find, add, remove or duplicate elements.\n" "Over an element, a double left click opens edit text dialog, " "and a right click opens edit properties dialog. \n" "Multiple element can be selected with shift left click. \n" "Use arrow keys or drag-and-drop to move elements.\n" "For further information see project webpage:" ) info.WebSite = ("http://code.google.com/p/pyfpdf/wiki/Templates", "pyfpdf Google Code Project") info.Developers = [ __author__, ] info.License = wordwrap(__license__, 500, wx.ClientDC(self)) # Then we call wx.AboutBox giving it that info object wx.AboutBox(info) def except_hook(self, type, value, trace): import traceback exc = traceback.format_exception(type, value, trace) for e in exc: wx.LogError(e) wx.LogError('Unhandled Error: %s: %s'%(str(type), str(value))) app = wx.PySimpleApp() ogl.OGLInitialize() frame = AppFrame() app.MainLoop() app.Destroy()
Python
# -*- coding: iso-8859-1 -*- "PDF Template Helper for FPDF.py" __author__ = "Mariano Reingart <reingart@gmail.com>" __copyright__ = "Copyright (C) 2010 Mariano Reingart" __license__ = "LGPL 3.0" import sys,os,csv from fpdf import FPDF def rgb(col): return (col // 65536), (col // 256 % 256), (col% 256) class Template: def __init__(self, infile=None, elements=None, format='A4', orientation='portrait', title='', author='', subject='', creator='', keywords=''): if elements: self.elements = dict([(v['name'].lower(),v) for v in elements]) self.handlers = {'T': self.text, 'L': self.line, 'I': self.image, 'B': self.rect, 'BC': self.barcode, } self.pg_no = 0 self.texts = {} pdf = self.pdf = FPDF(format=format,orientation=orientation, unit="mm") pdf.set_title(title) pdf.set_author(author) pdf.set_creator(creator) pdf.set_subject(subject) pdf.set_keywords(keywords) def parse_csv(self, infile, delimiter=",", decimal_sep="."): "Parse template format csv file and create elements dict" keys = ('name','type','x1','y1','x2','y2','font','size', 'bold','italic','underline','foreground','background', 'align','text','priority') self.elements = {} f = open(infile, 'rb') try: for row in csv.reader(f, delimiter=delimiter): kargs = {} for i,v in enumerate(row): if not v.startswith("'") and decimal_sep!=".": v = v.replace(decimal_sep,".") else: v = v if v=='': v = None else: v = eval(v.strip()) kargs[keys[i]] = v self.elements[kargs['name'].lower()] = kargs finally: f.close() def add_page(self): self.pg_no += 1 self.texts[self.pg_no] = {} def __setitem__(self, name, value): if name.lower() in self.elements: if isinstance(value,unicode): value = value.encode("latin1","ignore") else: value = str(value) self.texts[self.pg_no][name.lower()] = value # setitem shortcut (may be further extended) set = __setitem__ def __getitem__(self, name): if name.lower() in self.elements: return self.texts[self.pg_no].get(name.lower(), self.elements[name.lower()]['text']) def split_multicell(self, text, element_name): "Divide (\n) a string using a given element width" pdf = self.pdf element = self.elements[element_name.lower()] style = "" if element['bold']: style += "B" if element['italic']: style += "I" if element['underline']: style += "U" pdf.set_font(element['font'],style,element['size']) align = {'L':'L','R':'R','I':'L','D':'R','C':'C','':''}.get(element['align']) # D/I in spanish if isinstance(text, unicode): text = text.encode("latin1","ignore") else: text = str(text) return pdf.multi_cell(w=element['x2']-element['x1'], h=element['y2']-element['y1'], txt=text,align=align,split_only=True) def render(self, outfile, dest="F"): pdf = self.pdf for pg in range(1, self.pg_no+1): pdf.add_page() pdf.set_font('Arial','B',16) pdf.set_auto_page_break(False,margin=0) for element in sorted(self.elements.values(),key=lambda x: x['priority']): #print "dib",element['type'], element['name'], element['x1'], element['y1'], element['x2'], element['y2'] element = element.copy() element['text'] = self.texts[pg].get(element['name'].lower(), element['text']) if 'rotate' in element: pdf.rotate(element['rotate'], element['x1'], element['y1']) self.handlers[element['type'].upper()](pdf, **element) if 'rotate' in element: pdf.rotate(0) return pdf.output(outfile, dest) def text(self, pdf, x1=0, y1=0, x2=0, y2=0, text='', font="arial", size=10, bold=False, italic=False, underline=False, align="", foreground=0, backgroud=65535, *args, **kwargs): if text: if pdf.text_color!=rgb(foreground): pdf.set_text_color(*rgb(foreground)) if pdf.fill_color!=rgb(backgroud): pdf.set_fill_color(*rgb(backgroud)) font = font.strip().lower() if font == 'arial black': font = 'arial' style = "" for tag in 'B', 'I', 'U': if (text.startswith("<%s>" % tag) and text.endswith("</%s>" %tag)): text = text[3:-4] style += tag if bold: style += "B" if italic: style += "I" if underline: style += "U" align = {'L':'L','R':'R','I':'L','D':'R','C':'C','':''}.get(align) # D/I in spanish pdf.set_font(font,style,size) ##m_k = 72 / 2.54 ##h = (size/m_k) pdf.set_xy(x1,y1) pdf.cell(w=x2-x1,h=y2-y1,txt=text,border=0,ln=0,align=align) #pdf.Text(x=x1,y=y1,txt=text) def line(self, pdf, x1=0, y1=0, x2=0, y2=0, size=0, foreground=0, *args, **kwargs): if pdf.draw_color!=rgb(foreground): #print "SetDrawColor", hex(foreground) pdf.set_draw_color(*rgb(foreground)) #print "SetLineWidth", size pdf.set_line_width(size) pdf.line(x1, y1, x2, y2) def rect(self, pdf, x1=0, y1=0, x2=0, y2=0, size=0, foreground=0, backgroud=65535, *args, **kwargs): if pdf.draw_color!=rgb(foreground): pdf.set_draw_color(*rgb(foreground)) if pdf.fill_color!=rgb(backgroud): pdf.set_fill_color(*rgb(backgroud)) pdf.set_line_width(size) pdf.rect(x1, y1, x2-x1, y2-y1) def image(self, pdf, x1=0, y1=0, x2=0, y2=0, text='', *args,**kwargs): pdf.image(text,x1,y1,w=x2-x1,h=y2-y1,type='',link='') def barcode(self, pdf, x1=0, y1=0, x2=0, y2=0, text='', font="arial", size=1, foreground=0, *args, **kwargs): if pdf.draw_color!=rgb(foreground): pdf.set_draw_color(*rgb(foreground)) font = font.lower().strip() if font == 'interleaved 2of5 nt': pdf.interleaved2of5(text,x1,y1,w=size,h=y2-y1) if __name__ == "__main__": # generate sample invoice (according Argentina's regulations) import random from decimal import Decimal f = Template(format="A4", title="Sample Invoice", author="Sample Company", subject="Sample Customer", keywords="Electronic TAX Invoice") f.parse_csv(infile="invoice.csv", delimiter=";", decimal_sep=",") detail = "Lorem ipsum dolor sit amet, consectetur. " * 30 items = [] for i in range(1, 30): ds = "Sample product %s" % i qty = random.randint(1,10) price = round(random.random()*100,3) code = "%s%s%02d" % (chr(random.randint(65,90)), chr(random.randint(65,90)),i) items.append(dict(code=code, unit='u', qty=qty, price=price, amount=qty*price, ds="%s: %s" % (i,ds))) # divide and count lines lines = 0 li_items = [] for it in items: qty = it['qty'] code = it['code'] unit = it['unit'] for ds in f.split_multicell(it['ds'], 'item_description01'): # add item description line (without price nor amount) li_items.append(dict(code=code, ds=ds, qty=qty, unit=unit, price=None, amount=None)) # clean qty and code (show only at first) unit = qty = code = None # set last item line price and amount li_items[-1].update(amount = it['amount'], price = it['price']) obs="\n<U>Detail:</U>\n\n" + detail for ds in f.split_multicell(obs, 'item_description01'): li_items.append(dict(code=code, ds=ds, qty=qty, unit=unit, price=None, amount=None)) # calculate pages: lines = len(li_items) max_lines_per_page = 24 pages = lines / (max_lines_per_page - 1) if lines % (max_lines_per_page - 1): pages = pages + 1 # completo campos y hojas for page in range(1, pages+1): f.add_page() f['page'] = 'Page %s of %s' % (page, pages) if pages>1 and page<pages: s = 'Continues on page %s' % (page+1) else: s = '' f['item_description%02d' % (max_lines_per_page+1)] = s f["company_name"] = "Sample Company" f["company_logo"] = "tutorial/logo.png" f["company_header1"] = "Some Address - somewhere -" f["company_header2"] = "http://www.example.com" f["company_footer1"] = "Tax Code ..." f["company_footer2"] = "Tax/VAT ID ..." f['number'] = '0001-00001234' f['issue_date'] = '2010-09-10' f['due_date'] = '2099-09-10' f['customer_name'] = "Sample Client" f['customer_address'] = "Siempreviva 1234" # print line item... li = 0 k = 0 total = Decimal("0.00") for it in li_items: k = k + 1 if k > page * (max_lines_per_page - 1): break if it['amount']: total += Decimal("%.6f" % it['amount']) if k > (page - 1) * (max_lines_per_page - 1): li += 1 if it['qty'] is not None: f['item_quantity%02d' % li] = it['qty'] if it['code'] is not None: f['item_code%02d' % li] = it['code'] if it['unit'] is not None: f['item_unit%02d' % li] = it['unit'] f['item_description%02d' % li] = it['ds'] if it['price'] is not None: f['item_price%02d' % li] = "%0.3f" % it['price'] if it['amount'] is not None: f['item_amount%02d' % li] = "%0.2f" % it['amount'] if pages == page: f['net'] = "%0.2f" % (total/Decimal("1.21")) f['vat'] = "%0.2f" % (total*(1-1/Decimal("1.21"))) f['total_label'] = 'Total:' else: f['total_label'] = 'SubTotal:' f['total'] = "%0.2f" % total f.render("./invoice.pdf") if sys.platform.startswith("linux"): os.system("evince ./invoice.pdf") else: os.system("./invoice.pdf")
Python
# -*- coding: latin-1 -*- "HTML Renderer for FPDF.py" __author__ = "Mariano Reingart <reingart@gmail.com>" __copyright__ = "Copyright (C) 2010 Mariano Reingart" __license__ = "LGPL 3.0" # Inspired by tuto5.py and several examples from fpdf.org, html2fpdf, etc. from fpdf import FPDF from HTMLParser import HTMLParser DEBUG = False def px2mm(px): return int(px)*25.4/72.0 def hex2dec(color = "#000000"): if color: r = int(color[1:3], 16) g = int(color[3:5], 16) b = int(color[5:7], 16) return r, g, b class HTML2FPDF(HTMLParser): "Render basic HTML to FPDF" def __init__(self, pdf, image_map): HTMLParser.__init__(self) self.image_map = image_map self.style = {} self.pre = False self.href = '' self.align = '' self.page_links = {} self.font_list = ("times","courier", "helvetica") self.pdf = pdf self.r = self.g = self.b = 0 self.indent = 0 self.bullet = [] self.set_font("times", 12) self.table = None # table attributes self.table_col_width = None # column (header) widths self.table_col_index = None # current column index self.td = None # cell attributes self.th = False # header enabled self.tr = None self.theader = None # table header cells self.tfooter = None # table footer cells self.thead = None self.tfoot = None self.theader_out = self.tfooter_out = False def width2mm(self, length): if length[-1]=='%': total = self.pdf.w - self.pdf.r_margin - self.pdf.l_margin if self.table['width'][-1]=='%': total *= int(self.table['width'][:-1])/100.0 return int(length[:-1]) * total / 101.0 else: return int(length) / 6.0 def handle_data(self, txt): if self.td is not None: # drawing a table? if 'width' not in self.td and 'colspan' not in self.td: l = [self.table_col_width[self.table_col_index]] elif 'colspan' in self.td: i = self.table_col_index colspan = int(self.td['colspan']) l = self.table_col_width[i:i+colspan] else: l = [self.td.get('width','240')] w = sum([self.width2mm(lenght) for lenght in l]) h = int(self.td.get('height', 0)) / 4 or self.h*1.30 self.table_h = h border = int(self.table.get('border', 0)) if not self.th: align = self.td.get('align', 'L')[0].upper() border = border and 'LR' else: self.set_style('B',True) border = border or 'B' align = 'C' bgcolor = hex2dec(self.td.get('bgcolor', self.tr.get('bgcolor', ''))) # parsing table header/footer (drawn later): if self.thead is not None: self.theader.append(((w,h,txt,border,0,align), bgcolor)) if self.tfoot is not None: self.tfooter.append(((w,h,txt,border,0,align), bgcolor)) # check if reached end of page, add table footer and header: height = h + (self.tfooter and self.tfooter[0][0][1] or 0) if self.pdf.y+height>self.pdf.page_break_trigger and not self.th: self.output_table_footer() self.pdf.add_page() self.theader_out = self.tfooter_out = False if self.tfoot is None and self.thead is None: if not self.theader_out: self.output_table_header() self.box_shadow(w, h, bgcolor) if DEBUG: print "td cell", self.pdf.x, w, txt, "*" self.pdf.cell(w,h,txt,border,0,align) elif self.table is not None: # ignore anything else than td inside a table pass elif self.align: if DEBUG: print "cell", txt, "*" self.pdf.cell(0,self.h,txt,0,1,self.align[0].upper(), self.href) else: txt = txt.replace("\n"," ") if self.href: self.put_link(self.href,txt) else: if DEBUG: print "write", txt, "*" self.pdf.write(self.h,txt) def box_shadow(self, w, h, bgcolor): if DEBUG: print "box_shadow", w, h, bgcolor if bgcolor: fill_color = self.pdf.fill_color self.pdf.set_fill_color(*bgcolor) self.pdf.rect(self.pdf.x, self.pdf.y, w, h, 'F') self.pdf.fill_color = fill_color def output_table_header(self): if self.theader: b = self.b x = self.pdf.x self.pdf.set_x(self.table_offset) self.set_style('B',True) for cell, bgcolor in self.theader: self.box_shadow(cell[0], cell[1], bgcolor) self.pdf.cell(*cell) self.set_style('B',b) self.pdf.ln(self.theader[0][0][1]) self.pdf.set_x(self.table_offset) #self.pdf.set_x(x) self.theader_out = True def output_table_footer(self): if self.tfooter: x = self.pdf.x self.pdf.set_x(self.table_offset) #TODO: self.output_table_sep() for cell, bgcolor in self.tfooter: self.box_shadow(cell[0], cell[1], bgcolor) self.pdf.cell(*cell) self.pdf.ln(self.tfooter[0][0][1]) self.pdf.set_x(x) if int(self.table.get('border', 0)): self.output_table_sep() self.tfooter_out = True def output_table_sep(self): self.pdf.set_x(self.table_offset) x1 = self.pdf.x y1 = self.pdf.y w = sum([self.width2mm(lenght) for lenght in self.table_col_width]) self.pdf.line(x1,y1,x1+w,y1) def handle_starttag(self, tag, attrs): attrs = dict(attrs) if DEBUG: print "STARTTAG", tag, attrs if tag=='b' or tag=='i' or tag=='u': self.set_style(tag,1) if tag=='a': self.href=attrs['href'] if tag=='br': self.pdf.ln(5) if tag=='p': self.pdf.ln(5) if attrs: self.align=attrs['align'].lower() if tag in ('h1', 'h2', 'h3', 'h4', 'h5', 'h6'): k = (2, 1.5, 1.17, 1, 0.83, 0.67)[int(tag[1])] self.pdf.ln(5*k) self.pdf.set_text_color(150,0,0) self.pdf.set_font_size(12 * k) if attrs: self.align = attrs.get('align') if tag=='hr': self.put_line() if tag=='pre': self.pdf.set_font('Courier','',11) self.pdf.set_font_size(11) self.set_style('B',False) self.set_style('I',False) self.pre = True if tag=='blockquote': self.set_text_color(100,0,45) self.pdf.ln(3) if tag=='ul': self.indent+=1 self.bullet.append('\x95') if tag=='ol': self.indent+=1 self.bullet.append(0) if tag=='li': self.pdf.ln(self.h+2) self.pdf.set_text_color(190,0,0) bullet = self.bullet[self.indent-1] if not isinstance(bullet, basestring): bullet += 1 self.bullet[self.indent-1] = bullet bullet = "%s. " % bullet self.pdf.write(self.h,'%s%s ' % (' '*5*self.indent, bullet)) self.set_text_color() if tag=='font': if 'color' in attrs: self.color = hex2dec(attrs['color']) self.set_text_color(*color) self.color = color if 'face' in attrs and attrs['face'].lower() in self.font_list: face = attrs.get('face').lower() self.pdf.set_font(face) self.font_face = face if 'size' in attrs: face = attrs.get('size') self.pdf.set_font('', size) self.font_size = size if tag=='table': self.table = dict([(k.lower(), v) for k,v in attrs.items()]) if not 'width' in self.table: self.table['width'] = '100%' if self.table['width'][-1]=='%': w = self.pdf.w - self.pdf.r_margin - self.pdf.l_margin w *= int(self.table['width'][:-1])/100.0 self.table_offset = (self.pdf.w-w)/2.0 self.table_col_width = [] self.theader_out = self.tfooter_out = False self.theader = [] self.tfooter = [] self.thead = None self.tfoot = None self.pdf.ln() if tag=='tr': self.tr = dict([(k.lower(), v) for k,v in attrs.items()]) self.table_col_index = 0 self.pdf.set_x(self.table_offset) if tag=='td': self.td = dict([(k.lower(), v) for k,v in attrs.items()]) if tag=='th': self.td = dict([(k.lower(), v) for k,v in attrs.items()]) self.th = True if self.td['width']: self.table_col_width.append(self.td['width']) if tag=='thead': self.thead = {} if tag=='tfoot': self.tfoot = {} if tag=='img': if 'src' in attrs: x = self.pdf.get_x() y = self.pdf.get_y() w = px2mm(attrs.get('width', 0)) h = px2mm(attrs.get('height',0)) if self.align and self.align[0].upper() == 'C': x = (self.pdf.w-x)/2.0 - w/2.0 self.pdf.image(self.image_map(attrs['src']), x, y, w, h, link=self.href) self.pdf.set_x(x+w) self.pdf.set_y(y+h) if tag=='b' or tag=='i' or tag=='u': self.set_style(tag, True) if tag=='center': self.align = 'Center' def handle_endtag(self, tag): #Closing tag if DEBUG: print "ENDTAG", tag if tag=='h1' or tag=='h2' or tag=='h3' or tag=='h4': self.pdf.ln(6) self.set_font() self.set_style() self.align = None if tag=='pre': self.pdf.set_font(self.font or 'Times','',12) self.pdf.set_font_size(12) self.pre=False if tag=='blockquote': self.set_text_color(0,0,0) self.pdf.ln(3) if tag=='strong': tag='b' if tag=='em': tag='i' if tag=='b' or tag=='i' or tag=='u': self.set_style(tag, False) if tag=='a': self.href='' if tag=='p': self.align='' if tag in ('ul', 'ol'): self.indent-=1 self.bullet.pop() if tag=='table': if not self.tfooter_out: self.output_table_footer() self.table = None self.th = False self.theader = None self.tfooter = None self.pdf.ln() if tag=='thead': self.thead = None if tag=='tfoot': self.tfoot = None if tag=='tbody': # draw a line separator between table bodies self.pdf.set_x(self.table_offset) self.output_table_sep() if tag=='tr': h = self.table_h if self.tfoot is None: self.pdf.ln(h) self.tr = None if tag=='td' or tag=='th': if self.th: if DEBUG: print "revert style" self.set_style('B', False) # revert style self.table_col_index += int(self.td.get('colspan','1')) self.td = None self.th = False if tag=='font': if self.color: self.pdf.set_text_color(0,0,0) self.color = None if self.font: self.SetFont('Times','',12) self.font = None if tag=='center': self.align = None def set_font(self, face=None, size=None): if face: self.font_face = face if size: self.font_size = size self.h = size / 72.0*25.4 if DEBUG: print "H", self.h self.pdf.set_font(self.font_face or 'times','',12) self.pdf.set_font_size(self.font_size or 12) self.set_style('u', False) self.set_style('b', False) self.set_style('i', False) self.set_text_color() def set_style(self, tag=None, enable=None): #Modify style and select corresponding font if tag: t = self.style.get(tag.lower()) self.style[tag.lower()] = enable style='' for s in ('b','i','u'): if self.style.get(s): style+=s if DEBUG: print "SET_FONT_STYLE", style self.pdf.set_font('',style) def set_text_color(self, r=None, g=0, b=0): if r is None: self.pdf.set_text_color(self.r,self.g,self.b) else: self.pdf.set_text_color(r, g, b) self.r = r self.g = g self.b = b def put_link(self, url, txt): #Put a hyperlink self.set_text_color(0,0,255) self.set_style('u', True) self.pdf.write(5,txt,url) self.set_style('u', False) self.set_text_color(0) def put_line(self): self.pdf.ln(2) self.pdf.line(self.pdf.get_x(),self.pdf.get_y(),self.pdf.get_x()+187,self.pdf.get_y()) self.pdf.ln(3) class HTMLMixin(): def write_html(self, text, image_map=lambda x:x): "Parse HTML and convert it to PDF" h2p = HTML2FPDF(self,image_map=image_map) h2p.feed(text) if __name__=='__main__': html=""" <H1 align="center">html2fpdf</H1> <h2>Basic usage</h2> <p>You can now easily print text mixing different styles : <B>bold</B>, <I>italic</I>, <U>underlined</U>, or <B><I><U>all at once</U></I></B>!<BR>You can also insert links on text, such as <A HREF="http://www.fpdf.org">www.fpdf.org</A>, or on an image: click on the logo.<br> <center> <A HREF="http://www.fpdf.org"><img src="tutorial/logo.png" width="104" height="71"></A> </center> <h3>Sample List</h3> <ul><li>option 1</li> <ol><li>option 2</li></ol> <li>option 3</li></ul> <table border="0" align="center" width="50%"> <thead><tr><th width="30%">Header 1</th><th width="70%">header 2</th></tr></thead> <tbody> <tr><td>cell 1</td><td>cell 2</td></tr> <tr><td>cell 2</td><td>cell 3</td></tr> </tbody> </table> <table border="1"> <thead><tr bgcolor="#A0A0A0"><th width="30%">Header 1</th><th width="70%">header 2</th></tr></thead> <tfoot><tr bgcolor="#E0E0E0"><td>footer 1</td><td>footer 2</td></tr></tfoot> <tbody> <tr><td>cell 1</td><td>cell 2</td></tr> <tr> <td width="30%">cell 1</td><td width="70%" bgcolor="#D0D0FF" align='right'>cell 2</td> </tr> </tbody> <tbody><tr><td colspan="2">cell spanned</td></tr></tbody> <tbody> """ + """<tr bgcolor="#F0F0F0"> <td>cell 3</td><td>cell 4</td> </tr><tr bgcolor="#FFFFFF"> <td>cell 5</td><td>cell 6</td> </tr>""" * 200 + """ </tbody> </table> """ class MyFPDF(FPDF, HTMLMixin): def header(self): self.image('tutorial/logo_pb.png',10,8,33) self.set_font('Arial','B',15) self.cell(80) self.cell(30,10,'Title',1,0,'C') self.ln(20) def footer(self): self.set_y(-15) self.set_font('Arial','I',8) txt = 'Page %s of %s' % (self.page_no(), self.alias_nb_pages()) self.cell(0,10,txt,0,0,'C') pdf=MyFPDF() #First page pdf.add_page() pdf.write_html(html) pdf.output('html.pdf','F') import os os.system("evince html.pdf")
Python
from fpdf import FPDF from html import HTMLMixin from template import Template
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Creates a taskbar icon for web2py # # Author: Mark Larsen, mostly stolen from Mark Hammond's # # C:\Python25\Lib\site-packages\win32\Demos\win32gui_taskbar.py # # 11/7/08 # dual licensed under the web2py license (LGPL) and the Python license. import os import sys import base64 import win32con import win32api import win32gui class TaskBarIcon: def __init__(self, iconPath=None): self.iconPath = iconPath self.status = [] msg_TaskbarRestart = \ win32api.RegisterWindowMessage('TaskbarCreated') message_map = { msg_TaskbarRestart: self.OnRestart, win32con.WM_DESTROY: self.OnDestroy, win32con.WM_COMMAND: self.OnCommand, win32con.WM_USER + 20: self.OnTaskbarNotify, } # Register the Window class. wc = win32gui.WNDCLASS() hinst = wc.hInstance = win32api.GetModuleHandle(None) wc.lpszClassName = 'web2pyTaskbar' wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW wc.hCursor = win32gui.LoadCursor(0, win32con.IDC_ARROW) wc.hbrBackground = win32con.COLOR_WINDOW wc.lpfnWndProc = message_map # could also specify a wndproc. classAtom = win32gui.RegisterClass(wc) # Create the Window. style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU self.hwnd = win32gui.CreateWindow( classAtom, 'web2pyTaskbar', style, 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, 0, 0, hinst, None, ) win32gui.UpdateWindow(self.hwnd) self.SetServerStopped() def __createIcon(self): # try and use custom icon if self.iconPath and os.path.isfile(self.iconPath): hicon = self.__loadFromFile(self.iconPath) else: try: fp = 'tmp.ico' icFH = file(fp, 'wb') if self.serverState == self.EnumServerState.STOPPED: icFH.write(base64.b64decode(self.__getIconStopped())) elif self.serverState == self.EnumServerState.RUNNING: icFH.write(base64.b64decode(self.__getIconRunning())) icFH.close() hicon = self.__loadFromFile(fp) os.unlink(fp) except: print "Can't load web2py icons - using default" hicon = win32gui.LoadIcon(0, win32con.IDI_APPLICATION) flags = win32gui.NIF_ICON | win32gui.NIF_MESSAGE\ | win32gui.NIF_TIP nid = ( self.hwnd, 0, flags, win32con.WM_USER + 20, hicon, 'web2py Framework', ) try: win32gui.Shell_NotifyIcon(win32gui.NIM_MODIFY, nid) except: try: win32gui.Shell_NotifyIcon(win32gui.NIM_ADD, nid) except win32api.error: # This is common when windows is starting, and this code is hit # before the taskbar has been created. print 'Failed to add the taskbar icon - is explorer running?' # but keep running anyway - when explorer starts, we get the def OnRestart( self, hwnd, msg, wparam, lparam, ): self._DoCreateIcons() def OnDestroy( self, hwnd, msg, wparam, lparam, ): nid = (self.hwnd, 0) win32gui.Shell_NotifyIcon(win32gui.NIM_DELETE, nid) def OnTaskbarNotify( self, hwnd, msg, wparam, lparam, ): if lparam == win32con.WM_LBUTTONUP: pass elif lparam == win32con.WM_LBUTTONDBLCLK: pass elif lparam == win32con.WM_RBUTTONUP: menu = win32gui.CreatePopupMenu() win32gui.AppendMenu(menu, win32con.MF_STRING, 1023, 'Toggle Display') win32gui.AppendMenu(menu, win32con.MF_SEPARATOR, 0, '') if self.serverState == self.EnumServerState.STOPPED: win32gui.AppendMenu(menu, win32con.MF_STRING, 1024, 'Start Server') win32gui.AppendMenu(menu, win32con.MF_STRING | win32con.MF_GRAYED, 1025, 'Restart Server') win32gui.AppendMenu(menu, win32con.MF_STRING | win32con.MF_GRAYED, 1026, 'Stop Server') else: win32gui.AppendMenu(menu, win32con.MF_STRING | win32con.MF_GRAYED, 1024, 'Start Server') win32gui.AppendMenu(menu, win32con.MF_STRING, 1025, 'Restart Server') win32gui.AppendMenu(menu, win32con.MF_STRING, 1026, 'Stop Server') win32gui.AppendMenu(menu, win32con.MF_SEPARATOR, 0, '') win32gui.AppendMenu(menu, win32con.MF_STRING, 1027, 'Quit (pid:%i)' % os.getpid()) pos = win32gui.GetCursorPos() # See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/menus_0hdi.asp win32gui.SetForegroundWindow(self.hwnd) win32gui.TrackPopupMenu( menu, win32con.TPM_LEFTALIGN, pos[0], pos[1], 0, self.hwnd, None, ) win32api.PostMessage(self.hwnd, win32con.WM_NULL, 0, 0) return 1 def OnCommand( self, hwnd, msg, wparam, lparam, ): id = win32api.LOWORD(wparam) if id == 1023: self.status.append(self.EnumStatus.TOGGLE) elif id == 1024: self.status.append(self.EnumStatus.START) elif id == 1025: self.status.append(self.EnumStatus.RESTART) elif id == 1026: self.status.append(self.EnumStatus.STOP) elif id == 1027: self.status.append(self.EnumStatus.QUIT) self.Destroy() else: print 'Unknown command -', id def Destroy(self): win32gui.DestroyWindow(self.hwnd) def SetServerRunning(self): self.serverState = self.EnumServerState.RUNNING self.__createIcon() def SetServerStopped(self): self.serverState = self.EnumServerState.STOPPED self.__createIcon() def __getIconRunning(self): return 'AAABAAEAEBAQAAAAAAAoAQAAFgAAACgAAAAQAAAAIAAAAAEABAAAAAAAgAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAIXMGAABe/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABERAgAAIAAAEAACAAAgAAABEAIiACIgAAABAgAgIAIAEAECACAgAgABEAIiACACAAAAAAAAAAAAICACIiAiIAICAgIAACACAgICAgAAIAICAgICIiAiIAICAgIAACACAgICAgAAIAICAgICIiAiIAAAAAAAAAAAD//wAAhe8AAL3vAADMYwAA9a0AALWtAADMbQAA//8AAKwjAABV7QAAVe0AAFQjAABV7QAAVe0AAFQjAAD//wAA' def __getIconStopped(self): return 'AAABAAEAEBAQAAEABAAoAQAAFgAAACgAAAAQAAAAIAAAAAEABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJCdIAIXMGAABe/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAzMzMzMzMzAwERMjMzIzAzEDMyMzMjAzMxAzIiMyAjMzMwMjMjAzIzEzECMyAjMjMxEzAiAyMyMzMzMwAzMzMzIyMyACMiIzIyMjAzAyMyMjIyAjMwIzIyMjAyIiMCIzIyAjIzMyAyMjAyMjMzIwIyAjIyIiMiIDAzMzMzMzMzB//gAAhe0AAJ3rAADMYwAA9a0AALGNAADMLQAA/n8AAKwjAABVrQAAUc0AAFQjAABF5QAAVekAABQhAAB//gAA' def __loadFromFile(self, iconPath): hinst = win32api.GetModuleHandle(None) icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE hicon = win32gui.LoadImage( hinst, iconPath, win32con.IMAGE_ICON, 0, 0, icon_flags, ) return hicon class EnumStatus: TOGGLE = 0 START = 1 STOP = 2 RESTART = 3 QUIT = 4 class EnumServerState: RUNNING = 0 STOPPED = 1
Python
""" AIM class to credit card payment with authorize.net Fork of authnet code written by John Conde http://www.johnconde.net/blog/integrate-the-authorizenet-aim-api-with-python-3-2/ Unkown license, assuming public domain Modifed by Massimo Di Pierro - ported from Python 3.x run on Python 2.4+ - fixed a couple of bugs - merged with test so single file - namedtuple from http://code.activestate.com/recipes/500261/ """ __all__ = ['AIM'] from operator import itemgetter import urllib _known_tuple_types = {} class NamedTupleBase(tuple): """Base class for named tuples with the __new__ operator set, named tuples yielded by the namedtuple() function will subclass this and add properties.""" def __new__(cls, *args, **kws): """Create a new instance of this fielded tuple""" # May need to unpack named field values here if kws: values = list(args) + [None]*(len(cls._fields) - len(args)) fields = dict((val, idx) for idx, val in enumerate(cls._fields)) for kw, val in kws.iteritems(): assert kw in kws, "%r not in field list" % kw values[fields[kw]] = val args = tuple(values) return tuple.__new__(cls, args) def namedtuple(typename, fieldnames): """ >>> import namedtuples >>> tpl = namedtuples.namedtuple(['a', 'b', 'c']) >>> tpl(1, 2, 3) (1, 2, 3) >>> tpl(1, 2, 3).b 2 >>> tpl(c=1, a=2, b=3) (2, 3, 1) >>> tpl(c=1, a=2, b=3).b 3 >>> tpl(c='pads with nones') (None, None, 'pads with nones') >>> tpl(b='pads with nones') (None, 'pads with nones', None) >>> """ # Split up a string, some people do this if isinstance(fieldnames, basestring): fieldnames = fieldnames.replace(',', ' ').split() # Convert anything iterable that enumerates fields to a tuple now fieldname_tuple = tuple(str(field) for field in fieldnames) # See if we've cached this if fieldname_tuple in _known_tuple_types: return _known_tuple_types[fieldname_tuple] # Make the type new_tuple_type = type(typename, (NamedTupleBase,), {}) # Set the hidden field new_tuple_type._fields = fieldname_tuple # Add the getters for i, field in enumerate(fieldname_tuple): setattr(new_tuple_type, field, property(itemgetter(i))) # Cache _known_tuple_types[fieldname_tuple] = new_tuple_type # Done return new_tuple_type class AIM: class AIMError(Exception): def __init__(self, value): self.parameter = value def __str__(self): return str(self.parameter) def __init__(self, login, transkey, testmode=False): if str(login).strip() == '' or login == None: raise AIM.AIMError('No login name provided') if str(transkey).strip() == '' or transkey == None: raise AIM.AIMError('No transaction key provided') if testmode != True and testmode != False: raise AIM.AIMError('Invalid value for testmode. Must be True or False. "{0}" given.'.format(testmode)) self.testmode = testmode self.proxy = None; self.delimiter = '|' self.results = [] self.error = True self.success = False self.declined = False self.parameters = {} self.setParameter('x_delim_data', 'true') self.setParameter('x_delim_char', self.delimiter) self.setParameter('x_relay_response', 'FALSE') self.setParameter('x_url', 'FALSE') self.setParameter('x_version', '3.1') self.setParameter('x_method', 'CC') self.setParameter('x_type', 'AUTH_CAPTURE') self.setParameter('x_login', login) self.setParameter('x_tran_key', transkey) def process(self): encoded_args = urllib.urlencode(self.parameters) if self.testmode == True: url = 'https://test.authorize.net/gateway/transact.dll' else: url = 'https://secure.authorize.net/gateway/transact.dll' if self.proxy == None: self.results += str(urllib.urlopen(url, encoded_args).read()).split(self.delimiter) else: opener = urllib.FancyURLopener(self.proxy) opened = opener.open(url, encoded_args) try: self.results += str(opened.read()).split(self.delimiter) finally: opened.close() Results = namedtuple('Results', 'ResultResponse ResponseSubcode ResponseCode ResponseText AuthCode \ AVSResponse TransactionID InvoiceNumber Description Amount PaymentMethod \ TransactionType CustomerID CHFirstName CHLastName Company BillingAddress \ BillingCity BillingState BillingZip BillingCountry Phone Fax Email ShippingFirstName \ ShippingLastName ShippingCompany ShippingAddress ShippingCity ShippingState \ ShippingZip ShippingCountry TaxAmount DutyAmount FreightAmount TaxExemptFlag \ PONumber MD5Hash CVVResponse CAVVResponse') self.response = Results(*tuple(r for r in self.results)[0:40]) if self.getResultResponseFull() == 'Approved': self.error = False self.success = True self.declined = False elif self.getResultResponseFull() == 'Declined': self.error = False self.success = False self.declined = True else: raise AIM.AIMError(self.response.ResponseText) def setTransaction(self, creditcard, expiration, total, cvv=None, tax=None, invoice=None): if str(creditcard).strip() == '' or creditcard == None: raise AIM.AIMError('No credit card number passed to setTransaction(): {0}'.format(creditcard)) if str(expiration).strip() == '' or expiration == None: raise AIM.AIMError('No expiration number to setTransaction(): {0}'.format(expiration)) if str(total).strip() == '' or total == None: raise AIM.AIMError('No total amount passed to setTransaction(): {0}'.format(total)) self.setParameter('x_card_num', creditcard) self.setParameter('x_exp_date', expiration) self.setParameter('x_amount', total) if cvv != None: self.setParameter('x_card_code', cvv) if tax != None: self.setParameter('x_tax', tax) if invoice != None: self.setParameter('x_invoice_num', invoice) def setTransactionType(self, transtype=None): types = ['AUTH_CAPTURE', 'AUTH_ONLY', 'PRIOR_AUTH_CAPTURE', 'CREDIT', 'CAPTURE_ONLY', 'VOID'] if transtype.upper() not in types: raise AIM.AIMError('Incorrect Transaction Type passed to setTransactionType(): {0}'.format(transtype)) self.setParameter('x_type', transtype.upper()) def setProxy(self, proxy=None): if str(proxy).strip() == '' or proxy == None: raise AIM.AIMError('No proxy passed to setProxy()') self.proxy = {'http': str(proxy).strip()} def setParameter(self, key=None, value=None): if key != None and value != None and str(key).strip() != '' and str(value).strip() != '': self.parameters[key] = str(value).strip() else: raise AIM.AIMError('Incorrect parameters passed to setParameter(): {0}:{1}'.format(key, value)) def isApproved(self): return self.success def isDeclined(self): return self.declined def isError(self): return self.error def getResultResponseFull(self): responses = ['', 'Approved', 'Declined', 'Error'] return responses[int(self.results[0])] def process(creditcard,expiration,total,cvv=None,tax=None,invoice=None, login='cnpdev4289', transkey='SR2P8g4jdEn7vFLQ',testmode=True): payment = AIM(login,transkey,testmode) expiration = expiration.replace('/','') payment.setTransaction(creditcard, expiration, total, cvv, tax, invoice) try: payment.process() return payment.isApproved() except AIM.AIMError: return False def test(): import socket import sys from time import time creditcard = '4427802641004797' expiration = '122012' total = '1.00' cvv = '123' tax = '0.00' invoice = str(time())[4:10] # get a random invoice number try: payment = AIM('cnpdev4289', 'SR2P8g4jdEn7vFLQ', True) payment.setTransaction(creditcard, expiration, total, cvv, tax, invoice) payment.setParameter('x_duplicate_window', 180) # three minutes duplicate windows payment.setParameter('x_cust_id', '1324') # customer ID payment.setParameter('x_first_name', 'John') payment.setParameter('x_last_name', 'Conde') payment.setParameter('x_company', 'Test Company') payment.setParameter('x_address', '1234 Main Street') payment.setParameter('x_city', 'Townsville') payment.setParameter('x_state', 'NJ') payment.setParameter('x_zip', '12345') payment.setParameter('x_country', 'US') payment.setParameter('x_phone', '800-555-1234') payment.setParameter('x_description', 'Test Transaction') payment.setParameter('x_customer_ip', socket.gethostbyname(socket.gethostname())) payment.setParameter('x_email', 'john@example.com') payment.setParameter('x_email_customer', False) payment.process() if payment.isApproved(): print 'Response Code: ', payment.response.ResponseCode print 'Response Text: ', payment.response.ResponseText print 'Response: ', payment.getResultResponseFull() print 'Transaction ID: ', payment.response.TransactionID print 'CVV Result: ', payment.response.CVVResponse print 'Approval Code: ', payment.response.AuthCode print 'AVS Result: ', payment.response.AVSResponse elif payment.isDeclined(): print 'Your credit card was declined by your bank' elif payment.isError(): raise AIM.AIMError('An uncaught error occurred') except AIM.AIMError, e: print "Exception thrown:", e print 'An error occured' print 'approved',payment.isApproved() print 'declined',payment.isDeclined() print 'error',payment.isError() if __name__=='__main__': test()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """PyRSS2Gen - A Python library for generating RSS 2.0 feeds.""" __name__ = 'PyRSS2Gen' __version__ = (1, 0, 0) __author__ = 'Andrew Dalke <dalke@dalkescientific.com>' _generator_name = __name__ + '-' + '.'.join(map(str, __version__)) import datetime import cStringIO # Could make this the base class; will need to add 'publish' class WriteXmlMixin: def write_xml(self, outfile, encoding='iso-8859-1'): from xml.sax import saxutils handler = saxutils.XMLGenerator(outfile, encoding) handler.startDocument() self.publish(handler) handler.endDocument() def to_xml(self, encoding='iso-8859-1'): try: import cStringIO as StringIO except ImportError: import StringIO f = StringIO.StringIO() self.write_xml(f, encoding) return f.getvalue() def _element( handler, name, obj, d={}, ): if isinstance(obj, basestring) or obj is None: # special-case handling to make the API easier # to use for the common case. handler.startElement(name, d) if obj is not None: handler.characters(obj) handler.endElement(name) else: # It better know how to emit the correct XML. obj.publish(handler) def _opt_element(handler, name, obj): if obj is None: return _element(handler, name, obj) def _format_date(dt): """convert a datetime into an RFC 822 formatted date Input date must be in GMT. """ # Looks like: # Sat, 07 Sep 2002 00:00:01 GMT # Can't use strftime because that's locale dependent # # Isn't there a standard way to do this for Python? The # rfc822 and email.Utils modules assume a timestamp. The # following is based on the rfc822 module. return '%s, %02d %s %04d %02d:%02d:%02d GMT' % ( [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun', ][dt.weekday()], dt.day, [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', ][dt.month - 1], dt.year, dt.hour, dt.minute, dt.second, ) ## # A couple simple wrapper objects for the fields which # take a simple value other than a string. class IntElement: """implements the 'publish' API for integers Takes the tag name and the integer value to publish. (Could be used for anything which uses str() to be published to text for XML.) """ element_attrs = {} def __init__(self, name, val): self.name = name self.val = val def publish(self, handler): handler.startElement(self.name, self.element_attrs) handler.characters(str(self.val)) handler.endElement(self.name) class DateElement: """implements the 'publish' API for a datetime.datetime Takes the tag name and the datetime to publish. Converts the datetime to RFC 2822 timestamp (4-digit year). """ def __init__(self, name, dt): self.name = name self.dt = dt def publish(self, handler): _element(handler, self.name, _format_date(self.dt)) # ### class Category: """Publish a category element""" def __init__(self, category, domain=None): self.category = category self.domain = domain def publish(self, handler): d = {} if self.domain is not None: d['domain'] = self.domain _element(handler, 'category', self.category, d) class Cloud: """Publish a cloud""" def __init__( self, domain, port, path, registerProcedure, protocol, ): self.domain = domain self.port = port self.path = path self.registerProcedure = registerProcedure self.protocol = protocol def publish(self, handler): _element(handler, 'cloud', None, { 'domain': self.domain, 'port': str(self.port), 'path': self.path, 'registerProcedure': self.registerProcedure, 'protocol': self.protocol, }) class Image: """Publish a channel Image""" element_attrs = {} def __init__( self, url, title, link, width=None, height=None, description=None, ): self.url = url self.title = title self.link = link self.width = width self.height = height self.description = description def publish(self, handler): handler.startElement('image', self.element_attrs) _element(handler, 'url', self.url) _element(handler, 'title', self.title) _element(handler, 'link', self.link) width = self.width if isinstance(width, int): width = IntElement('width', width) _opt_element(handler, 'width', width) height = self.height if isinstance(height, int): height = IntElement('height', height) _opt_element(handler, 'height', height) _opt_element(handler, 'description', self.description) handler.endElement('image') class Guid: """Publish a guid Defaults to being a permalink, which is the assumption if it's omitted. Hence strings are always permalinks. """ def __init__(self, guid, isPermaLink=1): self.guid = guid self.isPermaLink = isPermaLink def publish(self, handler): d = {} if self.isPermaLink: d['isPermaLink'] = 'true' else: d['isPermaLink'] = 'false' _element(handler, 'guid', self.guid, d) class TextInput: """Publish a textInput Apparently this is rarely used. """ element_attrs = {} def __init__( self, title, description, name, link, ): self.title = title self.description = description self.name = name self.link = link def publish(self, handler): handler.startElement('textInput', self.element_attrs) _element(handler, 'title', self.title) _element(handler, 'description', self.description) _element(handler, 'name', self.name) _element(handler, 'link', self.link) handler.endElement('textInput') class Enclosure: """Publish an enclosure""" def __init__( self, url, length, type, ): self.url = url self.length = length self.type = type def publish(self, handler): _element(handler, 'enclosure', None, {'url': self.url, 'length': str(self.length), 'type': self.type}) class Source: """Publish the item's original source, used by aggregators""" def __init__(self, name, url): self.name = name self.url = url def publish(self, handler): _element(handler, 'source', self.name, {'url': self.url}) class SkipHours: """Publish the skipHours This takes a list of hours, as integers. """ element_attrs = {} def __init__(self, hours): self.hours = hours def publish(self, handler): if self.hours: handler.startElement('skipHours', self.element_attrs) for hour in self.hours: _element(handler, 'hour', str(hour)) handler.endElement('skipHours') class SkipDays: """Publish the skipDays This takes a list of days as strings. """ element_attrs = {} def __init__(self, days): self.days = days def publish(self, handler): if self.days: handler.startElement('skipDays', self.element_attrs) for day in self.days: _element(handler, 'day', day) handler.endElement('skipDays') class RSS2(WriteXmlMixin): """The main RSS class. Stores the channel attributes, with the \"category\" elements under \".categories\" and the RSS items under \".items\". """ rss_attrs = {'version': '2.0'} element_attrs = {} def __init__( self, title, link, description, language=None, copyright=None, managingEditor=None, webMaster=None, pubDate=None, lastBuildDate=None, categories=None, generator=_generator_name, docs='http://blogs.law.harvard.edu/tech/rss', cloud=None, ttl=None, image=None, rating=None, textInput=None, skipHours=None, skipDays=None, items=None, ): self.title = title self.link = link self.description = description self.language = language self.copyright = copyright self.managingEditor = managingEditor self.webMaster = webMaster self.pubDate = pubDate self.lastBuildDate = lastBuildDate if categories is None: categories = [] self.categories = categories self.generator = generator self.docs = docs self.cloud = cloud self.ttl = ttl self.image = image self.rating = rating self.textInput = textInput self.skipHours = skipHours self.skipDays = skipDays if items is None: items = [] self.items = items def publish(self, handler): handler.startElement('rss', self.rss_attrs) handler.startElement('channel', self.element_attrs) _element(handler, 'title', self.title) _element(handler, 'link', self.link) _element(handler, 'description', self.description) self.publish_extensions(handler) _opt_element(handler, 'language', self.language) _opt_element(handler, 'copyright', self.copyright) _opt_element(handler, 'managingEditor', self.managingEditor) _opt_element(handler, 'webMaster', self.webMaster) pubDate = self.pubDate if isinstance(pubDate, datetime.datetime): pubDate = DateElement('pubDate', pubDate) _opt_element(handler, 'pubDate', pubDate) lastBuildDate = self.lastBuildDate if isinstance(lastBuildDate, datetime.datetime): lastBuildDate = DateElement('lastBuildDate', lastBuildDate) _opt_element(handler, 'lastBuildDate', lastBuildDate) for category in self.categories: if isinstance(category, basestring): category = Category(category) category.publish(handler) _opt_element(handler, 'generator', self.generator) _opt_element(handler, 'docs', self.docs) if self.cloud is not None: self.cloud.publish(handler) ttl = self.ttl if isinstance(self.ttl, int): ttl = IntElement('ttl', ttl) _opt_element(handler, 'tt', ttl) if self.image is not None: self.image.publish(handler) _opt_element(handler, 'rating', self.rating) if self.textInput is not None: self.textInput.publish(handler) if self.skipHours is not None: self.skipHours.publish(handler) if self.skipDays is not None: self.skipDays.publish(handler) for item in self.items: item.publish(handler) handler.endElement('channel') handler.endElement('rss') def publish_extensions(self, handler): # Derived classes can hook into this to insert # output after the three required fields. pass class RSSItem(WriteXmlMixin): """Publish an RSS Item""" element_attrs = {} def __init__( self, title=None, link=None, description=None, author=None, categories=None, comments=None, enclosure=None, guid=None, pubDate=None, source=None, ): if title is None and description is None: raise TypeError( "RSSItem must define at least one of 'title' or 'description'") self.title = title self.link = link self.description = description self.author = author if categories is None: categories = [] self.categories = categories self.comments = comments self.enclosure = enclosure self.guid = guid self.pubDate = pubDate self.source = source # It sure does get tedious typing these names three times... def publish(self, handler): handler.startElement('item', self.element_attrs) _opt_element(handler, 'title', self.title) _opt_element(handler, 'link', self.link) self.publish_extensions(handler) _opt_element(handler, 'description', self.description) _opt_element(handler, 'author', self.author) for category in self.categories: if isinstance(category, basestring): category = Category(category) category.publish(handler) _opt_element(handler, 'comments', self.comments) if self.enclosure is not None: self.enclosure.publish(handler) _opt_element(handler, 'guid', self.guid) pubDate = self.pubDate if isinstance(pubDate, datetime.datetime): pubDate = DateElement('pubDate', pubDate) _opt_element(handler, 'pubDate', pubDate) if self.source is not None: self.source.publish(handler) handler.endElement('item') def publish_extensions(self, handler): # Derived classes can hook into this to insert # output after the title and link elements pass def dumps(rss, encoding='utf-8'): s = cStringIO.StringIO() rss.write_xml(s, encoding) return s.getvalue() def test(): rss = RSS2(title='web2py feed', link='http://www.web2py.com', description='About web2py', lastBuildDate=datetime.datetime.now(), items=[RSSItem(title='web2py and PyRSS2Gen-0.0', link='http://www.web2py.com/examples/simple_examples/getrss', description='web2py can now make rss feeds!', guid=Guid('http://www.web2py.com/'), pubDate=datetime.datetime(2007, 11, 14, 10, 30))]) return dumps(rss) if __name__ == '__main__': print test()
Python
#!/usr/bin/python # -*- coding: latin-1 -*- # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation; either version 3, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License # for more details. "Simple SOAP Server implementation" __author__ = "Mariano Reingart (reingart@gmail.com)" __copyright__ = "Copyright (C) 2010 Mariano Reingart" __license__ = "LGPL 3.0" __version__ = "1.02c" from simplexml import SimpleXMLElement, TYPE_MAP, DateTime, Date, Decimal DEBUG = False class SoapDispatcher(object): "Simple Dispatcher for SOAP Server" def __init__(self, name, documentation='', action='', location='', namespace=None, prefix=False, soap_uri="http://schemas.xmlsoap.org/soap/envelope/", soap_ns='soap', **kwargs): self.methods = {} self.name = name self.documentation = documentation self.action = action # base SoapAction self.location = location self.namespace = namespace # targetNamespace self.prefix = prefix self.soap_ns = soap_ns self.soap_uri = soap_uri def register_function(self, name, fn, returns=None, args=None, doc=None): self.methods[name] = fn, returns, args, doc or getattr(fn,"__doc__","") def dispatch(self, xml, action=None): "Receive and proccess SOAP call" # default values: prefix = self.prefix ret = fault = None soap_ns, soap_uri = self.soap_ns, self.soap_uri soap_fault_code = 'VersionMismatch' try: request = SimpleXMLElement(xml, namespace=self.namespace) # detect soap prefix and uri (xmlns attributes of Envelope) for k, v in request[:]: if v in ("http://schemas.xmlsoap.org/soap/envelope/", "http://www.w3.org/2003/05/soap-env",): soap_ns = request.attributes()[k].localName soap_uri = request.attributes()[k].value soap_fault_code = 'Client' # parse request message and get local method method = request('Body', ns=soap_uri).children()(0) if action: # method name = action name = action[len(self.action)+1:-1] prefix = self.prefix if not action or not name: # method name = input message name name = method.get_local_name() prefix = method.get_prefix() if DEBUG: print "dispatch method", name function, returns_types, args_types, doc = self.methods[name] # de-serialize parameters (if type definitions given) if args_types: args = method.children().unmarshall(args_types) elif args_types is None: args = {'request':method} # send raw request else: args = {} # no parameters soap_fault_code = 'Server' # execute function ret = function(**args) if DEBUG: print ret except Exception, e: import sys etype, evalue, etb = sys.exc_info() if DEBUG: import traceback detail = ''.join(traceback.format_exception(etype, evalue, etb)) detail += '\n\nXML REQUEST\n\n' + xml else: detail = None fault = {'faultcode': "%s.%s" % (soap_fault_code, etype.__name__), 'faultstring': unicode(evalue), 'detail': detail} # build response message if not prefix: xml = """<%(soap_ns)s:Envelope xmlns:%(soap_ns)s="%(soap_uri)s"/>""" else: xml = """<%(soap_ns)s:Envelope xmlns:%(soap_ns)s="%(soap_uri)s" xmlns:%(prefix)s="%(namespace)s"/>""" xml = xml % {'namespace': self.namespace, 'prefix': prefix, 'soap_ns': soap_ns, 'soap_uri': soap_uri} response = SimpleXMLElement(xml, namespace=self.namespace, prefix=prefix) response['xmlns:xsi'] = "http://www.w3.org/2001/XMLSchema-instance" response['xmlns:xsd'] = "http://www.w3.org/2001/XMLSchema" body = response.add_child("%s:Body" % soap_ns, ns=False) if fault: # generate a Soap Fault (with the python exception) body.marshall("%s:Fault" % soap_ns, fault, ns=False) else: # return normal value res = body.add_child("%sResponse" % name, ns=prefix) if not prefix: res['xmlns'] = self.namespace # add target namespace # serialize returned values (response) if type definition available if returns_types: if not isinstance(ret, dict): res.marshall(returns_types.keys()[0], ret, ) else: for k,v in ret.items(): res.marshall(k, v) elif returns_types is None: # merge xmlelement returned res.import_node(ret) return response.as_xml() # Introspection functions: def list_methods(self): "Return a list of aregistered operations" return [(method, doc) for method, (function, returns, args, doc) in self.methods.items()] def help(self, method=None): "Generate sample request and response messages" (function, returns, args, doc) = self.methods[method] xml = """ <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body><%(method)s xmlns="%(namespace)s"/></soap:Body> </soap:Envelope>""" % {'method':method, 'namespace':self.namespace} request = SimpleXMLElement(xml, namespace=self.namespace, prefix=self.prefix) if args: items = args.items() elif args is None: items = [('value', None)] else: items = [] for k,v in items: request(method).marshall(k, v, add_comments=True, ns=False) xml = """ <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body><%(method)sResponse xmlns="%(namespace)s"/></soap:Body> </soap:Envelope>""" % {'method':method, 'namespace':self.namespace} response = SimpleXMLElement(xml, namespace=self.namespace, prefix=self.prefix) if returns: items = returns.items() elif args is None: items = [('value', None)] else: items = [] for k,v in items: response('%sResponse'%method).marshall(k, v, add_comments=True, ns=False) return request.as_xml(pretty=True), response.as_xml(pretty=True), doc def wsdl(self): "Generate Web Service Description v1.1" xml = """<?xml version="1.0"?> <wsdl:definitions name="%(name)s" targetNamespace="%(namespace)s" xmlns:tns="%(namespace)s" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <wsdl:documentation xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">%(documentation)s</wsdl:documentation> <wsdl:types> <xsd:schema targetNamespace="%(namespace)s" elementFormDefault="qualified" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> </xsd:schema> </wsdl:types> </wsdl:definitions> """ % {'namespace': self.namespace, 'name': self.name, 'documentation': self.documentation} wsdl = SimpleXMLElement(xml) for method, (function, returns, args, doc) in self.methods.items(): # create elements: def parse_element(name, values, array=False, complex=False): if not complex: element = wsdl('wsdl:types')('xsd:schema').add_child('xsd:element') complex = element.add_child("xsd:complexType") else: complex = wsdl('wsdl:types')('xsd:schema').add_child('xsd:complexType') element = complex element['name'] = name if values: items = values elif values is None: items = [('value', None)] else: items = [] if not array and items: all = complex.add_child("xsd:all") elif items: all = complex.add_child("xsd:sequence") for k,v in items: e = all.add_child("xsd:element") e['name'] = k if array: e[:]={'minOccurs': "0", 'maxOccurs': "unbounded"} if v in TYPE_MAP.keys(): t='xsd:%s' % TYPE_MAP[v] elif v is None: t='xsd:anyType' elif isinstance(v, list): n="ArrayOf%s%s" % (name, k) l = [] for d in v: l.extend(d.items()) parse_element(n, l, array=True, complex=True) t = "tns:%s" % n elif isinstance(v, dict): n="%s%s" % (name, k) parse_element(n, v.items(), complex=True) t = "tns:%s" % n e.add_attribute('type', t) parse_element("%s" % method, args and args.items()) parse_element("%sResponse" % method, returns and returns.items()) # create messages: for m,e in ('Input',''), ('Output','Response'): message = wsdl.add_child('wsdl:message') message['name'] = "%s%s" % (method, m) part = message.add_child("wsdl:part") part[:] = {'name': 'parameters', 'element': 'tns:%s%s' % (method,e)} # create ports portType = wsdl.add_child('wsdl:portType') portType['name'] = "%sPortType" % self.name for method, (function, returns, args, doc) in self.methods.items(): op = portType.add_child('wsdl:operation') op['name'] = method if doc: op.add_child("wsdl:documentation", doc) input = op.add_child("wsdl:input") input['message'] = "tns:%sInput" % method output = op.add_child("wsdl:output") output['message'] = "tns:%sOutput" % method # create bindings binding = wsdl.add_child('wsdl:binding') binding['name'] = "%sBinding" % self.name binding['type'] = "tns:%sPortType" % self.name soapbinding = binding.add_child('soap:binding') soapbinding['style'] = "document" soapbinding['transport'] = "http://schemas.xmlsoap.org/soap/http" for method in self.methods.keys(): op = binding.add_child('wsdl:operation') op['name'] = method soapop = op.add_child('soap:operation') soapop['soapAction'] = self.action + method soapop['style'] = 'document' input = op.add_child("wsdl:input") ##input.add_attribute('name', "%sInput" % method) soapbody = input.add_child("soap:body") soapbody["use"] = "literal" output = op.add_child("wsdl:output") ##output.add_attribute('name', "%sOutput" % method) soapbody = output.add_child("soap:body") soapbody["use"] = "literal" service = wsdl.add_child('wsdl:service') service["name"] = "%sService" % self.name service.add_child('wsdl:documentation', text=self.documentation) port=service.add_child('wsdl:port') port["name"] = "%s" % self.name port["binding"] = "tns:%sBinding" % self.name soapaddress = port.add_child('soap:address') soapaddress["location"] = self.location return wsdl.as_xml(pretty=True) from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer class SOAPHandler(BaseHTTPRequestHandler): def do_GET(self): "User viewable help information and wsdl" args = self.path[1:].split("?") print "serving", args if self.path != "/" and args[0] not in self.server.dispatcher.methods.keys(): self.send_error(404, "Method not found: %s" % args[0]) else: if self.path == "/": # return wsdl if no method supplied response = self.server.dispatcher.wsdl() else: # return supplied method help (?request or ?response messages) req, res, doc = self.server.dispatcher.help(args[0]) if len(args)==1 or args[1]=="request": response = req else: response = res self.send_response(200) self.send_header("Content-type", "text/xml") self.end_headers() self.wfile.write(response) def do_POST(self): "SOAP POST gateway" self.send_response(200) self.send_header("Content-type", "text/xml") self.end_headers() request = self.rfile.read(int(self.headers.getheader('content-length'))) response = self.server.dispatcher.dispatch(request) self.wfile.write(response) if __name__=="__main__": import sys dispatcher = SoapDispatcher( name = "PySimpleSoapSample", location = "http://localhost:8008/", action = 'http://localhost:8008/', # SOAPAction namespace = "http://example.com/pysimplesoapsamle/", prefix="ns0", documentation = 'Example soap service using PySimpleSoap', trace = True, ns = True) def adder(p,c, dt=None): "Add several values" print c[0]['d'],c[1]['d'], import datetime dt = dt + datetime.timedelta(365) return {'ab': p['a']+p['b'], 'dd': c[0]['d']+c[1]['d'], 'dt': dt} def dummy(in0): "Just return input" return in0 def echo(request): "Copy request->response (generic, any type)" return request.value dispatcher.register_function('Adder', adder, returns={'AddResult': {'ab': int, 'dd': str } }, args={'p': {'a': int,'b': int}, 'dt': Date, 'c': [{'d': Decimal}]}) dispatcher.register_function('Dummy', dummy, returns={'out0': str}, args={'in0': str}) dispatcher.register_function('Echo', echo) if '--local' in sys.argv: wsdl=dispatcher.wsdl() print wsdl testfile = open("C:/test.wsdl","w") try: testfile.write(wsdl) finally: testfile.close() # dummy local test (clasic soap dialect) xml = """<?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <Adder xmlns="http://example.com/sample.wsdl"> <p><a>1</a><b>2</b></p><c><d>5000000.1</d><d>.2</d></c><dt>20100724</dt> </Adder> </soap:Body> </soap:Envelope>""" print dispatcher.dispatch(xml) # dummy local test (modern soap dialect, SoapUI) xml = """ <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:pys="http://example.com/pysimplesoapsamle/"> <soapenv:Header/> <soapenv:Body> <pys:Adder> <pys:p><pys:a>9</pys:a><pys:b>3</pys:b></pys:p> <pys:dt>19690720<!--1969-07-20T21:28:00--></pys:dt> <pys:c><pys:d>10.001</pys:d><pys:d>5.02</pys:d></pys:c> </pys:Adder> </soapenv:Body> </soapenv:Envelope> """ print dispatcher.dispatch(xml) # echo local test (generic soap service) xml = """<?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <Echo xmlns="http://example.com/sample.wsdl"> <value xsi:type="xsd:string">Hello world</value> </Echo> </soap:Body> </soap:Envelope>""" print dispatcher.dispatch(xml) for method, doc in dispatcher.list_methods(): request, response, doc = dispatcher.help(method) ##print request ##print response if '--serve' in sys.argv: print "Starting server..." httpd = HTTPServer(("", 8008), SOAPHandler) httpd.dispatcher = dispatcher httpd.serve_forever() if '--consume' in sys.argv: from client import SoapClient client = SoapClient( location = "http://localhost:8008/", action = 'http://localhost:8008/', # SOAPAction namespace = "http://example.com/sample.wsdl", soap_ns='soap', trace = True, ns = False) response = client.Adder(p={'a':1,'b':2},dt='20100724',c=[{'d':'1.20'},{'d':'2.01'}]) result = response.AddResult print int(result.ab) print str(result.dd)
Python
#!/usr/bin/python # -*- coding: latin-1 -*- # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation; either version 3, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License # for more details. "Pythonic simple SOAP Client implementation" __author__ = "Mariano Reingart (reingart@gmail.com)" __copyright__ = "Copyright (C) 2008 Mariano Reingart" __license__ = "LGPL 3.0" __version__ = "1.02c" import urllib try: import httplib2 Http = httplib2.Http except ImportError: import urllib2 class Http(): # wrapper to use when httplib2 not available def request(self, url, method, body, headers): f = urllib2.urlopen(urllib2.Request(url, body, headers)) return f.info(), f.read() from simplexml import SimpleXMLElement, TYPE_MAP, OrderedDict class SoapFault(RuntimeError): def __init__(self,faultcode,faultstring): self.faultcode = faultcode self.faultstring = faultstring # soap protocol specification & namespace soap_namespaces = dict( soap11="http://schemas.xmlsoap.org/soap/envelope/", soap="http://schemas.xmlsoap.org/soap/envelope/", soapenv="http://schemas.xmlsoap.org/soap/envelope/", soap12="http://www.w3.org/2003/05/soap-env", ) class SoapClient(object): "Simple SOAP Client (s�mil PHP)" def __init__(self, location = None, action = None, namespace = None, cert = None, trace = False, exceptions = True, proxy = None, ns=False, soap_ns=None, wsdl = None, cache = False): self.certssl = cert self.keyssl = None self.location = location # server location (url) self.action = action # SOAP base action self.namespace = namespace # message self.trace = trace # show debug messages self.exceptions = exceptions # lanzar execpiones? (Soap Faults) self.xml_request = self.xml_response = '' if not soap_ns and not ns: self.__soap_ns = 'soap' # 1.1 elif not soap_ns and ns: self.__soap_ns = 'soapenv' # 1.2 else: self.__soap_ns = soap_ns # parse wsdl url self.services = wsdl and self.wsdl(wsdl, debug=trace, cache=cache) self.service_port = None # service port for late binding if not proxy: self.http = Http() else: import socks ##httplib2.debuglevel=4 self.http = httplib2.Http(proxy_info = httplib2.ProxyInfo( proxy_type=socks.PROXY_TYPE_HTTP, **proxy)) #if self.certssl: # esto funciona para validar al server? # self.http.add_certificate(self.keyssl, self.keyssl, self.certssl) self.__ns = ns # namespace prefix or False to not use it if not ns: self.__xml = """<?xml version="1.0" encoding="UTF-8"?> <%(soap_ns)s:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:%(soap_ns)s="%(soap_uri)s"> <%(soap_ns)s:Body> <%(method)s xmlns="%(namespace)s"> </%(method)s> </%(soap_ns)s:Body> </%(soap_ns)s:Envelope>""" else: self.__xml = """<?xml version="1.0" encoding="UTF-8"?> <%(soap_ns)s:Envelope xmlns:%(soap_ns)s="%(soap_uri)s" xmlns:%(ns)s="%(namespace)s"> <%(soap_ns)s:Header/> <%(soap_ns)s:Body> <%(ns)s:%(method)s> </%(ns)s:%(method)s> </%(soap_ns)s:Body> </%(soap_ns)s:Envelope>""" def __getattr__(self, attr): "Return a pseudo-method that can be called" if not self.services: # not using WSDL? return lambda self=self, *args, **kwargs: self.call(attr,*args,**kwargs) else: # using WSDL: return lambda self=self, *args, **kwargs: self.wsdl_call(attr,*args,**kwargs) def call(self, method, *args, **kwargs): "Prepare xml request and make SOAP call, returning a SimpleXMLElement" #TODO: method != input_message # Basic SOAP request: xml = self.__xml % dict(method=method, namespace=self.namespace, ns=self.__ns, soap_ns=self.__soap_ns, soap_uri=soap_namespaces[self.__soap_ns]) request = SimpleXMLElement(xml,namespace=self.__ns and self.namespace, prefix=self.__ns) # serialize parameters if kwargs: parameters = kwargs.items() else: parameters = args if parameters and isinstance(parameters[0], SimpleXMLElement): # merge xmlelement parameter ("raw" - already marshalled) for param in parameters[0].children(): getattr(request,method).import_node(param) else: # marshall parameters: for k,v in parameters: # dict: tag=valor getattr(request,method).marshall(k,v) self.xml_request = request.as_xml() self.xml_response = self.send(method, self.xml_request) response = SimpleXMLElement(self.xml_response, namespace=self.namespace) if self.exceptions and response("Fault", ns=soap_namespaces.values(), error=False): raise SoapFault(unicode(response.faultcode), unicode(response.faultstring)) return response def send(self, method, xml): "Send SOAP request using HTTP" if self.location == 'test': return location = "%s" % self.location #?op=%s" % (self.location, method) if self.services: soap_action = self.action else: soap_action = self.action+method headers={ 'Content-type': 'text/xml; charset="UTF-8"', 'Content-length': str(len(xml)), "SOAPAction": "\"%s\"" % (soap_action) } if self.trace: print "-"*80 print "POST %s" % location print '\n'.join(["%s: %s" % (k,v) for k,v in headers.items()]) print u"\n%s" % xml.decode("utf8","ignore") response, content = self.http.request( location,"POST", body=xml, headers=headers ) self.response = response self.content = content if self.trace: print print '\n'.join(["%s: %s" % (k,v) for k,v in response.items()]) print content#.decode("utf8","ignore") print "="*80 return content def get_operation(self, method): # try to find operation in wsdl file soap_ver = self.__soap_ns == 'soap12' and 'soap12' or 'soap11' if not self.service_port: for service_name, service in self.services.items(): for port_name, port in [port for port in service['ports'].items()]: if port['soap_ver'] == soap_ver: self.service_port = service_name, port_name break else: raise RuntimeError("Cannot determine service in WSDL: " "SOAP version: %s" % soap_ver) else: port = self.services[self.service_port[0]]['ports'][self.service_port[1]] self.location = port['location'] operation = port['operations'].get(unicode(method)) if not operation: raise RuntimeError("Operation %s not found in WSDL: " "Service/Port Type: %s" % (method, self.service_port)) return operation def wsdl_call(self, method, *args, **kwargs): "Pre and post process SOAP call, input and output parameters using WSDL" soap_uri = soap_namespaces[self.__soap_ns] operation = self.get_operation(method) # get i/o type declarations: input = operation['input'] output = operation['output'] if 'action' in operation: self.action = operation['action'] # sort parameters (same order as xsd:sequence) def sort_dict(od, d): if isinstance(od, dict): ret = OrderedDict() for k in od.keys(): v = d.get(k) if v: if isinstance(v, dict): v = sort_dict(od[k], v) elif isinstance(v, list): v = [sort_dict(od[k][0], v1) for v1 in v] ret[str(k)] = v return ret else: return d if input and kwargs: params = sort_dict(input.values()[0], kwargs).items() method = input.keys()[0] #elif not input: #TODO: no message! (see wsmtxca.dummy) else: params = kwargs and kwargs.items() # call remote procedure response = self.call(method, *params) # parse results: resp = response('Body',ns=soap_uri).children().unmarshall(output) return resp and resp.values()[0] # pass Response tag children def help(self, method): "Return operation documentation and invocation/returned value example" operation = self.get_operation(method) input = operation['input'].values() input = input and input[0] output = operation['output'].values()[0] return u"%s(%s)\n -> %s:\n\n%s" % ( method, input and ", ".join("%s=%s" % (k,repr(v)) for k,v in input.items()) or "", output and output or "", operation.get("documentation",""), ) def wsdl(self, url, debug=False, cache=False): "Parse Web Service Description v1.1" soap_ns = { "http://schemas.xmlsoap.org/wsdl/soap/": 'soap11', "http://schemas.xmlsoap.org/wsdl/soap12/": 'soap12', } wsdl_uri="http://schemas.xmlsoap.org/wsdl/" xsd_uri="http://www.w3.org/2001/XMLSchema" xsi_uri="http://www.w3.org/2001/XMLSchema-instance" get_local_name = lambda s: str((':' in s) and s.split(':')[1] or s) REVERSE_TYPE_MAP = dict([(v,k) for k,v in TYPE_MAP.items()]) def fetch(url): "Fetch a document from a URL, save it locally if cache enabled" import os, hashlib # make md5 hash of the url for caching... filename = "%s.xml" % hashlib.md5(url).hexdigest() if isinstance(cache, basestring): filename = os.path.join(cache, filename) if cache and os.path.exists(filename): if debug: print "Reading file %s" % (filename, ) f = open(filename, "r") xml = f.read() f.close() else: if debug: print "Fetching url %s" % (url, ) f = urllib.urlopen(url) xml = f.read() if cache: if debug: print "Writing file %s" % (filename, ) f = open(filename, "w") f.write(xml) f.close() return xml # Open uri and read xml: xml = fetch(url) # Parse WSDL XML: wsdl = SimpleXMLElement(xml, namespace=wsdl_uri) # detect soap prefix and uri (xmlns attributes of <definitions>) xsd_ns = None soap_uris = {} for k, v in wsdl[:]: if v in soap_ns and k.startswith("xmlns:"): soap_uris[get_local_name(k)] = v if v== xsd_uri and k.startswith("xmlns:"): xsd_ns = get_local_name(k) # Extract useful data: self.namespace = wsdl['targetNamespace'] self.documentation = unicode(wsdl('documentation', error=False) or '') services = {} bindings = {} # binding_name: binding operations = {} # operation_name: operation port_type_bindings = {} # port_type_name: binding messages = {} # message: element elements = {} # element: type def for service in wsdl.service: service_name=service['name'] if not service_name: continue # empty service? if debug: print "Processing service", service_name serv = services.setdefault(service_name, {'ports': {}}) serv['documentation']=service['documentation'] or '' for port in service.port: binding_name = get_local_name(port['binding']) address = port('address', ns=soap_uris.values(), error=False) location = address and address['location'] or None soap_uri = address and soap_uris.get(address.get_prefix()) soap_ver = soap_uri and soap_ns.get(soap_uri) bindings[binding_name] = {'service_name': service_name, 'location': location, 'soap_uri': soap_uri, 'soap_ver': soap_ver, } serv['ports'][port['name']] = bindings[binding_name] for binding in wsdl.binding: binding_name = binding['name'] if debug: print "Processing binding", service_name soap_binding = binding('binding', ns=soap_uris.values(), error=False) transport = soap_binding and soap_binding['transport'] or None port_type_name = get_local_name(binding['type']) bindings[binding_name].update({ 'port_type_name': port_type_name, 'transport': transport, 'operations': {}, }) port_type_bindings[port_type_name] = bindings[binding_name] for operation in binding.operation: op_name = operation['name'] op = operation('operation',ns=soap_uris.values(), error=False) action = op and op['soapAction'] d = operations.setdefault(op_name, {}) bindings[binding_name]['operations'][op_name] = d d.update({'name': op_name}) #if action: #TODO: separe operation_binding from operation if action: d["action"] = action #TODO: cleanup element/schema/types parsing: def process_element(element_name, node): "Parse and define simple element types" if debug: print "Processing element", element_name for tag in node: if tag.get_local_name() in ("annotation", "documentation"): continue elif tag.get_local_name() in ('element', 'restriction'): if debug: print element_name,"has not children!",tag children = tag # element "alias"? alias = True elif tag.children(): children = tag.children() alias = False else: if debug: print element_name,"has not children!",tag continue #TODO: abstract? d = OrderedDict() for e in children: t = e['type'] if not t: t = e['base'] # complexContent (extension)! if not t: t = 'anyType' # no type given! t = t.split(":") if len(t)>1: ns, type_name = t else: ns, type_name = None, t[0] if element_name == type_name: continue # prevent infinite recursion uri = ns and e.get_namespace_uri(ns) or xsd_uri if uri==xsd_uri: # look for the type, None == any fn = REVERSE_TYPE_MAP.get(unicode(type_name), None) else: # complex type, postprocess later fn = elements.setdefault(unicode(type_name), OrderedDict()) if e['name'] is not None and not alias: e_name = unicode(e['name']) d[e_name] = fn else: if debug: print "complexConent/simpleType/element", element_name, "=", type_name d[None] = fn if e['maxOccurs']=="unbounded": # it's an array... TODO: compound arrays? d.array = True if e is not None and e.get_local_name() == 'extension' and e.children(): # extend base element: process_element(element_name, e.children()) elements.setdefault(element_name, OrderedDict()).update(d) # check axis2 namespace at schema types attributes self.namespace = dict(wsdl.types("schema", ns=xsd_uri)[:]).get('targetNamespace', self.namespace) imported_schemas = {} def preprocess_schema(schema): "Find schema elements and complex types" for element in schema.children(): if element.get_local_name() in ('import', ): schema_namespace = element['namespace'] schema_location = element['schemaLocation'] if schema_location is None: if debug: print "Schema location not provided for %s!" % (schema_namespace, ) continue if schema_location in imported_schemas: if debug: print "Schema %s already imported!" % (schema_location, ) continue imported_schemas[schema_location] = schema_namespace if debug: print "Importing schema %s from %s" % (schema_namespace, schema_location) # Open uri and read xml: xml = fetch(schema_location) # Parse imported XML schema (recursively): imported_schema = SimpleXMLElement(xml, namespace=xsd_uri) preprocess_schema(imported_schema) if element.get_local_name() in ('element', 'complexType', "simpleType"): element_name = unicode(element['name']) if debug: print "Parsing Element %s: %s" % (element.get_local_name(),element_name) if element.get_local_name() == 'complexType': children = element.children() elif element.get_local_name() == 'simpleType': children = element("restriction", ns=xsd_uri) elif element.get_local_name() == 'element' and element['type']: children = element else: children = element.children() if children: children = children.children() elif element.get_local_name() == 'element': children = element if children: process_element(element_name, children) def postprocess_element(elements): "Fix unresolved references (elements referenced before its definition, thanks .net)" for k,v in elements.items(): if isinstance(v, OrderedDict): if v.array: elements[k] = [v] # convert arrays to python lists if v!=elements: #TODO: fix recursive elements postprocess_element(v) if None in v and v[None]: # extension base? if isinstance(v[None], dict): for i, kk in enumerate(v[None]): # extend base -keep orginal order- elements[k].insert(kk, v[None][kk], i) del v[None] else: # "alias", just replace if debug: print "Replacing ", k , " = ", v[None] elements[k] = v[None] #break if isinstance(v, list): for n in v: # recurse list postprocess_element(n) # process current wsdl schema: for schema in wsdl.types("schema", ns=xsd_uri): preprocess_schema(schema) postprocess_element(elements) for message in wsdl.message: if debug: print "Processing message", message['name'] part = message('part', error=False) element = {} if part: element_name = part['element'] if not element_name: element_name = part['type'] # some uses type instead element_name = get_local_name(element_name) element = {element_name: elements.get(element_name)} messages[message['name']] = element for port_type in wsdl.portType: port_type_name = port_type['name'] if debug: print "Processing port type", port_type_name binding = port_type_bindings[port_type_name] for operation in port_type.operation: op_name = operation['name'] op = operations[op_name] op['documentation'] = unicode(operation('documentation', error=False) or '') if binding['soap_ver']: #TODO: separe operation_binding from operation (non SOAP?) input = get_local_name(operation.input['message']) output = get_local_name(operation.output['message']) op['input'] = messages[input] op['output'] = messages[output] if debug: import pprint pprint.pprint(services) return services def parse_proxy(proxy_str): "Parses proxy address user:pass@host:port into a dict suitable for httplib2" proxy_dict = {} if proxy_str is None: return if "@" in proxy_str: user_pass, host_port = proxy_str.split("@") else: user_pass, host_port = "", proxy_str if ":" in host_port: host, port = host_port.split(":") proxy_dict['proxy_host'], proxy_dict['proxy_port'] = host, int(port) if ":" in user_pass: proxy_dict['proxy_user'], proxy_dict['proxy_pass'] = user_pass.split(":") return proxy_dict if __name__=="__main__": import sys if '--web2py' in sys.argv: # test local sample webservice exposed by web2py from client import SoapClient if not '--wsdl' in sys.argv: client = SoapClient( location = "http://127.0.0.1:8000/webservices/sample/call/soap", action = 'http://127.0.0.1:8000/webservices/sample/call/soap', # SOAPAction namespace = "http://127.0.0.1:8000/webservices/sample/call/soap", soap_ns='soap', trace = True, ns = False, exceptions=True) else: client = SoapClient(wsdl="http://127.0.0.1:8000/webservices/sample/call/soap?WSDL",trace=True) response = client.Dummy() print 'dummy', response response = client.Echo(value='hola') print 'echo', repr(response) response = client.AddIntegers(a=1,b=2) if not '--wsdl' in sys.argv: result = response.AddResult # manully convert returned type print int(result) else: result = response['AddResult'] print result, type(result), "auto-unmarshalled" if '--raw' in sys.argv: # raw (unmarshalled parameter) local sample webservice exposed by web2py from client import SoapClient client = SoapClient( location = "http://127.0.0.1:8000/webservices/sample/call/soap", action = 'http://127.0.0.1:8000/webservices/sample/call/soap', # SOAPAction namespace = "http://127.0.0.1:8000/webservices/sample/call/soap", soap_ns='soap', trace = True, ns = False) params = SimpleXMLElement("""<?xml version="1.0" encoding="UTF-8"?><AddIntegers><a>3</a><b>2</b></AddIntegers>""") # manully convert returned type response = client.call('AddIntegers',params) result = response.AddResult print int(result) # manully convert returned type if '--ctg' in sys.argv: # test AFIP Agriculture webservice client = SoapClient( location = "https://fwshomo.afip.gov.ar/wsctg/services/CTGService", action = 'http://impl.service.wsctg.afip.gov.ar/CTGService/', # SOAPAction namespace = "http://impl.service.wsctg.afip.gov.ar/CTGService/", trace = True, ns = True) response = client.dummy() result = response.dummyResponse print str(result.appserver) print str(result.dbserver) print str(result.authserver) if '--wsfe' in sys.argv: # Demo & Test (AFIP Electronic Invoice): ta_file = open("TA.xml") try: ta_string = ta_file.read() # read access ticket (wsaa.py) finally: ta_file.close() ta = SimpleXMLElement(ta_string) token = str(ta.credentials.token) sign = str(ta.credentials.sign) cuit = long(20267565393) id = 1234 cbte =199 client = SoapClient( location = "https://wswhomo.afip.gov.ar/wsfe/service.asmx", action = 'http://ar.gov.afip.dif.facturaelectronica/', # SOAPAction namespace = "http://ar.gov.afip.dif.facturaelectronica/", trace = True) results = client.FERecuperaQTYRequest( argAuth= {"Token": token, "Sign": sign, "cuit":long(cuit)} ) if int(results.FERecuperaQTYRequestResult.RError.percode) != 0: print "Percode: %s" % results.FERecuperaQTYRequestResult.RError.percode print "MSGerror: %s" % results.FERecuperaQTYRequestResult.RError.perrmsg else: print int(results.FERecuperaQTYRequestResult.qty.value) if '--feriados' in sys.argv: # Demo & Test: Argentina Holidays (Ministerio del Interior): # this webservice seems disabled from datetime import datetime, timedelta client = SoapClient( location = "http://webservices.mininterior.gov.ar/Feriados/Service.svc", action = 'http://tempuri.org/IMyService/', # SOAPAction namespace = "http://tempuri.org/FeriadoDS.xsd", trace = True) dt1 = datetime.today() - timedelta(days=60) dt2 = datetime.today() + timedelta(days=60) feriadosXML = client.FeriadosEntreFechasas_xml(dt1=dt1.isoformat(), dt2=dt2.isoformat()); print feriadosXML if '--wsdl-parse' in sys.argv: client = SoapClient() # Test PySimpleSOAP WSDL client.wsdl("file:C:/test.wsdl", debug=True) # Test Java Axis WSDL: client.wsdl('https://wsaahomo.afip.gov.ar/ws/services/LoginCms?wsdl',debug=True) # Test .NET 2.0 WSDL: client.wsdl('https://wswhomo.afip.gov.ar/wsfe/service.asmx?WSDL',debug=True) client.wsdl('https://wswhomo.afip.gov.ar/wsfex/service.asmx?WSDL',debug=True) client.wsdl('https://testdia.afip.gov.ar/Dia/Ws/wDigDepFiel/wDigDepFiel.asmx?WSDL',debug=True) # Test JBoss WSDL: client.wsdl('https://fwshomo.afip.gov.ar/wsctg/services/CTGService?wsdl',debug=True) client.wsdl('https://wsaahomo.afip.gov.ar/ws/services/LoginCms?wsdl',debug=True) if '--wsdl-client' in sys.argv: client = SoapClient(wsdl='https://wswhomo.afip.gov.ar/wsfex/service.asmx?WSDL',trace=True) results = client.FEXDummy() print results['FEXDummyResult']['AppServer'] print results['FEXDummyResult']['DbServer'] print results['FEXDummyResult']['AuthServer'] ta_file = open("TA.xml") try: ta_string = ta_file.read() # read access ticket (wsaa.py) finally: ta_file.close() ta = SimpleXMLElement(ta_string) token = str(ta.credentials.token) sign = str(ta.credentials.sign) response = client.FEXGetCMP( Auth={"Token": token, "Sign": sign, "Cuit": 20267565393}, Cmp={"Tipo_cbte": 19, "Punto_vta": 1, "Cbte_nro": 1}) result = response['FEXGetCMPResult'] if False: print result if 'FEXErr' in result: print "FEXError:", result['FEXErr']['ErrCode'], result['FEXErr']['ErrCode'] cbt = result['FEXResultGet'] print cbt['Cae'] FEX_event = result['FEXEvents'] print FEX_event['EventCode'], FEX_event['EventMsg'] if '--wsdl-ctg' in sys.argv: client = SoapClient(wsdl='https://fwshomo.afip.gov.ar/wsctg/services/CTGService?wsdl', trace=True, ns = "ctg") results = client.dummy() print results print results['DummyResponse']['appserver'] print results['DummyResponse']['dbserver'] print results['DummyResponse']['authserver'] ta_file = open("TA.xml") try: ta_string = ta_file.read() # read access ticket (wsaa.py) finally: ta_file.close() ta = SimpleXMLElement(ta_string) token = str(ta.credentials.token) sign = str(ta.credentials.sign) print client.help("obtenerProvincias") response = client.obtenerProvincias(auth={"token":token, "sign":sign, "cuitRepresentado":20267565393}) print "response=",response for ret in response: print ret['return']['codigoProvincia'], ret['return']['descripcionProvincia'].encode("latin1") prueba = dict(numeroCartaDePorte=512345678, codigoEspecie=23, cuitRemitenteComercial=20267565393, cuitDestino=20267565393, cuitDestinatario=20267565393, codigoLocalidadOrigen=3058, codigoLocalidadDestino=3059, codigoCosecha='0910', pesoNetoCarga=1000, cantHoras=1, patenteVehiculo='CZO985', cuitTransportista=20267565393, numeroCTG="43816783", transaccion='10000001681', observaciones='', ) response = client.solicitarCTG( auth={"token": token, "sign": sign, "cuitRepresentado": 20267565393}, solicitarCTGRequest= prueba) print response['return']['numeroCTG'] ##print parse_proxy(None) ##print parse_proxy("host:1234") ##print parse_proxy("user:pass@host:1234") ##sys.exit(0)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- "Contributed modules"
Python
#!/usr/bin/python # -*- coding: latin-1 -*- # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation; either version 3, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License # for more details. "Simple XML manipulation" __author__ = "Mariano Reingart (reingart@gmail.com)" __copyright__ = "Copyright (C) 2008/009 Mariano Reingart" __license__ = "LGPL 3.0" __version__ = "1.02c" import xml.dom.minidom from decimal import Decimal import datetime import time DEBUG = False # Functions to serialize/unserialize special immutable types: datetime_u = lambda s: datetime.datetime.strptime(s, "%Y-%m-%dT%H:%M:%S") datetime_m = lambda dt: dt.isoformat('T') date_u = lambda s: datetime.datetime.strptime(s[0:10], "%Y-%m-%d").date() date_m = lambda d: d.strftime("%Y-%m-%d") time_u = lambda s: datetime.datetime.strptime(s, "%H:%M:%S").time() time_m = lambda d: d.strftime("%H%M%S") bool_u = lambda s: {'0':False, 'false': False, '1': True, 'true': True}[s] # aliases: class Alias(): def __init__(self, py_type, xml_type): self.py_type, self.xml_type = py_type, xml_type def __call__(self, value): return self.py_type(value) def __repr__(self): return "<alias '%s' for '%s'>" % (self.xml_type, self.py_type) byte = Alias(str,'byte') short = Alias(int,'short') double = Alias(float,'double') integer = Alias(long,'integer') DateTime = datetime.datetime Date = datetime.date Time = datetime.time # Define convertion function (python type): xml schema type TYPE_MAP = {str:'string',unicode:'string', bool:'boolean', short:'short', byte:'byte', int:'int', long:'long', integer:'integer', float:'float', double:'double', Decimal:'decimal', datetime.datetime:'dateTime', datetime.date:'date', } TYPE_MARSHAL_FN = {datetime.datetime:datetime_m, datetime.date:date_m,} TYPE_UNMARSHAL_FN = {datetime.datetime:datetime_u, datetime.date:date_u, bool:bool_u, } class OrderedDict(dict): "Minimal ordered dictionary for xsd:sequences" def __init__(self): self.__keys = [] self.array = False def __setitem__(self, key, value): if key not in self.__keys: self.__keys.append(key) dict.__setitem__(self, key, value) def insert(self, key, value, index=0): if key not in self.__keys: self.__keys.insert(index, key) dict.__setitem__(self, key, value) def __delitem__(self, key): if key in self.__keys: self.__keys.remove(key) dict.__delitem__(self, key) def __iter__(self): return iter(self.__keys) def keys(self): return self.__keys def items(self): return [(key, self[key]) for key in self.__keys] def update(self, other): for k,v in other.items(): self[k] = v if isinstance(other, OrderedDict): self.array = other.array def __str__(self): return "*%s*" % dict.__str__(self) def __repr__(self): s= "*{%s}*" % ", ".join(['%s: %s' % (repr(k),repr(v)) for k,v in self.items()]) if self.array and False: s = "[%s]" % s return s class SimpleXMLElement(object): "Simple XML manipulation (simil PHP)" def __init__(self, text = None, elements = None, document = None, namespace = None, prefix=None): self.__ns = namespace self.__prefix = prefix if text: try: self.__document = xml.dom.minidom.parseString(text) except: if DEBUG: print text raise self.__elements = [self.__document.documentElement] else: self.__elements = elements self.__document = document def add_child(self,name,text=None,ns=True): "Adding a child tag to a node" if not ns or not self.__ns: if DEBUG: print "adding %s" % (name) element = self.__document.createElement(name) else: if DEBUG: print "adding %s ns %s %s" % (name, self.__ns,ns) if self.__prefix: element = self.__document.createElementNS(self.__ns, "%s:%s" % (self.__prefix, name)) else: element = self.__document.createElementNS(self.__ns, name) if text: if isinstance(text, unicode): element.appendChild(self.__document.createTextNode(text)) else: element.appendChild(self.__document.createTextNode(str(text))) self._element.appendChild(element) return SimpleXMLElement( elements=[element], document=self.__document, namespace=self.__ns, prefix=self.__prefix) def __setattr__(self, tag, text): "Add text child tag node (short form)" if tag.startswith("_"): object.__setattr__(self, tag, text) else: if DEBUG: print "__setattr__(%s,%s)" % (tag, text) self.add_child(tag,text) def add_comment(self, data): "Add an xml comment to this child" comment = self.__document.createComment(data) self._element.appendChild(comment) def as_xml(self,filename=None,pretty=False): "Return the XML representation of the document" if not pretty: return self.__document.toxml('UTF-8') else: return self.__document.toprettyxml(encoding='UTF-8') def __repr__(self): "Return the XML representation of this tag" return self._element.toxml('UTF-8') def get_name(self): "Return the tag name of this node" return self._element.tagName def get_local_name(self): "Return the tag loca name (prefix:name) of this node" return self._element.localName def get_prefix(self): "Return the namespace prefix of this node" return self._element.prefix def get_namespace_uri(self, ns): "Return the namespace uri for a prefix" v = self.__document.documentElement.attributes['xmlns:%s' % ns] return v.value def attributes(self): "Return a dict of attributes for this tag" #TODO: use slice syntax [:]? return self._element.attributes def __getitem__(self, item): "Return xml tag attribute value or a slice of attributes (iter)" if DEBUG: print "__getitem__(%s)" % item if isinstance(item,basestring): if self._element.hasAttribute(item): return self._element.attributes[item].value elif isinstance(item, slice): # return a list with name:values return self._element.attributes.items()[item] else: # return element by index (position) element = self.__elements[item] return SimpleXMLElement( elements=[element], document=self.__document, namespace=self.__ns, prefix=self.__prefix) def add_attribute(self, name, value): "Set an attribute value from a string" self._element.setAttribute(name, value) def __setitem__(self, item, value): "Set an attribute value" if isinstance(item,basestring): self.add_attribute(item, value) elif isinstance(item, slice): # set multiple attributes at once for k, v in value.items(): self.add_attribute(k, v) def __call__(self, tag=None, ns=None, children=False, error=True): "Search (even in child nodes) and return a child tag by name" try: if tag is None: # if no name given, iterate over siblings (same level) return self.__iter__() if children: # future: filter children? by ns? return self.children() elements = None if isinstance(tag, int): # return tag by index elements=[self.__elements[tag]] if ns and not elements: for ns_uri in isinstance(ns, (tuple, list)) and ns or (ns, ): if DEBUG: print "searching %s by ns=%s" % (tag,ns_uri) elements = self._element.getElementsByTagNameNS(ns_uri, tag) if elements: break if self.__ns and not elements: if DEBUG: print "searching %s by ns=%s" % (tag, self.__ns) elements = self._element.getElementsByTagNameNS(self.__ns, tag) if not elements: if DEBUG: print "searching %s " % (tag) elements = self._element.getElementsByTagName(tag) if not elements: if DEBUG: print self._element.toxml() if error: raise AttributeError("No elements found") else: return return SimpleXMLElement( elements=elements, document=self.__document, namespace=self.__ns, prefix=self.__prefix) except AttributeError, e: raise AttributeError("Tag not found: %s (%s)" % (tag, str(e))) def __getattr__(self, tag): "Shortcut for __call__" return self.__call__(tag) def __iter__(self): "Iterate over xml tags at this level" try: for __element in self.__elements: yield SimpleXMLElement( elements=[__element], document=self.__document, namespace=self.__ns, prefix=self.__prefix) except: raise def __dir__(self): "List xml children tags names" return [node.tagName for node in self._element.childNodes if node.nodeType != node.TEXT_NODE] def children(self): "Return xml children tags element" elements=[__element for __element in self._element.childNodes if __element.nodeType == __element.ELEMENT_NODE] if not elements: return None #raise IndexError("Tag %s has no children" % self._element.tagName) return SimpleXMLElement( elements=elements, document=self.__document, namespace=self.__ns, prefix=self.__prefix) def __len__(self): "Return elements count" return len(self.__elements) def __contains__( self, item): "Search for a tag name in this element or child nodes" return self._element.getElementsByTagName(item) def __unicode__(self): "Returns the unicode text nodes of the current element" if self._element.childNodes: rc = u"" for node in self._element.childNodes: if node.nodeType == node.TEXT_NODE: rc = rc + node.data return rc return '' def __str__(self): "Returns the str text nodes of the current element" return unicode(self).encode("utf8","ignore") def __int__(self): "Returns the integer value of the current element" return int(self.__str__()) def __float__(self): "Returns the float value of the current element" try: return float(self.__str__()) except: raise IndexError(self._element.toxml()) _element = property(lambda self: self.__elements[0]) def unmarshall(self, types): "Convert to python values the current serialized xml element" # types is a dict of {tag name: convertion function} # example: types={'p': {'a': int,'b': int}, 'c': [{'d':str}]} # expected xml: <p><a>1</a><b>2</b></p><c><d>hola</d><d>chau</d> # returnde value: {'p': {'a':1,'b':2}, `'c':[{'d':'hola'},{'d':'chau'}]} d = {} for node in self(): name = str(node.get_local_name()) try: fn = types[name] except (KeyError, ), e: raise TypeError("Tag: %s invalid" % (name,)) if isinstance(fn,list): value = [] children = node.children() for child in children and children() or []: value.append(child.unmarshall(fn[0])) elif isinstance(fn,dict): children = node.children() value = children and children.unmarshall(fn) else: if fn is None: # xsd:anyType not unmarshalled value = node elif str(node) or fn == str: try: # get special desserialization function (if any) fn = TYPE_UNMARSHAL_FN.get(fn,fn) value = fn(unicode(node)) except (ValueError, TypeError), e: raise ValueError("Tag: %s: %s" % (name, unicode(e))) else: value = None d[name] = value return d def marshall(self, name, value, add_child=True, add_comments=False, ns=False): "Analize python value and add the serialized XML element using tag name" if isinstance(value, dict): # serialize dict (<key>value</key>) child = add_child and self.add_child(name,ns=ns) or self for k,v in value.items(): child.marshall(k, v, add_comments=add_comments, ns=ns) elif isinstance(value, tuple): # serialize tuple (<key>value</key>) child = add_child and self.add_child(name,ns=ns) or self for k,v in value: getattr(self,name).marshall(k, v, add_comments=add_comments, ns=ns) elif isinstance(value, list): # serialize lists child=self.add_child(name,ns=ns) if add_comments: child.add_comment("Repetitive array of:") for t in value: child.marshall(name,t, False, add_comments=add_comments, ns=ns) elif isinstance(value, basestring): # do not convert strings or unicodes self.add_child(name,value,ns=ns) elif value is None: # sent a empty tag? self.add_child(name,ns=ns) elif value in TYPE_MAP.keys(): # add commented placeholders for simple tipes (for examples/help only) child = self.add_child(name,ns=ns) child.add_comment(TYPE_MAP[value]) else: # the rest of object types are converted to string # get special serialization function (if any) fn = TYPE_MARSHAL_FN.get(type(value),str) self.add_child(name,fn(value),ns=ns) def import_node(self, other): x = self.__document.importNode(other._element, True) # deep copy self._element.appendChild(x) if __name__ == "__main__": span = SimpleXMLElement('<span><a href="python.org.ar">pyar</a><prueba><i>1</i><float>1.5</float></prueba></span>') assert str(span.a)==str(span('a'))==str(span.a(0))=="pyar" assert span.a['href']=="python.org.ar" assert int(span.prueba.i)==1 and float(span.prueba.float)==1.5 span1 = SimpleXMLElement('<span><a href="google.com">google</a><a>yahoo</a><a>hotmail</a></span>') assert [str(a) for a in span1.a()] == ['google', 'yahoo', 'hotmail'] span1.add_child('a','altavista') span1.b = "ex msn" d = {'href':'http://www.bing.com/', 'alt': 'Bing'} span1.b[:] = d assert sorted([(k,v) for k,v in span1.b[:]]) == sorted(d.items()) print span1.as_xml() assert 'b' in span1 span.import_node(span1) print span.as_xml()
Python
#!/usr/bin/env python # created my Massimo Di Pierro # license MIT/BSD/GPL import re import cgi __all__ = ['render', 'markmin2html'] __doc__ = """ # Markmin markup language ## About This is a new markup language that we call markmin designed to produce high quality scientific papers and books and also put them online. We provide serializers for html, latex and pdf. It is implemented in the ``markmin2html`` function in the ``markmin2html.py``. Example of usage: `` >>> m = "Hello **world** [[link http://web2py.com]]" >>> from markmin2html import markmin2html >>> print markmin2html(m) >>> from markmin2latex import markmin2latex >>> print markmin2latex(m) >>> from markmin2pdf import markmin2pdf # requires pdflatex >>> print markmin2pdf(m) `` ## Why? We wanted a markup language with the following requirements: - less than 100 lines of functional code - easy to read - secure - support table, ul, ol, code - support html5 video and audio elements (html serialization only) - can align images and resize them - can specify class for tables and code elements - can add anchors - does not use _ for markup (since it creates odd behavior) - automatically links urls - fast - easy to extend - supports latex and pdf including references - allows to describe the markup in the markup (this document is generated from markmin syntax) (results depend on text but in average for text ~100K markmin is 30% faster than markdown, for text ~10K it is 10x faster) The [[web2py book http://www.lulu.com/product/paperback/web2py-%283rd-edition%29/12822827]] published by lulu, for example, was entirely generated with markmin2pdf from the online [[web2py wiki http://www.web2py.com/book]] ## Download - http://web2py.googlecode.com/hg/gluon/contrib/markmin/markmin2html.py - http://web2py.googlecode.com/hg/gluon/contrib/markmin/markmin2latex.py - http://web2py.googlecode.com/hg/gluon/contrib/markmin/markmin2pdf.py markmin2html.py and markmin2latex.py are single files and have no web2py dependence. Their license is BSD. ## Examples ### Bold, italic, code and links -------------------------------------------------- **SOURCE** | **OUTPUT** ``# title`` | **title** ``## section`` | **section** ``### subsection`` | **subsection** ``**bold**`` | **bold** ``''italic''`` | ''italic'' ``!`!`verbatim`!`!`` | ``verbatim`` ``http://google.com`` | http://google.com ``[[click me #myanchor]]`` | [[click me #myanchor]] --------------------------------------------------- ### More on links The format is always ``[[title link]]``. Notice you can nest bold, italic and code inside the link title. ### Anchors [[myanchor]] You can place an anchor anywhere in the text using the syntax ``[[name]]`` where ''name'' is the name of the anchor. You can then link the anchor with [[link #myanchor]], i.e. ``[[link #myanchor]]``. ### Images [[some image http://www.web2py.com/examples/static/web2py_logo.png right 200px]] This paragraph has an image aligned to the right with a width of 200px. Its is placed using the code ``[[some image http://www.web2py.com/examples/static/web2py_logo.png right 200px]]``. ### Unordered Lists `` - Dog - Cat - Mouse `` is rendered as - Dog - Cat - Mouse Two new lines between items break the list in two lists. ### Ordered Lists `` + Dog + Cat + Mouse `` is rendered as + Dog + Cat + Mouse ### Tables Something like this `` --------- **A** | **B** | **C** 0 | 0 | X 0 | X | 0 X | 0 | 0 -----:abc `` is a table and is rendered as --------- **A** | **B** | **C** 0 | 0 | X 0 | X | 0 X | 0 | 0 -----:abc Four or more dashes delimit the table and | separates the columns. The ``:abc`` at the end sets the class for the table and it is optional. ### Blockquote A table with a single cell is rendered as a blockquote: ----- Hello world ----- ### Code, ``<code>``, escaping and extra stuff `` def test(): return "this is Python code" ``:python Optionally a ` inside a ``!`!`...`!`!`` block can be inserted escaped with !`!. The ``:python`` after the markup is also optional. If present, by default, it is used to set the class of the <code> block. The behavior can be overridden by passing an argument ``extra`` to the ``render`` function. For example: `` >>> markmin2html("!`!!`!aaa!`!!`!:custom", extra=dict(custom=lambda text: 'x'+text+'x')) ``:python generates ``'xaaax'``:python (the ``!`!`...`!`!:custom`` block is rendered by the ``custom=lambda`` function passed to ``render``). ### Html5 support Markmin also supports the <video> and <audio> html5 tags using the notation: `` [[title link video]] [[title link audio]] `` ### Latex and other extensions Formulas can be embedded into HTML with ``$````$``formula``$````$``. You can use Google charts to render the formula: `` >>> LATEX = '<img src="http://chart.apis.google.com/chart?cht=tx&chl=%s" align="ce\ nter"/>' >>> markmin2html(text,{'latex':lambda code: LATEX % code.replace('"','\"')}) `` ### Code with syntax highlighting This requires a syntax highlighting tool, such as the web2py CODE helper. `` >>> extra={'code_cpp':lambda text: CODE(text,language='cpp').xml(), 'code_java':lambda text: CODE(text,language='java').xml(), 'code_python':lambda text: CODE(text,language='python').xml(), 'code_html':lambda text: CODE(text,language='html').xml()} >>> markmin2html(text,extra=extra) `` Code can now be marked up as in this example: `` !`!` <html><body>example</body></html> !`!`:code_html `` ### Citations and References Citations are treated as internal links in html and proper citations in latex if there is a final section called "References". Items like `` - [[key]] value `` in the References will be translated into Latex `` \\bibitem{key} value `` Here is an example of usage: `` As shown in Ref.!`!`mdipierro`!`!:cite ## References - [[mdipierro]] web2py Manual, 3rd Edition, lulu.com `` ### Caveats ``<ul/>``, ``<ol/>``, ``<code/>``, ``<table/>``, ``<blockquote/>``, ``<h1/>``, ..., ``<h6/>`` do not have ``<p>...</p>`` around them. """ META = 'META' LATEX = '<img src="http://chart.apis.google.com/chart?cht=tx&chl=%s" align="center"/>' regex_newlines = re.compile('(\n\r)|(\r\n)') regex_dd=re.compile('\$\$(?P<latex>.*?)\$\$') regex_code = re.compile('('+META+')|(``(?P<t>.*?)``(:(?P<c>\w+))?)',re.S) regex_maps = [ (re.compile('[ \t\r]+\n'),'\n'), (re.compile('[ \t\r]+\n'),'\n'), (re.compile('\*\*(?P<t>[^\s\*]+( +[^\s\*]+)*)\*\*'),'<b>\g<t></b>'), (re.compile("''(?P<t>[^\s']+( +[^\s']+)*)''"),'<i>\g<t></i>'), (re.compile('^#{6} (?P<t>[^\n]+)',re.M),'\n\n<<h6>\g<t></h6>\n'), (re.compile('^#{5} (?P<t>[^\n]+)',re.M),'\n\n<<h5>\g<t></h5>\n'), (re.compile('^#{4} (?P<t>[^\n]+)',re.M),'\n\n<<h4>\g<t></h4>\n'), (re.compile('^#{3} (?P<t>[^\n]+)',re.M),'\n\n<<h3>\g<t></h3>\n'), (re.compile('^#{2} (?P<t>[^\n]+)',re.M),'\n\n<<h2>\g<t></h2>\n'), (re.compile('^#{1} (?P<t>[^\n]+)',re.M),'\n\n<<h1>\g<t></h1>\n'), (re.compile('^\- +(?P<t>.*)',re.M),'<<ul><li>\g<t></li></ul>'), (re.compile('^\+ +(?P<t>.*)',re.M),'<<ol><li>\g<t></li></ol>'), (re.compile('</ol>\n<<ol>'),''), (re.compile('</ul>\n<<ul>'),''), (re.compile('<<'),'\n\n<<'), (re.compile('\n\s+\n'),'\n\n')] regex_table = re.compile('^\-{4,}\n(?P<t>.*?)\n\-{4,}(:(?P<c>\w+))?\n',re.M|re.S) regex_anchor = re.compile('\[\[(?P<t>\S+)\]\]') regex_image_width = re.compile('\[\[(?P<t>.*?) +(?P<k>\S+) +(?P<p>left|right|center) +(?P<w>\d+px)\]\]') regex_image = re.compile('\[\[(?P<t>.*?) +(?P<k>\S+) +(?P<p>left|right|center)\]\]') regex_video = re.compile('\[\[(?P<t>.*?) +(?P<k>\S+) +video\]\]') regex_audio = re.compile('\[\[(?P<t>.*?) +(?P<k>\S+) +audio\]\]') regex_link = re.compile('\[\[(?P<t>.*?) +(?P<k>\S+)\]\]') regex_link_popup = re.compile('\[\[(?P<t>.*?) +(?P<k>\S+) popup\]\]') regex_link_no_anchor = re.compile('\[\[ +(?P<k>\S+)\]\]') regex_auto = re.compile('(?<!["\w\>])(?P<k>\w+://[\w\.\-\+\?&%\/]+)',re.M) def render(text,extra={},allowed={},sep='p'): """ Arguments: - text is the text to be processed - extra is a dict like extra=dict(custom=lambda value: value) that process custom code as in " ``this is custom code``:custom " - allowed is a dictionary of list of allowed classes like allowed = dict(code=('python','cpp','java')) - sep can be 'p' to separate text in <p>...</p> or can be 'br' to separate text using <br /> >>> render('this is\\n# a section\\nparagraph') '<p>this is</p><h1>a section</h1><p>paragraph</p>' >>> render('this is\\n## a subsection\\nparagraph') '<p>this is</p><h2>a subsection</h2><p>paragraph</p>' >>> render('this is\\n### a subsubsection\\nparagraph') '<p>this is</p><h3>a subsubsection</h3><p>paragraph</p>' >>> render('**hello world**') '<p><b>hello world</b></p>' >>> render('``hello world``') '<code class="">hello world</code>' >>> render('``hello world``:python') '<code class="python">hello world</code>' >>> render('``\\nhello\\nworld\\n``:python') '<pre><code class="python">hello\\nworld</code></pre>' >>> render("''hello world''") '<p><i>hello world</i></p>' >>> render('** hello** **world**') '<p>** hello** <b>world</b></p>' >>> render('- this\\n- is\\n- a list\\n\\nand this\\n- is\\n- another') '<ul><li>this</li><li>is</li><li>a list</li></ul><p>and this</p><ul><li>is</li><li>another</li></ul>' >>> render('+ this\\n+ is\\n+ a list\\n\\nand this\\n+ is\\n+ another') '<ol><li>this</li><li>is</li><li>a list</li></ol><p>and this</p><ol><li>is</li><li>another</li></ol>' >>> render("----\\na | b\\nc | d\\n----\\n") '<table class=""><tr><td>a</td><td>b</td></tr><tr><td>c</td><td>d</td></tr></table>' >>> render("----\\nhello world\\n----\\n") '<blockquote class="">hello world</blockquote>' >>> render('[[this is a link http://example.com]]') '<p><a href="http://example.com">this is a link</a></p>' >>> render('[[this is an image http://example.com left]]') '<p><img src="http://example.com" alt="this is an image" align="left" /></p>' >>> render('[[this is an image http://example.com left 200px]]') '<p><img src="http://example.com" alt="this is an image" align="left" width="200px" /></p>' >>> render('[[this is an image http://example.com video]]') '<p><video src="http://example.com" controls></video></p>' >>> render('[[this is an image http://example.com audio]]') '<p><audio src="http://example.com" controls></audio></p>' >>> render('[[this is a **link** http://example.com]]') '<p><a href="http://example.com">this is a <b>link</b></a></p>' >>> render("``aaa``:custom",extra=dict(custom=lambda text: 'x'+text+'x')) 'xaaax' >>> render(r"$$\int_a^b sin(x)dx$$") '<code class="latex">\\\\int_a^b sin(x)dx</code>' """ text = str(text or '') ############################################################# # replace all blocks marked with ``...``:class with META # store them into segments they will be treated as code ############################################################# segments, i = [], 0 text = regex_dd.sub('``\g<latex>``:latex ',text) text = regex_newlines.sub('\n',text) while True: item = regex_code.search(text,i) if not item: break if item.group()==META: segments.append((None,None)) text = text[:item.start()]+META+text[item.end():] else: c = item.group('c') or '' if 'code' in allowed and not c in allowed['code']: c = '' code = item.group('t').replace('!`!','`') segments.append((code,c)) text = text[:item.start()]+META+text[item.end():] i=item.start()+3 ############################################################# # do h1,h2,h3,h4,h5,h6,b,i,ol,ul and normalize spaces ############################################################# text = '\n'.join(t.strip() for t in text.split('\n')) text = cgi.escape(text) for regex, sub in regex_maps: text = regex.sub(sub,text) ############################################################# # process tables and blockquotes ############################################################# while True: item = regex_table.search(text) if not item: break c = item.group('c') or '' if 'table' in allowed and not c in allowed['table']: c = '' content = item.group('t') if ' | ' in content: rows = content.replace('\n','</td></tr><tr><td>').replace(' | ','</td><td>') text = text[:item.start()] + '<<table class="%s"><tr><td>'%c + rows + '</td></tr></table>' + text[item.end():] else: text = text[:item.start()] + '<<blockquote class="%s">'%c + content + '</blockquote>' + text[item.end():] ############################################################# # deal with images, videos, audios and links ############################################################# text = regex_anchor.sub('<span id="\g<t>"><span>', text) text = regex_image_width.sub('<img src="\g<k>" alt="\g<t>" align="\g<p>" width="\g<w>" />', text) text = regex_image.sub('<img src="\g<k>" alt="\g<t>" align="\g<p>" />', text) text = regex_video.sub('<video src="\g<k>" controls></video>', text) text = regex_audio.sub('<audio src="\g<k>" controls></audio>', text) text = regex_link_popup.sub('<a href="\g<k>" target="_blank">\g<t></a>', text) text = regex_link_no_anchor.sub('<a href="\g<k>">\g<k></a>', text) text = regex_link.sub('<a href="\g<k>">\g<t></a>', text) text = regex_auto.sub('<a href="\g<k>">\g<k></a>', text) ############################################################# # deal with paragraphs (trick <<ul, <<ol, <<table, <<h1, etc) # the << indicates that there should NOT be a new paragraph # META indicates a code block therefore no new paragraph ############################################################# items = [item.strip() for item in text.split('\n\n')] if sep=='p': text = ''.join(p[:2]!='<<' and p!=META and '<p>%s</p>'%p or '%s'%p for p in items if p) elif sep=='br': text = '<br />'.join(items) ############################################################# # finally get rid of << ############################################################# text=text.replace('<<','<') ############################################################# # process all code text ############################################################# parts = text.split(META) text = parts[0] for i,(code,b) in enumerate(segments): if code==None: html = META else: if b in extra: if code[:1]=='\n': code=code[1:] if code[-1:]=='\n': code=code[:-1] html = extra[b](code) elif b=='cite': html = '['+','.join('<a href="#%s" class="%s">%s</a>' \ % (d,b,d) \ for d in cgi.escape(code).split(','))+']' elif b=='latex': html = LATEX % code.replace('"','\"').replace('\n',' ') elif code[:1]=='\n' or code[-1:]=='\n': if code[:1]=='\n': code=code[1:] if code[-1:]=='\n': code=code[:-1] html = '<pre><code class="%s">%s</code></pre>' % (b,cgi.escape(code)) else: if code[:1]=='\n': code=code[1:] if code[-1:]=='\n': code=code[:-1] html = '<code class="%s">%s</code>' % (b,cgi.escape(code)) text = text+html+parts[i+1] return text def markmin2html(text,extra={},allowed={},sep='p'): return render(text,extra,allowed,sep) if __name__ == '__main__': import sys import doctest if sys.argv[1:2]==['-h']: print '<html><body>'+markmin2html(__doc__)+'</body></html>' elif len(sys.argv)>1: fargv = open(sys.argv[1],'r') try: print '<html><body>'+markmin2html(fargv.read())+'</body></html>' finally: fargv.close() else: doctest.testmod()
Python
#!/usr/bin/env python # created my Massimo Di Pierro # license MIT/BSD/GPL import re import cgi import sys import doctest from optparse import OptionParser __all__ = ['render','markmin2latex'] META = 'META' regex_newlines = re.compile('(\n\r)|(\r\n)') regex_dd=re.compile('\$\$(?P<latex>.*?)\$\$') regex_code = re.compile('('+META+')|(``(?P<t>.*?)``(:(?P<c>\w+))?)',re.S) regex_title = re.compile('^#{1} (?P<t>[^\n]+)',re.M) regex_maps = [ (re.compile('[ \t\r]+\n'),'\n'), (re.compile('[ \t\r]+\n'),'\n'), (re.compile('\*\*(?P<t>[^\s\*]+( +[^\s\*]+)*)\*\*'),'{\\\\bf \g<t>}'), (re.compile("''(?P<t>[^\s']+( +[^\s']+)*)''"),'{\\it \g<t>}'), (re.compile('^#{6} (?P<t>[^\n]+)',re.M),'\n\n{\\\\bf \g<t>}\n'), (re.compile('^#{5} (?P<t>[^\n]+)',re.M),'\n\n{\\\\bf \g<t>}\n'), (re.compile('^#{4} (?P<t>[^\n]+)',re.M),'\n\n\\\\goodbreak\\subsubsection{\g<t>}\n'), (re.compile('^#{3} (?P<t>[^\n]+)',re.M),'\n\n\\\\goodbreak\\subsection{\g<t>}\n'), (re.compile('^#{2} (?P<t>[^\n]+)',re.M),'\n\n\\\\goodbreak\\section{\g<t>}\n'), (re.compile('^#{1} (?P<t>[^\n]+)',re.M),''), (re.compile('^\- +(?P<t>.*)',re.M),'\\\\begin{itemize}\n\\item \g<t>\n\\end{itemize}'), (re.compile('^\+ +(?P<t>.*)',re.M),'\\\\begin{itemize}\n\\item \g<t>\n\\end{itemize}'), (re.compile('\\\\end\{itemize\}\s+\\\\begin\{itemize\}'),'\n'), (re.compile('\n\s+\n'),'\n\n')] regex_table = re.compile('^\-{4,}\n(?P<t>.*?)\n\-{4,}(:(?P<c>\w+))?\n',re.M|re.S) regex_anchor = re.compile('\[\[(?P<t>\S+)\]\]') regex_bibitem = re.compile('\-\s*\[\[(?P<t>\S+)\]\]') regex_image_width = re.compile('\[\[(?P<t>.*?) +(?P<k>\S+) +(?P<p>left|right|center) +(?P<w>\d+px)\]\]') regex_image = re.compile('\[\[(?P<t>.*?) +(?P<k>\S+) +(?P<p>left|right|center)\]\]') #regex_video = re.compile('\[\[(?P<t>.*?) +(?P<k>\S+) +video\]\]') #regex_audio = re.compile('\[\[(?P<t>.*?) +(?P<k>\S+) +audio\]\]') regex_link = re.compile('\[\[(?P<t>.*?) +(?P<k>\S+)\]\]') regex_auto = re.compile('(?<!["\w])(?P<k>\w+://[\w\.\-\?&%]+)',re.M) regex_commas = re.compile('[ ]+(?P<t>[,;\.])') regex_noindent = re.compile('\n\n(?P<t>[a-z])') regex_quote_left = re.compile('"(?=\w)') regex_quote_right = re.compile('(?=\w\.)"') def latex_escape(text,pound=True): text=text.replace('\\','{\\textbackslash}') for c in '^_&$%{}': text=text.replace(c,'\\'+c) text=text.replace('\\{\\textbackslash\\}','{\\textbackslash}') if pound: text=text.replace('#','\\#') return text def render(text,extra={},allowed={},sep='p',image_mapper=lambda x:x): ############################################################# # replace all blocks marked with ``...``:class with META # store them into segments they will be treated as code ############################################################# text = str(text or '') segments, i = [], 0 text = regex_dd.sub('``\g<latex>``:latex ',text) text = regex_newlines.sub('\n',text) while True: item = regex_code.search(text,i) if not item: break if item.group()==META: segments.append((None,None)) text = text[:item.start()]+META+text[item.end():] else: c = item.group('c') or '' if 'code' in allowed and not c in allowed['code']: c = '' code = item.group('t').replace('!`!','`') segments.append((code,c)) text = text[:item.start()]+META+text[item.end():] i=item.start()+3 ############################################################# # do h1,h2,h3,h4,h5,h6,b,i,ol,ul and normalize spaces ############################################################# title = regex_title.search(text) if not title: title='Title' else: title=title.group('t') text = latex_escape(text,pound=False) texts = text.split('## References',1) text = regex_anchor.sub('\\label{\g<t>}', texts[0]) if len(texts)==2: text += '\n\\begin{thebibliography}{999}\n' text += regex_bibitem.sub('\n\\\\bibitem{\g<t>}', texts[1]) text += '\n\\end{thebibliography}\n' text = '\n'.join(t.strip() for t in text.split('\n')) for regex, sub in regex_maps: text = regex.sub(sub,text) text=text.replace('#','\\#') text=text.replace('`',"'") ############################################################# # process tables and blockquotes ############################################################# while True: item = regex_table.search(text) if not item: break c = item.group('c') or '' if 'table' in allowed and not c in allowed['table']: c = '' content = item.group('t') if ' | ' in content: rows = content.replace('\n','\\\\\n').replace(' | ',' & ') row0,row2 = rows.split('\\\\\n',1) cols=row0.count(' & ')+1 cal='{'+''.join('l' for j in range(cols))+'}' tabular = '\\begin{center}\n{\\begin{tabular}'+cal+'\\hline\n' + row0+'\\\\ \\hline\n'+row2 + ' \\\\ \\hline\n\\end{tabular}}\n\\end{center}' if row2.count('\n')>20: tabular='\\newpage\n'+tabular text = text[:item.start()] + tabular + text[item.end():] else: text = text[:item.start()] + '\\begin{quote}' + content + '\\end{quote}' + text[item.end():] ############################################################# # deal with images, videos, audios and links ############################################################# def sub(x): f=image_mapper(x.group('k')) if not f: return None return '\n\\begin{center}\\includegraphics[width=8cm]{%s}\\end{center}\n' % (f) text = regex_image_width.sub(sub,text) text = regex_image.sub(sub,text) text = regex_link.sub('{\\\\footnotesize\\href{\g<k>}{\g<t>}}', text) text = regex_commas.sub('\g<t>',text) text = regex_noindent.sub('\n\\\\noindent \g<t>',text) ### fix paths in images regex=re.compile('\\\\_[\w_]*\.(eps|png|jpg|gif)') while True: match=regex.search(text) if not match: break text=text[:match.start()]+text[match.start()+1:] text = regex_quote_left.sub('``',text) text = regex_quote_right.sub("''",text) ############################################################# # process all code text ############################################################# parts = text.split(META) text = parts[0] authors = [] for i,(code,b) in enumerate(segments): if code==None: html = META else: if b=='hidden': html='' elif b=='author': author = latex_escape(code.strip()) authors.append(author) html='' elif b=='inxx': html='\inxx{%s}' % latex_escape(code) elif b=='cite': html='~\cite{%s}' % latex_escape(code.strip()) elif b=='ref': html='~\ref{%s}' % latex_escape(code.strip()) elif b=='latex': if '\n' in code: html='\n\\begin{equation}\n%s\n\\end{equation}\n' % code.strip() else: html='$%s$' % code.strip() elif b=='latex_eqnarray': code=code.strip() code='\\\\'.join(x.replace('=','&=&',1) for x in code.split('\\\\')) html='\n\\begin{eqnarray}\n%s\n\\end{eqnarray}\n' % code elif b.startswith('latex_'): key=b[6:] html='\\begin{%s}%s\\end{%s}' % (key,code,key) elif b in extra: if code[:1]=='\n': code=code[1:] if code[-1:]=='\n': code=code[:-1] html = extra[b](code) elif code[:1]=='\n' or code[:-1]=='\n': if code[:1]=='\n': code=code[1:] if code[-1:]=='\n': code=code[:-1] if code.startswith('<') or code.startswith('{{') or code.startswith('http'): html = '\\begin{lstlisting}[keywords={}]\n%s\n\\end{lstlisting}' % code else: html = '\\begin{lstlisting}\n%s\n\\end{lstlisting}' % code else: if code[:1]=='\n': code=code[1:] if code[-1:]=='\n': code=code[:-1] html = '{\\ft %s}' % latex_escape(code) try: text = text+html+parts[i+1] except: text = text + '... WIKI PROCESSING ERROR ...' break text = text.replace(' ~\\cite','~\\cite') return text, title, authors WRAPPER = """ \\documentclass[12pt]{article} \\usepackage{hyperref} \\usepackage{listings} \\usepackage{upquote} \\usepackage{color} \\usepackage{graphicx} \\usepackage{grffile} \\usepackage[utf8x]{inputenc} \\definecolor{lg}{rgb}{0.9,0.9,0.9} \\definecolor{dg}{rgb}{0.3,0.3,0.3} \\def\\ft{\\small\\tt} \\lstset{ basicstyle=\\footnotesize, breaklines=true, basicstyle=\\ttfamily\\color{black}\\footnotesize, keywordstyle=\\bf\\ttfamily, commentstyle=\\it\\ttfamily, stringstyle=\\color{dg}\\it\\ttfamily, numbers=left, numberstyle=\\color{dg}\\tiny, stepnumber=1, numbersep=5pt, backgroundcolor=\\color{lg}, tabsize=4, showspaces=false, showstringspaces=false } \\title{%(title)s} \\author{%(author)s} \\begin{document} \\maketitle \\tableofcontents \\newpage %(body)s \\end{document} """ def markmin2latex(data, image_mapper=lambda x:x, extra={}, wrapper=WRAPPER): body, title, authors = render(data, extra=extra, image_mapper=image_mapper) author = '\n\\and\n'.join(a.replace('\n','\\\\\n\\footnotesize ') for a in authors) return wrapper % dict(title=title, author=author, body=body) if __name__ == '__main__': parser = OptionParser() parser.add_option("-i", "--info", dest="info", help="markmin help") parser.add_option("-t", "--test", dest="test", action="store_true", default=False) parser.add_option("-n", "--no_wrapper", dest="no_wrapper", action="store_true",default=False) parser.add_option("-1", "--one", dest="one",action="store_true", default=False,help="switch section for chapter") parser.add_option("-w", "--wrapper", dest="wrapper", default=False, help="latex file containing header and footer") (options, args) = parser.parse_args() if options.info: import markmin2html markmin2latex(markmin2html.__doc__) elif options.test: doctest.testmod() else: if options.wrapper: fwrapper = open(options.wrapper,'rb') try: wrapper = fwrapper.read() finally: fwrapper.close() elif options.no_wrapper: wrapper = '%(body)s' else: wrapper = WRAPPER for f in args: fargs = open(f,'r') content_data = [] try: content_data.append(fargs.read()) finally: fargs.close() content = '\n'.join(content_data) output= markmin2latex(content,wrapper=wrapper) if options.one: output=output.replace(r'\section*{',r'\chapter*{') output=output.replace(r'\section{',r'\chapter{') output=output.replace(r'subsection{',r'section{') print output
Python
""" Created by Massimo Di Pierro Licese BSD """ import subprocess import os import os.path import re import sys from tempfile import mkstemp, mkdtemp, NamedTemporaryFile from markmin2latex import markmin2latex __all__ = ['markmin2pdf'] def removeall(path): ERROR_STR= """Error removing %(path)s, %(error)s """ def rmgeneric(path, __func__): try: __func__(path) except OSError, (errno, strerror): print ERROR_STR % {'path' : path, 'error': strerror } files=[path] while files: file=files[0] if os.path.isfile(file): f=os.remove rmgeneric(file, os.remove) del files[0] elif os.path.isdir(file): nested = os.listdir(file) if not nested: rmgeneric(file, os.rmdir) del files[0] else: files = [os.path.join(file,x) for x in nested] + files def latex2pdf(latex, pdflatex='pdflatex', passes=3): """ calls pdflatex in a tempfolder Arguments: - pdflatex: path to the pdflatex command. Default is just 'pdflatex'. - passes: defines how often pdflates should be run in the texfile. """ pdflatex=pdflatex passes=passes warnings=[] # setup the envoriment tmpdir = mkdtemp() texfile = open(tmpdir+'/test.tex','wb') texfile.write(latex) texfile.seek(0) texfile.close() texfile = os.path.abspath(texfile.name) # start doing some work for i in range(0, passes): logfd,logname = mkstemp() outfile=os.fdopen(logfd) try: ret = subprocess.call([pdflatex, '-interaction=nonstopmode', '-output-format', 'pdf', '-output-directory', tmpdir, texfile], cwd=os.path.dirname(texfile), stdout=outfile, stderr=subprocess.PIPE) finally: outfile.close() re_errors=re.compile('^\!(.*)$',re.M) re_warnings=re.compile('^LaTeX Warning\:(.*)$',re.M) flog = open(logname) try: loglines = flog.read() finally: flog.close() errors=re_errors.findall(loglines) warnings=re_warnings.findall(loglines) os.unlink(logname) pdffile=texfile.rsplit('.',1)[0]+'.pdf' if os.path.isfile(pdffile): fpdf = open(pdffile, 'rb') try: data = fpdf.read() finally: fpdf.close() else: data = None removeall(tmpdir) return data, warnings, errors def markmin2pdf(text, image_mapper=lambda x: None, extra={}): return latex2pdf(markmin2latex(text,image_mapper=image_mapper, extra=extra)) if __name__ == '__main__': import sys import doctest import markmin2html if sys.argv[1:2]==['-h']: data, warnings, errors = markmin2pdf(markmin2html.__doc__) if errors: print 'ERRORS:'+'\n'.join(errors) print 'WARNGINS:'+'\n'.join(warnings) else: print data elif len(sys.argv)>1: fargv = open(sys.argv[1],'rb') try: data, warnings, errors = markmin2pdf(fargv.read()) finally: fargv.close() if errors: print 'ERRORS:'+'\n'.join(errors) print 'WARNGINS:'+'\n'.join(warnings) else: print data else: doctest.testmod()
Python
# this file exists for backward compatibility __all__ = ['DAL','Field','drivers','gae'] from gluon.dal import DAL, Field, Table, Query, Set, Expression, Row, Rows, drivers, BaseAdapter, SQLField, SQLTable, SQLXorable, SQLQuery, SQLSet, SQLRows, SQLStorage, SQLDB, GQLDB, SQLALL, SQLCustomType, gae
Python
# -*- coding: utf-8 -*- import struct import re try: import cStringIO as StringIO except ImportError: import StringIO from err import Warning, Error, InterfaceError, DataError, \ DatabaseError, OperationalError, IntegrityError, InternalError, \ NotSupportedError, ProgrammingError insert_values = re.compile(r'\svalues\s*(\(.+\))', re.IGNORECASE) class Cursor(object): ''' This is the object you use to interact with the database. ''' def __init__(self, connection): ''' Do not create an instance of a Cursor yourself. Call connections.Connection.cursor(). ''' from weakref import proxy self.connection = proxy(connection) self.description = None self.rownumber = 0 self.rowcount = -1 self.arraysize = 1 self._executed = None self.messages = [] self.errorhandler = connection.errorhandler self._has_next = None self._rows = () def __del__(self): ''' When this gets GC'd close it. ''' self.close() def close(self): ''' Closing a cursor just exhausts all remaining data. ''' if not self.connection: return try: while self.nextset(): pass except: pass self.connection = None def _get_db(self): if not self.connection: self.errorhandler(self, ProgrammingError, "cursor closed") return self.connection def _check_executed(self): if not self._executed: self.errorhandler(self, ProgrammingError, "execute() first") def setinputsizes(self, *args): """Does nothing, required by DB API.""" def setoutputsizes(self, *args): """Does nothing, required by DB API.""" def nextset(self): ''' Get the next query set ''' if self._executed: self.fetchall() del self.messages[:] if not self._has_next: return None connection = self._get_db() connection.next_result() self._do_get_result() return True def execute(self, query, args=None): ''' Execute a query ''' from sys import exc_info conn = self._get_db() charset = conn.charset del self.messages[:] # TODO: make sure that conn.escape is correct if args is not None: query = query % conn.escape(args) if isinstance(query, unicode): query = query.encode(charset) result = 0 try: result = self._query(query) except: exc, value, tb = exc_info() del tb self.messages.append((exc,value)) self.errorhandler(self, exc, value) self._executed = query return result def executemany(self, query, args): ''' Run several data against one query ''' del self.messages[:] conn = self._get_db() if not args: return charset = conn.charset if isinstance(query, unicode): query = query.encode(charset) self.rowcount = sum([ self.execute(query, arg) for arg in args ]) return self.rowcount def callproc(self, procname, args=()): """Execute stored procedure procname with args procname -- string, name of procedure to execute on server args -- Sequence of parameters to use with procedure Returns the original args. Compatibility warning: PEP-249 specifies that any modified parameters must be returned. This is currently impossible as they are only available by storing them in a server variable and then retrieved by a query. Since stored procedures return zero or more result sets, there is no reliable way to get at OUT or INOUT parameters via callproc. The server variables are named @_procname_n, where procname is the parameter above and n is the position of the parameter (from zero). Once all result sets generated by the procedure have been fetched, you can issue a SELECT @_procname_0, ... query using .execute() to get any OUT or INOUT values. Compatibility warning: The act of calling a stored procedure itself creates an empty result set. This appears after any result sets generated by the procedure. This is non-standard behavior with respect to the DB-API. Be sure to use nextset() to advance through all result sets; otherwise you may get disconnected. """ conn = self._get_db() for index, arg in enumerate(args): q = "SET @_%s_%d=%s" % (procname, index, conn.escape(arg)) if isinstance(q, unicode): q = q.encode(conn.charset) self._query(q) self.nextset() q = "CALL %s(%s)" % (procname, ','.join(['@_%s_%d' % (procname, i) for i in range(len(args))])) if isinstance(q, unicode): q = q.encode(conn.charset) self._query(q) self._executed = q return args def fetchone(self): ''' Fetch the next row ''' self._check_executed() if self._rows is None or self.rownumber >= len(self._rows): return None result = self._rows[self.rownumber] self.rownumber += 1 return result def fetchmany(self, size=None): ''' Fetch several rows ''' self._check_executed() end = self.rownumber + (size or self.arraysize) result = self._rows[self.rownumber:end] if self._rows is None: return None self.rownumber = min(end, len(self._rows)) return result def fetchall(self): ''' Fetch all the rows ''' self._check_executed() if self._rows is None: return None if self.rownumber: result = self._rows[self.rownumber:] else: result = self._rows self.rownumber = len(self._rows) return result def scroll(self, value, mode='relative'): self._check_executed() if mode == 'relative': r = self.rownumber + value elif mode == 'absolute': r = value else: self.errorhandler(self, ProgrammingError, "unknown scroll mode %s" % mode) if r < 0 or r >= len(self._rows): self.errorhandler(self, IndexError, "out of range") self.rownumber = r def _query(self, q): conn = self._get_db() self._last_executed = q conn.query(q) self._do_get_result() return self.rowcount def _do_get_result(self): conn = self._get_db() self.rowcount = conn._result.affected_rows self.rownumber = 0 self.description = conn._result.description self.lastrowid = conn._result.insert_id self._rows = conn._result.rows self._has_next = conn._result.has_next conn._result = None def __iter__(self): self._check_executed() result = self.rownumber and self._rows[self.rownumber:] or self._rows return iter(result) Warning = Warning Error = Error InterfaceError = InterfaceError DatabaseError = DatabaseError DataError = DataError OperationalError = OperationalError IntegrityError = IntegrityError InternalError = InternalError ProgrammingError = ProgrammingError NotSupportedError = NotSupportedError
Python
import re import datetime import time from constants import FIELD_TYPE, FLAG from charset import charset_by_id try: set except NameError: try: from sets import BaseSet as set except ImportError: from sets import Set as set ESCAPE_REGEX = re.compile(r"[\0\n\r\032\'\"\\]") ESCAPE_MAP = {'\0': '\\0', '\n': '\\n', '\r': '\\r', '\032': '\\Z', '\'': '\\\'', '"': '\\"', '\\': '\\\\'} def escape_item(val, charset): if type(val) in [tuple, list, set]: return escape_sequence(val, charset) if type(val) is dict: return escape_dict(val, charset) if hasattr(val, "decode") and not isinstance(val, unicode): # deal with py3k bytes val = val.decode(charset) encoder = encoders[type(val)] val = encoder(val) if type(val) is str: return val val = val.encode(charset) return val def escape_dict(val, charset): n = {} for k, v in val.items(): quoted = escape_item(v, charset) n[k] = quoted return n def escape_sequence(val, charset): n = [] for item in val: quoted = escape_item(item, charset) n.append(quoted) return tuple(n) def escape_set(val, charset): val = map(lambda x: escape_item(x, charset), val) return ','.join(val) def escape_bool(value): return str(int(value)) def escape_object(value): return str(value) escape_int = escape_long = escape_object def escape_float(value): return ('%.15g' % value) def escape_string(value): return ("'%s'" % ESCAPE_REGEX.sub( lambda match: ESCAPE_MAP.get(match.group(0)), value)) def escape_unicode(value): return escape_string(value) def escape_None(value): return 'NULL' def escape_timedelta(obj): seconds = int(obj.seconds) % 60 minutes = int(obj.seconds // 60) % 60 hours = int(obj.seconds // 3600) % 24 + int(obj.days) * 24 return escape_string('%02d:%02d:%02d' % (hours, minutes, seconds)) def escape_time(obj): s = "%02d:%02d:%02d" % (int(obj.hour), int(obj.minute), int(obj.second)) if obj.microsecond: s += ".%f" % obj.microsecond return escape_string(s) def escape_datetime(obj): return escape_string(obj.strftime("%Y-%m-%d %H:%M:%S")) def escape_date(obj): return escape_string(obj.strftime("%Y-%m-%d")) def escape_struct_time(obj): return escape_datetime(datetime.datetime(*obj[:6])) def convert_datetime(connection, field, obj): """Returns a DATETIME or TIMESTAMP column value as a datetime object: >>> datetime_or_None('2007-02-25 23:06:20') datetime.datetime(2007, 2, 25, 23, 6, 20) >>> datetime_or_None('2007-02-25T23:06:20') datetime.datetime(2007, 2, 25, 23, 6, 20) Illegal values are returned as None: >>> datetime_or_None('2007-02-31T23:06:20') is None True >>> datetime_or_None('0000-00-00 00:00:00') is None True """ if not isinstance(obj, unicode): obj = obj.decode(connection.charset) if ' ' in obj: sep = ' ' elif 'T' in obj: sep = 'T' else: return convert_date(connection, field, obj) try: ymd, hms = obj.split(sep, 1) return datetime.datetime(*[ int(x) for x in ymd.split('-')+hms.split(':') ]) except ValueError: return convert_date(connection, field, obj) def convert_timedelta(connection, field, obj): """Returns a TIME column as a timedelta object: >>> timedelta_or_None('25:06:17') datetime.timedelta(1, 3977) >>> timedelta_or_None('-25:06:17') datetime.timedelta(-2, 83177) Illegal values are returned as None: >>> timedelta_or_None('random crap') is None True Note that MySQL always returns TIME columns as (+|-)HH:MM:SS, but can accept values as (+|-)DD HH:MM:SS. The latter format will not be parsed correctly by this function. """ from math import modf try: if not isinstance(obj, unicode): obj = obj.decode(connection.charset) hours, minutes, seconds = tuple([int(x) for x in obj.split(':')]) tdelta = datetime.timedelta( hours = int(hours), minutes = int(minutes), seconds = int(seconds), microseconds = int(modf(float(seconds))[0]*1000000), ) return tdelta except ValueError: return None def convert_time(connection, field, obj): """Returns a TIME column as a time object: >>> time_or_None('15:06:17') datetime.time(15, 6, 17) Illegal values are returned as None: >>> time_or_None('-25:06:17') is None True >>> time_or_None('random crap') is None True Note that MySQL always returns TIME columns as (+|-)HH:MM:SS, but can accept values as (+|-)DD HH:MM:SS. The latter format will not be parsed correctly by this function. Also note that MySQL's TIME column corresponds more closely to Python's timedelta and not time. However if you want TIME columns to be treated as time-of-day and not a time offset, then you can use set this function as the converter for FIELD_TYPE.TIME. """ from math import modf try: hour, minute, second = obj.split(':') return datetime.time(hour=int(hour), minute=int(minute), second=int(second), microsecond=int(modf(float(second))[0]*1000000)) except ValueError: return None def convert_date(connection, field, obj): """Returns a DATE column as a date object: >>> date_or_None('2007-02-26') datetime.date(2007, 2, 26) Illegal values are returned as None: >>> date_or_None('2007-02-31') is None True >>> date_or_None('0000-00-00') is None True """ try: if not isinstance(obj, unicode): obj = obj.decode(connection.charset) return datetime.date(*[ int(x) for x in obj.split('-', 2) ]) except ValueError: return None def convert_mysql_timestamp(connection, field, timestamp): """Convert a MySQL TIMESTAMP to a Timestamp object. MySQL >= 4.1 returns TIMESTAMP in the same format as DATETIME: >>> mysql_timestamp_converter('2007-02-25 22:32:17') datetime.datetime(2007, 2, 25, 22, 32, 17) MySQL < 4.1 uses a big string of numbers: >>> mysql_timestamp_converter('20070225223217') datetime.datetime(2007, 2, 25, 22, 32, 17) Illegal values are returned as None: >>> mysql_timestamp_converter('2007-02-31 22:32:17') is None True >>> mysql_timestamp_converter('00000000000000') is None True """ if not isinstance(timestamp, unicode): timestamp = timestamp.decode(connection.charset) if timestamp[4] == '-': return convert_datetime(connection, field, timestamp) timestamp += "0"*(14-len(timestamp)) # padding year, month, day, hour, minute, second = \ int(timestamp[:4]), int(timestamp[4:6]), int(timestamp[6:8]), \ int(timestamp[8:10]), int(timestamp[10:12]), int(timestamp[12:14]) try: return datetime.datetime(year, month, day, hour, minute, second) except ValueError: return None def convert_set(s): return set(s.split(",")) def convert_bit(connection, field, b): #b = "\x00" * (8 - len(b)) + b # pad w/ zeroes #return struct.unpack(">Q", b)[0] # # the snippet above is right, but MySQLdb doesn't process bits, # so we shouldn't either return b def convert_characters(connection, field, data): field_charset = charset_by_id(field.charsetnr).name if field.flags & FLAG.SET: return convert_set(data.decode(field_charset)) if field.flags & FLAG.BINARY: return data if connection.use_unicode: data = data.decode(field_charset) elif connection.charset != field_charset: data = data.decode(field_charset) data = data.encode(connection.charset) else: data = data.decode(connection.charset) return data def convert_int(connection, field, data): return int(data) def convert_long(connection, field, data): return long(data) def convert_float(connection, field, data): return float(data) encoders = { bool: escape_bool, int: escape_int, long: escape_long, float: escape_float, str: escape_string, unicode: escape_unicode, tuple: escape_sequence, list:escape_sequence, set:escape_sequence, dict:escape_dict, type(None):escape_None, datetime.date: escape_date, datetime.datetime : escape_datetime, datetime.timedelta : escape_timedelta, datetime.time : escape_time, time.struct_time : escape_struct_time, } decoders = { FIELD_TYPE.BIT: convert_bit, FIELD_TYPE.TINY: convert_int, FIELD_TYPE.SHORT: convert_int, FIELD_TYPE.LONG: convert_long, FIELD_TYPE.FLOAT: convert_float, FIELD_TYPE.DOUBLE: convert_float, FIELD_TYPE.DECIMAL: convert_float, FIELD_TYPE.NEWDECIMAL: convert_float, FIELD_TYPE.LONGLONG: convert_long, FIELD_TYPE.INT24: convert_int, FIELD_TYPE.YEAR: convert_int, FIELD_TYPE.TIMESTAMP: convert_mysql_timestamp, FIELD_TYPE.DATETIME: convert_datetime, FIELD_TYPE.TIME: convert_timedelta, FIELD_TYPE.DATE: convert_date, FIELD_TYPE.SET: convert_set, FIELD_TYPE.BLOB: convert_characters, FIELD_TYPE.TINY_BLOB: convert_characters, FIELD_TYPE.MEDIUM_BLOB: convert_characters, FIELD_TYPE.LONG_BLOB: convert_characters, FIELD_TYPE.STRING: convert_characters, FIELD_TYPE.VAR_STRING: convert_characters, FIELD_TYPE.VARCHAR: convert_characters, #FIELD_TYPE.BLOB: str, #FIELD_TYPE.STRING: str, #FIELD_TYPE.VAR_STRING: str, #FIELD_TYPE.VARCHAR: str } conversions = decoders # for MySQLdb compatibility try: # python version > 2.3 from decimal import Decimal def convert_decimal(connection, field, data): return Decimal(data) decoders[FIELD_TYPE.DECIMAL] = convert_decimal decoders[FIELD_TYPE.NEWDECIMAL] = convert_decimal def escape_decimal(obj): return unicode(obj) encoders[Decimal] = escape_decimal except ImportError: pass
Python
from time import localtime from datetime import date, datetime, time, timedelta Date = date Time = time TimeDelta = timedelta Timestamp = datetime def DateFromTicks(ticks): return date(*localtime(ticks)[:3]) def TimeFromTicks(ticks): return time(*localtime(ticks)[3:6]) def TimestampFromTicks(ticks): return datetime(*localtime(ticks)[:6])
Python
import struct try: Exception, Warning except ImportError: try: from exceptions import Exception, Warning except ImportError: import sys e = sys.modules['exceptions'] Exception = e.Exception Warning = e.Warning from constants import ER class MySQLError(Exception): """Exception related to operation with MySQL.""" class Warning(Warning, MySQLError): """Exception raised for important warnings like data truncations while inserting, etc.""" class Error(MySQLError): """Exception that is the base class of all other error exceptions (not Warning).""" class InterfaceError(Error): """Exception raised for errors that are related to the database interface rather than the database itself.""" class DatabaseError(Error): """Exception raised for errors that are related to the database.""" class DataError(DatabaseError): """Exception raised for errors that are due to problems with the processed data like division by zero, numeric value out of range, etc.""" class OperationalError(DatabaseError): """Exception raised for errors that are related to the database's operation and not necessarily under the control of the programmer, e.g. an unexpected disconnect occurs, the data source name is not found, a transaction could not be processed, a memory allocation error occurred during processing, etc.""" class IntegrityError(DatabaseError): """Exception raised when the relational integrity of the database is affected, e.g. a foreign key check fails, duplicate key, etc.""" class InternalError(DatabaseError): """Exception raised when the database encounters an internal error, e.g. the cursor is not valid anymore, the transaction is out of sync, etc.""" class ProgrammingError(DatabaseError): """Exception raised for programming errors, e.g. table not found or already exists, syntax error in the SQL statement, wrong number of parameters specified, etc.""" class NotSupportedError(DatabaseError): """Exception raised in case a method or database API was used which is not supported by the database, e.g. requesting a .rollback() on a connection that does not support transaction or has transactions turned off.""" error_map = {} def _map_error(exc, *errors): for error in errors: error_map[error] = exc _map_error(ProgrammingError, ER.DB_CREATE_EXISTS, ER.SYNTAX_ERROR, ER.PARSE_ERROR, ER.NO_SUCH_TABLE, ER.WRONG_DB_NAME, ER.WRONG_TABLE_NAME, ER.FIELD_SPECIFIED_TWICE, ER.INVALID_GROUP_FUNC_USE, ER.UNSUPPORTED_EXTENSION, ER.TABLE_MUST_HAVE_COLUMNS, ER.CANT_DO_THIS_DURING_AN_TRANSACTION) _map_error(DataError, ER.WARN_DATA_TRUNCATED, ER.WARN_NULL_TO_NOTNULL, ER.WARN_DATA_OUT_OF_RANGE, ER.NO_DEFAULT, ER.PRIMARY_CANT_HAVE_NULL, ER.DATA_TOO_LONG, ER.DATETIME_FUNCTION_OVERFLOW) _map_error(IntegrityError, ER.DUP_ENTRY, ER.NO_REFERENCED_ROW, ER.NO_REFERENCED_ROW_2, ER.ROW_IS_REFERENCED, ER.ROW_IS_REFERENCED_2, ER.CANNOT_ADD_FOREIGN) _map_error(NotSupportedError, ER.WARNING_NOT_COMPLETE_ROLLBACK, ER.NOT_SUPPORTED_YET, ER.FEATURE_DISABLED, ER.UNKNOWN_STORAGE_ENGINE) del _map_error, ER def _get_error_info(data): errno = struct.unpack('<h', data[1:3])[0] if data[3] == "#": # version 4.1 sqlstate = data[4:9].decode("utf8") errorvalue = data[9:].decode("utf8") return (errno, sqlstate, errorvalue) else: # version 4.0 return (errno, None, data[3:].decode("utf8")) def _check_mysql_exception(errinfo): errno, sqlstate, errorvalue = errinfo errorclass = error_map.get(errno, None) if errorclass: raise errorclass, (errno,errorvalue) # couldn't find the right error number raise InternalError, (errno, errorvalue) def raise_mysql_exception(data): errinfo = _get_error_info(data) _check_mysql_exception(errinfo)
Python
import struct def byte2int(b): if isinstance(b, int): return b else: return struct.unpack("!B", b)[0] def int2byte(i): return struct.pack("!B", i) def join_bytes(bs): if len(bs) == 0: return "" else: rv = bs[0] for b in bs[1:]: rv += b return rv
Python
MBLENGTH = { 8:1, 33:3, 88:2, 91:2 } class Charset: def __init__(self, id, name, collation, is_default): self.id, self.name, self.collation = id, name, collation self.is_default = is_default == 'Yes' class Charsets: def __init__(self): self._by_id = {} def add(self, c): self._by_id[c.id] = c def by_id(self, id): return self._by_id[id] def by_name(self, name): for c in self._by_id.values(): if c.name == name and c.is_default: return c _charsets = Charsets() """ Generated with: mysql -N -s -e "select id, character_set_name, collation_name, is_default from information_schema.collations order by id;" | python -c "import sys for l in sys.stdin.readlines(): id, name, collation, is_default = l.split(chr(9)) print '_charsets.add(Charset(%s, \'%s\', \'%s\', \'%s\'))' \ % (id, name, collation, is_default.strip()) " """ _charsets.add(Charset(1, 'big5', 'big5_chinese_ci', 'Yes')) _charsets.add(Charset(2, 'latin2', 'latin2_czech_cs', '')) _charsets.add(Charset(3, 'dec8', 'dec8_swedish_ci', 'Yes')) _charsets.add(Charset(4, 'cp850', 'cp850_general_ci', 'Yes')) _charsets.add(Charset(5, 'latin1', 'latin1_german1_ci', '')) _charsets.add(Charset(6, 'hp8', 'hp8_english_ci', 'Yes')) _charsets.add(Charset(7, 'koi8r', 'koi8r_general_ci', 'Yes')) _charsets.add(Charset(8, 'latin1', 'latin1_swedish_ci', 'Yes')) _charsets.add(Charset(9, 'latin2', 'latin2_general_ci', 'Yes')) _charsets.add(Charset(10, 'swe7', 'swe7_swedish_ci', 'Yes')) _charsets.add(Charset(11, 'ascii', 'ascii_general_ci', 'Yes')) _charsets.add(Charset(12, 'ujis', 'ujis_japanese_ci', 'Yes')) _charsets.add(Charset(13, 'sjis', 'sjis_japanese_ci', 'Yes')) _charsets.add(Charset(14, 'cp1251', 'cp1251_bulgarian_ci', '')) _charsets.add(Charset(15, 'latin1', 'latin1_danish_ci', '')) _charsets.add(Charset(16, 'hebrew', 'hebrew_general_ci', 'Yes')) _charsets.add(Charset(18, 'tis620', 'tis620_thai_ci', 'Yes')) _charsets.add(Charset(19, 'euckr', 'euckr_korean_ci', 'Yes')) _charsets.add(Charset(20, 'latin7', 'latin7_estonian_cs', '')) _charsets.add(Charset(21, 'latin2', 'latin2_hungarian_ci', '')) _charsets.add(Charset(22, 'koi8u', 'koi8u_general_ci', 'Yes')) _charsets.add(Charset(23, 'cp1251', 'cp1251_ukrainian_ci', '')) _charsets.add(Charset(24, 'gb2312', 'gb2312_chinese_ci', 'Yes')) _charsets.add(Charset(25, 'greek', 'greek_general_ci', 'Yes')) _charsets.add(Charset(26, 'cp1250', 'cp1250_general_ci', 'Yes')) _charsets.add(Charset(27, 'latin2', 'latin2_croatian_ci', '')) _charsets.add(Charset(28, 'gbk', 'gbk_chinese_ci', 'Yes')) _charsets.add(Charset(29, 'cp1257', 'cp1257_lithuanian_ci', '')) _charsets.add(Charset(30, 'latin5', 'latin5_turkish_ci', 'Yes')) _charsets.add(Charset(31, 'latin1', 'latin1_german2_ci', '')) _charsets.add(Charset(32, 'armscii8', 'armscii8_general_ci', 'Yes')) _charsets.add(Charset(33, 'utf8', 'utf8_general_ci', 'Yes')) _charsets.add(Charset(34, 'cp1250', 'cp1250_czech_cs', '')) _charsets.add(Charset(35, 'ucs2', 'ucs2_general_ci', 'Yes')) _charsets.add(Charset(36, 'cp866', 'cp866_general_ci', 'Yes')) _charsets.add(Charset(37, 'keybcs2', 'keybcs2_general_ci', 'Yes')) _charsets.add(Charset(38, 'macce', 'macce_general_ci', 'Yes')) _charsets.add(Charset(39, 'macroman', 'macroman_general_ci', 'Yes')) _charsets.add(Charset(40, 'cp852', 'cp852_general_ci', 'Yes')) _charsets.add(Charset(41, 'latin7', 'latin7_general_ci', 'Yes')) _charsets.add(Charset(42, 'latin7', 'latin7_general_cs', '')) _charsets.add(Charset(43, 'macce', 'macce_bin', '')) _charsets.add(Charset(44, 'cp1250', 'cp1250_croatian_ci', '')) _charsets.add(Charset(47, 'latin1', 'latin1_bin', '')) _charsets.add(Charset(48, 'latin1', 'latin1_general_ci', '')) _charsets.add(Charset(49, 'latin1', 'latin1_general_cs', '')) _charsets.add(Charset(50, 'cp1251', 'cp1251_bin', '')) _charsets.add(Charset(51, 'cp1251', 'cp1251_general_ci', 'Yes')) _charsets.add(Charset(52, 'cp1251', 'cp1251_general_cs', '')) _charsets.add(Charset(53, 'macroman', 'macroman_bin', '')) _charsets.add(Charset(57, 'cp1256', 'cp1256_general_ci', 'Yes')) _charsets.add(Charset(58, 'cp1257', 'cp1257_bin', '')) _charsets.add(Charset(59, 'cp1257', 'cp1257_general_ci', 'Yes')) _charsets.add(Charset(63, 'binary', 'binary', 'Yes')) _charsets.add(Charset(64, 'armscii8', 'armscii8_bin', '')) _charsets.add(Charset(65, 'ascii', 'ascii_bin', '')) _charsets.add(Charset(66, 'cp1250', 'cp1250_bin', '')) _charsets.add(Charset(67, 'cp1256', 'cp1256_bin', '')) _charsets.add(Charset(68, 'cp866', 'cp866_bin', '')) _charsets.add(Charset(69, 'dec8', 'dec8_bin', '')) _charsets.add(Charset(70, 'greek', 'greek_bin', '')) _charsets.add(Charset(71, 'hebrew', 'hebrew_bin', '')) _charsets.add(Charset(72, 'hp8', 'hp8_bin', '')) _charsets.add(Charset(73, 'keybcs2', 'keybcs2_bin', '')) _charsets.add(Charset(74, 'koi8r', 'koi8r_bin', '')) _charsets.add(Charset(75, 'koi8u', 'koi8u_bin', '')) _charsets.add(Charset(77, 'latin2', 'latin2_bin', '')) _charsets.add(Charset(78, 'latin5', 'latin5_bin', '')) _charsets.add(Charset(79, 'latin7', 'latin7_bin', '')) _charsets.add(Charset(80, 'cp850', 'cp850_bin', '')) _charsets.add(Charset(81, 'cp852', 'cp852_bin', '')) _charsets.add(Charset(82, 'swe7', 'swe7_bin', '')) _charsets.add(Charset(83, 'utf8', 'utf8_bin', '')) _charsets.add(Charset(84, 'big5', 'big5_bin', '')) _charsets.add(Charset(85, 'euckr', 'euckr_bin', '')) _charsets.add(Charset(86, 'gb2312', 'gb2312_bin', '')) _charsets.add(Charset(87, 'gbk', 'gbk_bin', '')) _charsets.add(Charset(88, 'sjis', 'sjis_bin', '')) _charsets.add(Charset(89, 'tis620', 'tis620_bin', '')) _charsets.add(Charset(90, 'ucs2', 'ucs2_bin', '')) _charsets.add(Charset(91, 'ujis', 'ujis_bin', '')) _charsets.add(Charset(92, 'geostd8', 'geostd8_general_ci', 'Yes')) _charsets.add(Charset(93, 'geostd8', 'geostd8_bin', '')) _charsets.add(Charset(94, 'latin1', 'latin1_spanish_ci', '')) _charsets.add(Charset(95, 'cp932', 'cp932_japanese_ci', 'Yes')) _charsets.add(Charset(96, 'cp932', 'cp932_bin', '')) _charsets.add(Charset(97, 'eucjpms', 'eucjpms_japanese_ci', 'Yes')) _charsets.add(Charset(98, 'eucjpms', 'eucjpms_bin', '')) _charsets.add(Charset(99, 'cp1250', 'cp1250_polish_ci', '')) _charsets.add(Charset(128, 'ucs2', 'ucs2_unicode_ci', '')) _charsets.add(Charset(129, 'ucs2', 'ucs2_icelandic_ci', '')) _charsets.add(Charset(130, 'ucs2', 'ucs2_latvian_ci', '')) _charsets.add(Charset(131, 'ucs2', 'ucs2_romanian_ci', '')) _charsets.add(Charset(132, 'ucs2', 'ucs2_slovenian_ci', '')) _charsets.add(Charset(133, 'ucs2', 'ucs2_polish_ci', '')) _charsets.add(Charset(134, 'ucs2', 'ucs2_estonian_ci', '')) _charsets.add(Charset(135, 'ucs2', 'ucs2_spanish_ci', '')) _charsets.add(Charset(136, 'ucs2', 'ucs2_swedish_ci', '')) _charsets.add(Charset(137, 'ucs2', 'ucs2_turkish_ci', '')) _charsets.add(Charset(138, 'ucs2', 'ucs2_czech_ci', '')) _charsets.add(Charset(139, 'ucs2', 'ucs2_danish_ci', '')) _charsets.add(Charset(140, 'ucs2', 'ucs2_lithuanian_ci', '')) _charsets.add(Charset(141, 'ucs2', 'ucs2_slovak_ci', '')) _charsets.add(Charset(142, 'ucs2', 'ucs2_spanish2_ci', '')) _charsets.add(Charset(143, 'ucs2', 'ucs2_roman_ci', '')) _charsets.add(Charset(144, 'ucs2', 'ucs2_persian_ci', '')) _charsets.add(Charset(145, 'ucs2', 'ucs2_esperanto_ci', '')) _charsets.add(Charset(146, 'ucs2', 'ucs2_hungarian_ci', '')) _charsets.add(Charset(192, 'utf8', 'utf8_unicode_ci', '')) _charsets.add(Charset(193, 'utf8', 'utf8_icelandic_ci', '')) _charsets.add(Charset(194, 'utf8', 'utf8_latvian_ci', '')) _charsets.add(Charset(195, 'utf8', 'utf8_romanian_ci', '')) _charsets.add(Charset(196, 'utf8', 'utf8_slovenian_ci', '')) _charsets.add(Charset(197, 'utf8', 'utf8_polish_ci', '')) _charsets.add(Charset(198, 'utf8', 'utf8_estonian_ci', '')) _charsets.add(Charset(199, 'utf8', 'utf8_spanish_ci', '')) _charsets.add(Charset(200, 'utf8', 'utf8_swedish_ci', '')) _charsets.add(Charset(201, 'utf8', 'utf8_turkish_ci', '')) _charsets.add(Charset(202, 'utf8', 'utf8_czech_ci', '')) _charsets.add(Charset(203, 'utf8', 'utf8_danish_ci', '')) _charsets.add(Charset(204, 'utf8', 'utf8_lithuanian_ci', '')) _charsets.add(Charset(205, 'utf8', 'utf8_slovak_ci', '')) _charsets.add(Charset(206, 'utf8', 'utf8_spanish2_ci', '')) _charsets.add(Charset(207, 'utf8', 'utf8_roman_ci', '')) _charsets.add(Charset(208, 'utf8', 'utf8_persian_ci', '')) _charsets.add(Charset(209, 'utf8', 'utf8_esperanto_ci', '')) _charsets.add(Charset(210, 'utf8', 'utf8_hungarian_ci', '')) def charset_by_name(name): return _charsets.by_name(name) def charset_by_id(id): return _charsets.by_id(id)
Python
import pymysql import unittest class PyMySQLTestCase(unittest.TestCase): databases = [ {"host":"localhost","user":"root", "passwd":"","db":"test_pymysql", "use_unicode": True}, {"host":"localhost","user":"root","passwd":"","db":"test_pymysql2"}] def setUp(self): self.connections = [] for params in self.databases: self.connections.append(pymysql.connect(**params)) def tearDown(self): for connection in self.connections: connection.close()
Python
from pymysql.tests.test_issues import * from pymysql.tests.test_example import * from pymysql.tests.test_basic import * if __name__ == "__main__": import unittest unittest.main()
Python
''' PyMySQL: A pure-Python drop-in replacement for MySQLdb. Copyright (c) 2010 PyMySQL contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' VERSION = (0, 4, None) from constants import FIELD_TYPE from converters import escape_dict, escape_sequence, escape_string from err import Warning, Error, InterfaceError, DataError, \ DatabaseError, OperationalError, IntegrityError, InternalError, \ NotSupportedError, ProgrammingError from times import Date, Time, Timestamp, \ DateFromTicks, TimeFromTicks, TimestampFromTicks import sys try: frozenset except NameError: from sets import ImmutableSet as frozenset try: from sets import BaseSet as set except ImportError: from sets import Set as set threadsafety = 1 apilevel = "2.0" paramstyle = "format" class DBAPISet(frozenset): def __ne__(self, other): if isinstance(other, set): return super(DBAPISet, self).__ne__(self, other) else: return other not in self def __eq__(self, other): if isinstance(other, frozenset): return frozenset.__eq__(self, other) else: return other in self def __hash__(self): return frozenset.__hash__(self) STRING = DBAPISet([FIELD_TYPE.ENUM, FIELD_TYPE.STRING, FIELD_TYPE.VAR_STRING]) BINARY = DBAPISet([FIELD_TYPE.BLOB, FIELD_TYPE.LONG_BLOB, FIELD_TYPE.MEDIUM_BLOB, FIELD_TYPE.TINY_BLOB]) NUMBER = DBAPISet([FIELD_TYPE.DECIMAL, FIELD_TYPE.DOUBLE, FIELD_TYPE.FLOAT, FIELD_TYPE.INT24, FIELD_TYPE.LONG, FIELD_TYPE.LONGLONG, FIELD_TYPE.TINY, FIELD_TYPE.YEAR]) DATE = DBAPISet([FIELD_TYPE.DATE, FIELD_TYPE.NEWDATE]) TIME = DBAPISet([FIELD_TYPE.TIME]) TIMESTAMP = DBAPISet([FIELD_TYPE.TIMESTAMP, FIELD_TYPE.DATETIME]) DATETIME = TIMESTAMP ROWID = DBAPISet() def Binary(x): """Return x as a binary type.""" return str(x) def Connect(*args, **kwargs): """ Connect to the database; see connections.Connection.__init__() for more information. """ from connections import Connection return Connection(*args, **kwargs) def get_client_info(): # for MySQLdb compatibility return '%s.%s.%s' % VERSION connect = Connection = Connect # we include a doctored version_info here for MySQLdb compatibility version_info = (1,2,2,"final",0) NULL = "NULL" __version__ = get_client_info() def thread_safe(): return True # match MySQLdb.thread_safe() def install_as_MySQLdb(): """ After this function is called, any application that imports MySQLdb or _mysql will unwittingly actually use """ sys.modules["MySQLdb"] = sys.modules["_mysql"] = sys.modules["pymysql"] __all__ = [ 'BINARY', 'Binary', 'Connect', 'Connection', 'DATE', 'Date', 'Time', 'Timestamp', 'DateFromTicks', 'TimeFromTicks', 'TimestampFromTicks', 'DataError', 'DatabaseError', 'Error', 'FIELD_TYPE', 'IntegrityError', 'InterfaceError', 'InternalError', 'MySQLError', 'NULL', 'NUMBER', 'NotSupportedError', 'DBAPISet', 'OperationalError', 'ProgrammingError', 'ROWID', 'STRING', 'TIME', 'TIMESTAMP', 'Warning', 'apilevel', 'connect', 'connections', 'constants', 'converters', 'cursors', 'debug', 'escape', 'escape_dict', 'escape_sequence', 'escape_string', 'get_client_info', 'paramstyle', 'string_literal', 'threadsafety', 'version_info', "install_as_MySQLdb", "NULL","__version__", ]
Python
# Python implementation of the MySQL client-server protocol # http://forge.mysql.com/wiki/MySQL_Internals_ClientServer_Protocol try: import hashlib sha_new = lambda *args, **kwargs: hashlib.new("sha1", *args, **kwargs) except ImportError: import sha sha_new = sha.new import socket try: import ssl SSL_ENABLED = True except ImportError: SSL_ENABLED = False import struct import sys import os import ConfigParser try: import cStringIO as StringIO except ImportError: import StringIO from charset import MBLENGTH, charset_by_name, charset_by_id from cursors import Cursor from constants import FIELD_TYPE, FLAG from constants import SERVER_STATUS from constants.CLIENT import * from constants.COMMAND import * from util import join_bytes, byte2int, int2byte from converters import escape_item, encoders, decoders from err import raise_mysql_exception, Warning, Error, \ InterfaceError, DataError, DatabaseError, OperationalError, \ IntegrityError, InternalError, NotSupportedError, ProgrammingError DEBUG = False NULL_COLUMN = 251 UNSIGNED_CHAR_COLUMN = 251 UNSIGNED_SHORT_COLUMN = 252 UNSIGNED_INT24_COLUMN = 253 UNSIGNED_INT64_COLUMN = 254 UNSIGNED_CHAR_LENGTH = 1 UNSIGNED_SHORT_LENGTH = 2 UNSIGNED_INT24_LENGTH = 3 UNSIGNED_INT64_LENGTH = 8 DEFAULT_CHARSET = 'latin1' MAX_PACKET_LENGTH = 256*256*256-1 def dump_packet(data): def is_ascii(data): if byte2int(data) >= 65 and byte2int(data) <= 122: #data.isalnum(): return data return '.' print "packet length %d" % len(data) print "method call[1]: %s" % sys._getframe(1).f_code.co_name print "method call[2]: %s" % sys._getframe(2).f_code.co_name print "method call[3]: %s" % sys._getframe(3).f_code.co_name print "method call[4]: %s" % sys._getframe(4).f_code.co_name print "method call[5]: %s" % sys._getframe(5).f_code.co_name print "-" * 88 dump_data = [data[i:i+16] for i in xrange(len(data)) if i%16 == 0] for d in dump_data: print ' '.join(map(lambda x:"%02X" % byte2int(x), d)) + \ ' ' * (16 - len(d)) + ' ' * 2 + \ ' '.join(map(lambda x:"%s" % is_ascii(x), d)) print "-" * 88 print "" def _scramble(password, message): if password == None or len(password) == 0: return int2byte(0) if DEBUG: print 'password=' + password stage1 = sha_new(password).digest() stage2 = sha_new(stage1).digest() s = sha_new() s.update(message) s.update(stage2) result = s.digest() return _my_crypt(result, stage1) def _my_crypt(message1, message2): length = len(message1) result = struct.pack('B', length) for i in xrange(length): x = (struct.unpack('B', message1[i:i+1])[0] ^ \ struct.unpack('B', message2[i:i+1])[0]) result += struct.pack('B', x) return result # old_passwords support ported from libmysql/password.c SCRAMBLE_LENGTH_323 = 8 class RandStruct_323(object): def __init__(self, seed1, seed2): self.max_value = 0x3FFFFFFFL self.seed1 = seed1 % self.max_value self.seed2 = seed2 % self.max_value def my_rnd(self): self.seed1 = (self.seed1 * 3L + self.seed2) % self.max_value self.seed2 = (self.seed1 + self.seed2 + 33L) % self.max_value return float(self.seed1) / float(self.max_value) def _scramble_323(password, message): hash_pass = _hash_password_323(password) hash_message = _hash_password_323(message[:SCRAMBLE_LENGTH_323]) hash_pass_n = struct.unpack(">LL", hash_pass) hash_message_n = struct.unpack(">LL", hash_message) rand_st = RandStruct_323(hash_pass_n[0] ^ hash_message_n[0], hash_pass_n[1] ^ hash_message_n[1]) outbuf = StringIO.StringIO() for _ in xrange(min(SCRAMBLE_LENGTH_323, len(message))): outbuf.write(int2byte(int(rand_st.my_rnd() * 31) + 64)) extra = int2byte(int(rand_st.my_rnd() * 31)) out = outbuf.getvalue() outbuf = StringIO.StringIO() for c in out: outbuf.write(int2byte(byte2int(c) ^ byte2int(extra))) return outbuf.getvalue() def _hash_password_323(password): nr = 1345345333L add = 7L nr2 = 0x12345671L for c in [byte2int(x) for x in password if x not in (' ', '\t')]: nr^= (((nr & 63)+add)*c)+ (nr << 8) & 0xFFFFFFFF nr2= (nr2 + ((nr2 << 8) ^ nr)) & 0xFFFFFFFF add= (add + c) & 0xFFFFFFFF r1 = nr & ((1L << 31) - 1L) # kill sign bits r2 = nr2 & ((1L << 31) - 1L) # pack return struct.pack(">LL", r1, r2) def pack_int24(n): return struct.pack('BBB', n&0xFF, (n>>8)&0xFF, (n>>16)&0xFF) def unpack_uint16(n): return struct.unpack('<H', n[0:2])[0] # TODO: stop using bit-shifting in these functions... # TODO: rename to "uint" to make it clear they're unsigned... def unpack_int24(n): return struct.unpack('B',n[0])[0] + (struct.unpack('B', n[1])[0] << 8) +\ (struct.unpack('B',n[2])[0] << 16) def unpack_int32(n): return struct.unpack('B',n[0])[0] + (struct.unpack('B', n[1])[0] << 8) +\ (struct.unpack('B',n[2])[0] << 16) + (struct.unpack('B', n[3])[0] << 24) def unpack_int64(n): return struct.unpack('B',n[0])[0] + (struct.unpack('B', n[1])[0]<<8) +\ (struct.unpack('B',n[2])[0] << 16) + (struct.unpack('B',n[3])[0]<<24)+\ (struct.unpack('B',n[4])[0] << 32) + (struct.unpack('B',n[5])[0]<<40)+\ (struct.unpack('B',n[6])[0] << 48) + (struct.unpack('B',n[7])[0]<<56) def defaulterrorhandler(connection, cursor, errorclass, errorvalue): err = errorclass, errorvalue if DEBUG: raise if cursor: cursor.messages.append(err) else: connection.messages.append(err) del cursor del connection if not issubclass(errorclass, Error): raise Error(errorclass, errorvalue) else: raise errorclass, errorvalue class MysqlPacket(object): """Representation of a MySQL response packet. Reads in the packet from the network socket, removes packet header and provides an interface for reading/parsing the packet results.""" def __init__(self, socket): self.__position = 0 self.__recv_packet(socket) del socket def __recv_packet(self, socket): """Parse the packet header and read entire packet payload into buffer.""" packet_header = socket.recv(4) while len(packet_header) < 4: d = socket.recv(4 - len(packet_header)) if len(d) == 0: raise OperationalError(2013, "Lost connection to MySQL server during query") packet_header += d if DEBUG: dump_packet(packet_header) packet_length_bin = packet_header[:3] self.__packet_number = byte2int(packet_header[3]) # TODO: check packet_num is correct (+1 from last packet) bin_length = packet_length_bin + int2byte(0) # pad little-endian number bytes_to_read = struct.unpack('<I', bin_length)[0] payload_buff = [] # this is faster than cStringIO while bytes_to_read > 0: recv_data = socket.recv(bytes_to_read) if len(recv_data) == 0: raise OperationalError(2013, "Lost connection to MySQL server during query") if DEBUG: dump_packet(recv_data) payload_buff.append(recv_data) bytes_to_read -= len(recv_data) self.__data = join_bytes(payload_buff) def packet_number(self): return self.__packet_number def get_all_data(self): return self.__data def read(self, size): """Read the first 'size' bytes in packet and advance cursor past them.""" result = self.peek(size) self.advance(size) return result def read_all(self): """Read all remaining data in the packet. (Subsequent read() or peek() will return errors.) """ result = self.__data[self.__position:] self.__position = None # ensure no subsequent read() or peek() return result def advance(self, length): """Advance the cursor in data buffer 'length' bytes.""" new_position = self.__position + length if new_position < 0 or new_position > len(self.__data): raise Exception('Invalid advance amount (%s) for cursor. ' 'Position=%s' % (length, new_position)) self.__position = new_position def rewind(self, position=0): """Set the position of the data buffer cursor to 'position'.""" if position < 0 or position > len(self.__data): raise Exception("Invalid position to rewind cursor to: %s." % position) self.__position = position def peek(self, size): """Look at the first 'size' bytes in packet without moving cursor.""" result = self.__data[self.__position:(self.__position+size)] if len(result) != size: error = ('Result length not requested length:\n' 'Expected=%s. Actual=%s. Position: %s. Data Length: %s' % (size, len(result), self.__position, len(self.__data))) if DEBUG: print error self.dump() raise AssertionError(error) return result def get_bytes(self, position, length=1): """Get 'length' bytes starting at 'position'. Position is start of payload (first four packet header bytes are not included) starting at index '0'. No error checking is done. If requesting outside end of buffer an empty string (or string shorter than 'length') may be returned! """ return self.__data[position:(position+length)] def read_length_coded_binary(self): """Read a 'Length Coded Binary' number from the data buffer. Length coded numbers can be anywhere from 1 to 9 bytes depending on the value of the first byte. """ c = byte2int(self.read(1)) if c == NULL_COLUMN: return None if c < UNSIGNED_CHAR_COLUMN: return c elif c == UNSIGNED_SHORT_COLUMN: return unpack_uint16(self.read(UNSIGNED_SHORT_LENGTH)) elif c == UNSIGNED_INT24_COLUMN: return unpack_int24(self.read(UNSIGNED_INT24_LENGTH)) elif c == UNSIGNED_INT64_COLUMN: # TODO: what was 'longlong'? confirm it wasn't used? return unpack_int64(self.read(UNSIGNED_INT64_LENGTH)) def read_length_coded_string(self): """Read a 'Length Coded String' from the data buffer. A 'Length Coded String' consists first of a length coded (unsigned, positive) integer represented in 1-9 bytes followed by that many bytes of binary data. (For example "cat" would be "3cat".) """ length = self.read_length_coded_binary() if length is None: return None return self.read(length) def is_ok_packet(self): return byte2int(self.get_bytes(0)) == 0 def is_eof_packet(self): return byte2int(self.get_bytes(0)) == 254 # 'fe' def is_resultset_packet(self): field_count = byte2int(self.get_bytes(0)) return field_count >= 1 and field_count <= 250 def is_error_packet(self): return byte2int(self.get_bytes(0)) == 255 def check_error(self): if self.is_error_packet(): self.rewind() self.advance(1) # field_count == error (we already know that) errno = unpack_uint16(self.read(2)) if DEBUG: print "errno = %d" % errno raise_mysql_exception(self.__data) def dump(self): dump_packet(self.__data) class FieldDescriptorPacket(MysqlPacket): """A MysqlPacket that represents a specific column's metadata in the result. Parsing is automatically done and the results are exported via public attributes on the class such as: db, table_name, name, length, type_code. """ def __init__(self, *args): MysqlPacket.__init__(self, *args) self.__parse_field_descriptor() def __parse_field_descriptor(self): """Parse the 'Field Descriptor' (Metadata) packet. This is compatible with MySQL 4.1+ (not compatible with MySQL 4.0). """ self.catalog = self.read_length_coded_string() self.db = self.read_length_coded_string() self.table_name = self.read_length_coded_string() self.org_table = self.read_length_coded_string() self.name = self.read_length_coded_string() self.org_name = self.read_length_coded_string() self.advance(1) # non-null filler self.charsetnr = struct.unpack('<H', self.read(2))[0] self.length = struct.unpack('<I', self.read(4))[0] self.type_code = byte2int(self.read(1)) self.flags = struct.unpack('<H', self.read(2))[0] self.scale = byte2int(self.read(1)) # "decimals" self.advance(2) # filler (always 0x00) # 'default' is a length coded binary and is still in the buffer? # not used for normal result sets... def description(self): """Provides a 7-item tuple compatible with the Python PEP249 DB Spec.""" desc = [] desc.append(self.name) desc.append(self.type_code) desc.append(None) # TODO: display_length; should this be self.length? desc.append(self.get_column_length()) # 'internal_size' desc.append(self.get_column_length()) # 'precision' # TODO: why!?!? desc.append(self.scale) # 'null_ok' -- can this be True/False rather than 1/0? # if so just do: desc.append(bool(self.flags % 2 == 0)) if self.flags % 2 == 0: desc.append(1) else: desc.append(0) return tuple(desc) def get_column_length(self): if self.type_code == FIELD_TYPE.VAR_STRING: mblen = MBLENGTH.get(self.charsetnr, 1) return self.length // mblen return self.length def __str__(self): return ('%s %s.%s.%s, type=%s' % (self.__class__, self.db, self.table_name, self.name, self.type_code)) class Connection(object): """ Representation of a socket with a mysql server. The proper way to get an instance of this class is to call connect().""" errorhandler = defaulterrorhandler def __init__(self, host="localhost", user=None, passwd="", db=None, port=3306, unix_socket=None, charset='', sql_mode=None, read_default_file=None, conv=decoders, use_unicode=None, client_flag=0, cursorclass=Cursor, init_command=None, connect_timeout=None, ssl=None, read_default_group=None, compress=None, named_pipe=None): """ Establish a connection to the MySQL database. Accepts several arguments: host: Host where the database server is located user: Username to log in as passwd: Password to use. db: Database to use, None to not use a particular one. port: MySQL port to use, default is usually OK. unix_socket: Optionally, you can use a unix socket rather than TCP/IP. charset: Charset you want to use. sql_mode: Default SQL_MODE to use. read_default_file: Specifies my.cnf file to read these parameters from under the [client] section. conv: Decoders dictionary to use instead of the default one. This is used to provide custom marshalling of types. See converters. use_unicode: Whether or not to default to unicode strings. This option defaults to true for Py3k. client_flag: Custom flags to send to MySQL. Find potential values in constants.CLIENT. cursorclass: Custom cursor class to use. init_command: Initial SQL statement to run when connection is established. connect_timeout: Timeout before throwing an exception when connecting. ssl: A dict of arguments similar to mysql_ssl_set()'s parameters. For now the capath and cipher arguments are not supported. read_default_group: Group to read from in the configuration file. compress; Not supported named_pipe: Not supported """ if use_unicode is None and sys.version_info[0] > 2: use_unicode = True if compress or named_pipe: raise NotImplementedError, "compress and named_pipe arguments are not supported" if ssl and (ssl.has_key('capath') or ssl.has_key('cipher')): raise NotImplementedError, 'ssl options capath and cipher are not supported' self.ssl = False if ssl: if not SSL_ENABLED: raise NotImplementedError, "ssl module not found" self.ssl = True client_flag |= SSL for k in ('key', 'cert', 'ca'): v = None if ssl.has_key(k): v = ssl[k] setattr(self, k, v) if read_default_group and not read_default_file: if sys.platform.startswith("win"): read_default_file = "c:\\my.ini" else: read_default_file = "/etc/my.cnf" if read_default_file: if not read_default_group: read_default_group = "client" cfg = ConfigParser.RawConfigParser() cfg.read(os.path.expanduser(read_default_file)) def _config(key, default): try: return cfg.get(read_default_group,key) except: return default user = _config("user",user) passwd = _config("password",passwd) host = _config("host", host) db = _config("db",db) unix_socket = _config("socket",unix_socket) port = _config("port", port) charset = _config("default-character-set", charset) self.host = host self.port = port self.user = user self.password = passwd self.db = db self.unix_socket = unix_socket if charset: self.charset = charset self.use_unicode = True else: self.charset = DEFAULT_CHARSET self.use_unicode = False if use_unicode: self.use_unicode = use_unicode client_flag |= CAPABILITIES client_flag |= MULTI_STATEMENTS if self.db: client_flag |= CONNECT_WITH_DB self.client_flag = client_flag self.cursorclass = cursorclass self.connect_timeout = connect_timeout self._connect() self.messages = [] self.set_charset(charset) self.encoders = encoders self.decoders = conv self._affected_rows = 0 self.host_info = "Not connected" self.autocommit(False) if sql_mode is not None: c = self.cursor() c.execute("SET sql_mode=%s", (sql_mode,)) self.commit() if init_command is not None: c = self.cursor() c.execute(init_command) self.commit() def close(self): ''' Send the quit message and close the socket ''' send_data = struct.pack('<i',1) + int2byte(COM_QUIT) self.socket.send(send_data) self.socket.close() self.socket = None def autocommit(self, value): ''' Set whether or not to commit after every execute() ''' try: self._execute_command(COM_QUERY, "SET AUTOCOMMIT = %s" % \ self.escape(value)) self.read_packet() except: exc,value,tb = sys.exc_info() self.errorhandler(None, exc, value) def commit(self): ''' Commit changes to stable storage ''' try: self._execute_command(COM_QUERY, "COMMIT") self.read_packet() except: exc,value,tb = sys.exc_info() self.errorhandler(None, exc, value) def rollback(self): ''' Roll back the current transaction ''' try: self._execute_command(COM_QUERY, "ROLLBACK") self.read_packet() except: exc,value,tb = sys.exc_info() self.errorhandler(None, exc, value) def escape(self, obj): ''' Escape whatever value you pass to it ''' return escape_item(obj, self.charset) def literal(self, obj): ''' Alias for escape() ''' return escape_item(obj, self.charset) def cursor(self): ''' Create a new cursor to execute queries with ''' return self.cursorclass(self) def __enter__(self): ''' Context manager that returns a Cursor ''' return self.cursor() def __exit__(self, exc, value, traceback): ''' On successful exit, commit. On exception, rollback. ''' if exc: self.rollback() else: self.commit() # The following methods are INTERNAL USE ONLY (called from Cursor) def query(self, sql): self._execute_command(COM_QUERY, sql) self._affected_rows = self._read_query_result() return self._affected_rows def next_result(self): self._affected_rows = self._read_query_result() return self._affected_rows def affected_rows(self): return self._affected_rows def kill(self, thread_id): arg = struct.pack('<I', thread_id) try: self._execute_command(COM_PROCESS_KILL, arg) except: exc,value,tb = sys.exc_info() self.errorhandler(None, exc, value) return pkt = self.read_packet() return pkt.is_ok_packet() def ping(self, reconnect=True): ''' Check if the server is alive ''' try: self._execute_command(COM_PING, "") except: if reconnect: self._connect() return self.ping(False) else: exc,value,tb = sys.exc_info() self.errorhandler(None, exc, value) return pkt = self.read_packet() return pkt.is_ok_packet() def set_charset(self, charset): try: if charset: self._execute_command(COM_QUERY, "SET NAMES %s" % self.escape(charset)) self.read_packet() self.charset = charset except: exc,value,tb = sys.exc_info() self.errorhandler(None, exc, value) def _connect(self): try: if self.unix_socket and (self.host == 'localhost' or self.host == '127.0.0.1'): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) t = sock.gettimeout() sock.settimeout(self.connect_timeout) sock.connect(self.unix_socket) sock.settimeout(t) self.host_info = "Localhost via UNIX socket" if DEBUG: print 'connected using unix_socket' else: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) t = sock.gettimeout() sock.settimeout(self.connect_timeout) sock.connect((self.host, self.port)) sock.settimeout(t) self.host_info = "socket %s:%d" % (self.host, self.port) if DEBUG: print 'connected using socket' self.socket = sock self._get_server_information() self._request_authentication() except socket.error, e: raise OperationalError(2003, "Can't connect to MySQL server on %r (%d)" % (self.host, e.args[0])) def read_packet(self, packet_type=MysqlPacket): """Read an entire "mysql packet" in its entirety from the network and return a MysqlPacket type that represents the results.""" # TODO: is socket.recv(small_number) significantly slower than # socket.recv(large_number)? if so, maybe we should buffer # the socket.recv() (though that obviously makes memory management # more complicated. packet = packet_type(self.socket) packet.check_error() return packet def _read_query_result(self): result = MySQLResult(self) result.read() self._result = result return result.affected_rows def _send_command(self, command, sql): #send_data = struct.pack('<i', len(sql) + 1) + command + sql # could probably be more efficient, at least it's correct if not self.socket: self.errorhandler(None, InterfaceError, "(0, '')") if isinstance(sql, unicode): sql = sql.encode(self.charset) buf = int2byte(command) + sql pckt_no = 0 while len(buf) >= MAX_PACKET_LENGTH: header = struct.pack('<i', MAX_PACKET_LENGTH)[:-1]+int2byte(pckt_no) send_data = header + buf[:MAX_PACKET_LENGTH] self.socket.send(send_data) if DEBUG: dump_packet(send_data) buf = buf[MAX_PACKET_LENGTH:] pckt_no += 1 header = struct.pack('<i', len(buf))[:-1]+int2byte(pckt_no) self.socket.send(header+buf) #sock = self.socket #sock.send(send_data) # def _execute_command(self, command, sql): self._send_command(command, sql) def _request_authentication(self): self._send_authentication() def _send_authentication(self): sock = self.socket self.client_flag |= CAPABILITIES if self.server_version.startswith('5'): self.client_flag |= MULTI_RESULTS if self.user is None: raise ValueError, "Did not specify a username" charset_id = charset_by_name(self.charset).id self.user = self.user.encode(self.charset) data_init = struct.pack('<i', self.client_flag) + struct.pack("<I", 1) + \ int2byte(charset_id) + int2byte(0)*23 next_packet = 1 if self.ssl: data = pack_int24(len(data_init)) + int2byte(next_packet) + data_init next_packet += 1 if DEBUG: dump_packet(data) sock.send(data) sock = self.socket = ssl.wrap_socket(sock, keyfile=self.key, certfile=self.cert, ssl_version=ssl.PROTOCOL_TLSv1, cert_reqs=ssl.CERT_REQUIRED, ca_certs=self.ca) data = data_init + self.user+int2byte(0) + _scramble(self.password.encode(self.charset), self.salt) if self.db: self.db = self.db.encode(self.charset) data += self.db + int2byte(0) data = pack_int24(len(data)) + int2byte(next_packet) + data next_packet += 2 if DEBUG: dump_packet(data) sock.send(data) auth_packet = MysqlPacket(sock) auth_packet.check_error() if DEBUG: auth_packet.dump() # if old_passwords is enabled the packet will be 1 byte long and # have the octet 254 if auth_packet.is_eof_packet(): # send legacy handshake #raise NotImplementedError, "old_passwords are not supported. Check to see if mysqld was started with --old-passwords, if old-passwords=1 in a my.cnf file, or if there are some short hashes in your mysql.user table." # TODO: is this the correct charset? data = _scramble_323(self.password.encode(self.charset), self.salt.encode(self.charset)) + int2byte(0) data = pack_int24(len(data)) + int2byte(next_packet) + data sock.send(data) auth_packet = MysqlPacket(sock) auth_packet.check_error() if DEBUG: auth_packet.dump() # _mysql support def thread_id(self): return self.server_thread_id[0] def character_set_name(self): return self.charset def get_host_info(self): return self.host_info def get_proto_info(self): return self.protocol_version def _get_server_information(self): sock = self.socket i = 0 packet = MysqlPacket(sock) data = packet.get_all_data() if DEBUG: dump_packet(data) #packet_len = byte2int(data[i:i+1]) #i += 4 self.protocol_version = byte2int(data[i:i+1]) i += 1 server_end = data.find(int2byte(0), i) # TODO: is this the correct charset? should it be default_charset? self.server_version = data[i:server_end].decode(self.charset) i = server_end + 1 self.server_thread_id = struct.unpack('<h', data[i:i+2]) i += 4 self.salt = data[i:i+8] i += 9 if len(data) >= i + 1: i += 1 self.server_capabilities = struct.unpack('<h', data[i:i+2])[0] i += 1 self.server_language = byte2int(data[i:i+1]) self.server_charset = charset_by_id(self.server_language).name i += 16 if len(data) >= i+12-1: rest_salt = data[i:i+12] self.salt += rest_salt def get_server_info(self): return self.server_version Warning = Warning Error = Error InterfaceError = InterfaceError DatabaseError = DatabaseError DataError = DataError OperationalError = OperationalError IntegrityError = IntegrityError InternalError = InternalError ProgrammingError = ProgrammingError NotSupportedError = NotSupportedError # TODO: move OK and EOF packet parsing/logic into a proper subclass # of MysqlPacket like has been done with FieldDescriptorPacket. class MySQLResult(object): def __init__(self, connection): from weakref import proxy self.connection = proxy(connection) self.affected_rows = None self.insert_id = None self.server_status = 0 self.warning_count = 0 self.message = None self.field_count = 0 self.description = None self.rows = None self.has_next = None def read(self): self.first_packet = self.connection.read_packet() # TODO: use classes for different packet types? if self.first_packet.is_ok_packet(): self._read_ok_packet() else: self._read_result_packet() def _read_ok_packet(self): self.first_packet.advance(1) # field_count (always '0') self.affected_rows = self.first_packet.read_length_coded_binary() self.insert_id = self.first_packet.read_length_coded_binary() self.server_status = struct.unpack('<H', self.first_packet.read(2))[0] self.warning_count = struct.unpack('<H', self.first_packet.read(2))[0] self.message = self.first_packet.read_all() def _read_result_packet(self): self.field_count = byte2int(self.first_packet.read(1)) self._get_descriptions() self._read_rowdata_packet() # TODO: implement this as an iteratable so that it is more # memory efficient and lower-latency to client... def _read_rowdata_packet(self): """Read a rowdata packet for each data row in the result set.""" rows = [] while True: packet = self.connection.read_packet() if packet.is_eof_packet(): self.warning_count = packet.read(2) server_status = struct.unpack('<h', packet.read(2))[0] self.has_next = (server_status & SERVER_STATUS.SERVER_MORE_RESULTS_EXISTS) break row = [] for field in self.fields: if field.type_code in self.connection.decoders: converter = self.connection.decoders[field.type_code] if DEBUG: print "DEBUG: field=%s, converter=%s" % (field, converter) data = packet.read_length_coded_string() converted = None if data != None: converted = converter(self.connection, field, data) row.append(converted) rows.append(tuple(row)) self.affected_rows = len(rows) self.rows = tuple(rows) if DEBUG: self.rows def _get_descriptions(self): """Read a column descriptor packet for each column in the result.""" self.fields = [] description = [] for i in xrange(self.field_count): field = self.connection.read_packet(FieldDescriptorPacket) self.fields.append(field) description.append(field.description()) eof_packet = self.connection.read_packet() assert eof_packet.is_eof_packet(), 'Protocol error, expecting EOF' self.description = tuple(description)
Python
COM_SLEEP = 0x00 COM_QUIT = 0x01 COM_INIT_DB = 0x02 COM_QUERY = 0x03 COM_FIELD_LIST = 0x04 COM_CREATE_DB = 0x05 COM_DROP_DB = 0x06 COM_REFRESH = 0x07 COM_SHUTDOWN = 0x08 COM_STATISTICS = 0x09 COM_PROCESS_INFO = 0x0a COM_CONNECT = 0x0b COM_PROCESS_KILL = 0x0c COM_DEBUG = 0x0d COM_PING = 0x0e COM_TIME = 0x0f COM_DELAYED_INSERT = 0x10 COM_CHANGE_USER = 0x11 COM_BINLOG_DUMP = 0x12 COM_TABLE_DUMP = 0x13 COM_CONNECT_OUT = 0x14 COM_REGISTER_SLAVE = 0x15
Python
DECIMAL = 0 TINY = 1 SHORT = 2 LONG = 3 FLOAT = 4 DOUBLE = 5 NULL = 6 TIMESTAMP = 7 LONGLONG = 8 INT24 = 9 DATE = 10 TIME = 11 DATETIME = 12 YEAR = 13 NEWDATE = 14 VARCHAR = 15 BIT = 16 NEWDECIMAL = 246 ENUM = 247 SET = 248 TINY_BLOB = 249 MEDIUM_BLOB = 250 LONG_BLOB = 251 BLOB = 252 VAR_STRING = 253 STRING = 254 GEOMETRY = 255 CHAR = TINY INTERVAL = ENUM
Python
NOT_NULL = 1 PRI_KEY = 2 UNIQUE_KEY = 4 MULTIPLE_KEY = 8 BLOB = 16 UNSIGNED = 32 ZEROFILL = 64 BINARY = 128 ENUM = 256 AUTO_INCREMENT = 512 TIMESTAMP = 1024 SET = 2048 PART_KEY = 16384 GROUP = 32767 UNIQUE = 65536
Python
ERROR_FIRST = 1000 HASHCHK = 1000 NISAMCHK = 1001 NO = 1002 YES = 1003 CANT_CREATE_FILE = 1004 CANT_CREATE_TABLE = 1005 CANT_CREATE_DB = 1006 DB_CREATE_EXISTS = 1007 DB_DROP_EXISTS = 1008 DB_DROP_DELETE = 1009 DB_DROP_RMDIR = 1010 CANT_DELETE_FILE = 1011 CANT_FIND_SYSTEM_REC = 1012 CANT_GET_STAT = 1013 CANT_GET_WD = 1014 CANT_LOCK = 1015 CANT_OPEN_FILE = 1016 FILE_NOT_FOUND = 1017 CANT_READ_DIR = 1018 CANT_SET_WD = 1019 CHECKREAD = 1020 DISK_FULL = 1021 DUP_KEY = 1022 ERROR_ON_CLOSE = 1023 ERROR_ON_READ = 1024 ERROR_ON_RENAME = 1025 ERROR_ON_WRITE = 1026 FILE_USED = 1027 FILSORT_ABORT = 1028 FORM_NOT_FOUND = 1029 GET_ERRNO = 1030 ILLEGAL_HA = 1031 KEY_NOT_FOUND = 1032 NOT_FORM_FILE = 1033 NOT_KEYFILE = 1034 OLD_KEYFILE = 1035 OPEN_AS_READONLY = 1036 OUTOFMEMORY = 1037 OUT_OF_SORTMEMORY = 1038 UNEXPECTED_EOF = 1039 CON_COUNT_ERROR = 1040 OUT_OF_RESOURCES = 1041 BAD_HOST_ERROR = 1042 HANDSHAKE_ERROR = 1043 DBACCESS_DENIED_ERROR = 1044 ACCESS_DENIED_ERROR = 1045 NO_DB_ERROR = 1046 UNKNOWN_COM_ERROR = 1047 BAD_NULL_ERROR = 1048 BAD_DB_ERROR = 1049 TABLE_EXISTS_ERROR = 1050 BAD_TABLE_ERROR = 1051 NON_UNIQ_ERROR = 1052 SERVER_SHUTDOWN = 1053 BAD_FIELD_ERROR = 1054 WRONG_FIELD_WITH_GROUP = 1055 WRONG_GROUP_FIELD = 1056 WRONG_SUM_SELECT = 1057 WRONG_VALUE_COUNT = 1058 TOO_LONG_IDENT = 1059 DUP_FIELDNAME = 1060 DUP_KEYNAME = 1061 DUP_ENTRY = 1062 WRONG_FIELD_SPEC = 1063 PARSE_ERROR = 1064 EMPTY_QUERY = 1065 NONUNIQ_TABLE = 1066 INVALID_DEFAULT = 1067 MULTIPLE_PRI_KEY = 1068 TOO_MANY_KEYS = 1069 TOO_MANY_KEY_PARTS = 1070 TOO_LONG_KEY = 1071 KEY_COLUMN_DOES_NOT_EXITS = 1072 BLOB_USED_AS_KEY = 1073 TOO_BIG_FIELDLENGTH = 1074 WRONG_AUTO_KEY = 1075 READY = 1076 NORMAL_SHUTDOWN = 1077 GOT_SIGNAL = 1078 SHUTDOWN_COMPLETE = 1079 FORCING_CLOSE = 1080 IPSOCK_ERROR = 1081 NO_SUCH_INDEX = 1082 WRONG_FIELD_TERMINATORS = 1083 BLOBS_AND_NO_TERMINATED = 1084 TEXTFILE_NOT_READABLE = 1085 FILE_EXISTS_ERROR = 1086 LOAD_INFO = 1087 ALTER_INFO = 1088 WRONG_SUB_KEY = 1089 CANT_REMOVE_ALL_FIELDS = 1090 CANT_DROP_FIELD_OR_KEY = 1091 INSERT_INFO = 1092 UPDATE_TABLE_USED = 1093 NO_SUCH_THREAD = 1094 KILL_DENIED_ERROR = 1095 NO_TABLES_USED = 1096 TOO_BIG_SET = 1097 NO_UNIQUE_LOGFILE = 1098 TABLE_NOT_LOCKED_FOR_WRITE = 1099 TABLE_NOT_LOCKED = 1100 BLOB_CANT_HAVE_DEFAULT = 1101 WRONG_DB_NAME = 1102 WRONG_TABLE_NAME = 1103 TOO_BIG_SELECT = 1104 UNKNOWN_ERROR = 1105 UNKNOWN_PROCEDURE = 1106 WRONG_PARAMCOUNT_TO_PROCEDURE = 1107 WRONG_PARAMETERS_TO_PROCEDURE = 1108 UNKNOWN_TABLE = 1109 FIELD_SPECIFIED_TWICE = 1110 INVALID_GROUP_FUNC_USE = 1111 UNSUPPORTED_EXTENSION = 1112 TABLE_MUST_HAVE_COLUMNS = 1113 RECORD_FILE_FULL = 1114 UNKNOWN_CHARACTER_SET = 1115 TOO_MANY_TABLES = 1116 TOO_MANY_FIELDS = 1117 TOO_BIG_ROWSIZE = 1118 STACK_OVERRUN = 1119 WRONG_OUTER_JOIN = 1120 NULL_COLUMN_IN_INDEX = 1121 CANT_FIND_UDF = 1122 CANT_INITIALIZE_UDF = 1123 UDF_NO_PATHS = 1124 UDF_EXISTS = 1125 CANT_OPEN_LIBRARY = 1126 CANT_FIND_DL_ENTRY = 1127 FUNCTION_NOT_DEFINED = 1128 HOST_IS_BLOCKED = 1129 HOST_NOT_PRIVILEGED = 1130 PASSWORD_ANONYMOUS_USER = 1131 PASSWORD_NOT_ALLOWED = 1132 PASSWORD_NO_MATCH = 1133 UPDATE_INFO = 1134 CANT_CREATE_THREAD = 1135 WRONG_VALUE_COUNT_ON_ROW = 1136 CANT_REOPEN_TABLE = 1137 INVALID_USE_OF_NULL = 1138 REGEXP_ERROR = 1139 MIX_OF_GROUP_FUNC_AND_FIELDS = 1140 NONEXISTING_GRANT = 1141 TABLEACCESS_DENIED_ERROR = 1142 COLUMNACCESS_DENIED_ERROR = 1143 ILLEGAL_GRANT_FOR_TABLE = 1144 GRANT_WRONG_HOST_OR_USER = 1145 NO_SUCH_TABLE = 1146 NONEXISTING_TABLE_GRANT = 1147 NOT_ALLOWED_COMMAND = 1148 SYNTAX_ERROR = 1149 DELAYED_CANT_CHANGE_LOCK = 1150 TOO_MANY_DELAYED_THREADS = 1151 ABORTING_CONNECTION = 1152 NET_PACKET_TOO_LARGE = 1153 NET_READ_ERROR_FROM_PIPE = 1154 NET_FCNTL_ERROR = 1155 NET_PACKETS_OUT_OF_ORDER = 1156 NET_UNCOMPRESS_ERROR = 1157 NET_READ_ERROR = 1158 NET_READ_INTERRUPTED = 1159 NET_ERROR_ON_WRITE = 1160 NET_WRITE_INTERRUPTED = 1161 TOO_LONG_STRING = 1162 TABLE_CANT_HANDLE_BLOB = 1163 TABLE_CANT_HANDLE_AUTO_INCREMENT = 1164 DELAYED_INSERT_TABLE_LOCKED = 1165 WRONG_COLUMN_NAME = 1166 WRONG_KEY_COLUMN = 1167 WRONG_MRG_TABLE = 1168 DUP_UNIQUE = 1169 BLOB_KEY_WITHOUT_LENGTH = 1170 PRIMARY_CANT_HAVE_NULL = 1171 TOO_MANY_ROWS = 1172 REQUIRES_PRIMARY_KEY = 1173 NO_RAID_COMPILED = 1174 UPDATE_WITHOUT_KEY_IN_SAFE_MODE = 1175 KEY_DOES_NOT_EXITS = 1176 CHECK_NO_SUCH_TABLE = 1177 CHECK_NOT_IMPLEMENTED = 1178 CANT_DO_THIS_DURING_AN_TRANSACTION = 1179 ERROR_DURING_COMMIT = 1180 ERROR_DURING_ROLLBACK = 1181 ERROR_DURING_FLUSH_LOGS = 1182 ERROR_DURING_CHECKPOINT = 1183 NEW_ABORTING_CONNECTION = 1184 DUMP_NOT_IMPLEMENTED = 1185 FLUSH_MASTER_BINLOG_CLOSED = 1186 INDEX_REBUILD = 1187 MASTER = 1188 MASTER_NET_READ = 1189 MASTER_NET_WRITE = 1190 FT_MATCHING_KEY_NOT_FOUND = 1191 LOCK_OR_ACTIVE_TRANSACTION = 1192 UNKNOWN_SYSTEM_VARIABLE = 1193 CRASHED_ON_USAGE = 1194 CRASHED_ON_REPAIR = 1195 WARNING_NOT_COMPLETE_ROLLBACK = 1196 TRANS_CACHE_FULL = 1197 SLAVE_MUST_STOP = 1198 SLAVE_NOT_RUNNING = 1199 BAD_SLAVE = 1200 MASTER_INFO = 1201 SLAVE_THREAD = 1202 TOO_MANY_USER_CONNECTIONS = 1203 SET_CONSTANTS_ONLY = 1204 LOCK_WAIT_TIMEOUT = 1205 LOCK_TABLE_FULL = 1206 READ_ONLY_TRANSACTION = 1207 DROP_DB_WITH_READ_LOCK = 1208 CREATE_DB_WITH_READ_LOCK = 1209 WRONG_ARGUMENTS = 1210 NO_PERMISSION_TO_CREATE_USER = 1211 UNION_TABLES_IN_DIFFERENT_DIR = 1212 LOCK_DEADLOCK = 1213 TABLE_CANT_HANDLE_FT = 1214 CANNOT_ADD_FOREIGN = 1215 NO_REFERENCED_ROW = 1216 ROW_IS_REFERENCED = 1217 CONNECT_TO_MASTER = 1218 QUERY_ON_MASTER = 1219 ERROR_WHEN_EXECUTING_COMMAND = 1220 WRONG_USAGE = 1221 WRONG_NUMBER_OF_COLUMNS_IN_SELECT = 1222 CANT_UPDATE_WITH_READLOCK = 1223 MIXING_NOT_ALLOWED = 1224 DUP_ARGUMENT = 1225 USER_LIMIT_REACHED = 1226 SPECIFIC_ACCESS_DENIED_ERROR = 1227 LOCAL_VARIABLE = 1228 GLOBAL_VARIABLE = 1229 NO_DEFAULT = 1230 WRONG_VALUE_FOR_VAR = 1231 WRONG_TYPE_FOR_VAR = 1232 VAR_CANT_BE_READ = 1233 CANT_USE_OPTION_HERE = 1234 NOT_SUPPORTED_YET = 1235 MASTER_FATAL_ERROR_READING_BINLOG = 1236 SLAVE_IGNORED_TABLE = 1237 INCORRECT_GLOBAL_LOCAL_VAR = 1238 WRONG_FK_DEF = 1239 KEY_REF_DO_NOT_MATCH_TABLE_REF = 1240 OPERAND_COLUMNS = 1241 SUBQUERY_NO_1_ROW = 1242 UNKNOWN_STMT_HANDLER = 1243 CORRUPT_HELP_DB = 1244 CYCLIC_REFERENCE = 1245 AUTO_CONVERT = 1246 ILLEGAL_REFERENCE = 1247 DERIVED_MUST_HAVE_ALIAS = 1248 SELECT_REDUCED = 1249 TABLENAME_NOT_ALLOWED_HERE = 1250 NOT_SUPPORTED_AUTH_MODE = 1251 SPATIAL_CANT_HAVE_NULL = 1252 COLLATION_CHARSET_MISMATCH = 1253 SLAVE_WAS_RUNNING = 1254 SLAVE_WAS_NOT_RUNNING = 1255 TOO_BIG_FOR_UNCOMPRESS = 1256 ZLIB_Z_MEM_ERROR = 1257 ZLIB_Z_BUF_ERROR = 1258 ZLIB_Z_DATA_ERROR = 1259 CUT_VALUE_GROUP_CONCAT = 1260 WARN_TOO_FEW_RECORDS = 1261 WARN_TOO_MANY_RECORDS = 1262 WARN_NULL_TO_NOTNULL = 1263 WARN_DATA_OUT_OF_RANGE = 1264 WARN_DATA_TRUNCATED = 1265 WARN_USING_OTHER_HANDLER = 1266 CANT_AGGREGATE_2COLLATIONS = 1267 DROP_USER = 1268 REVOKE_GRANTS = 1269 CANT_AGGREGATE_3COLLATIONS = 1270 CANT_AGGREGATE_NCOLLATIONS = 1271 VARIABLE_IS_NOT_STRUCT = 1272 UNKNOWN_COLLATION = 1273 SLAVE_IGNORED_SSL_PARAMS = 1274 SERVER_IS_IN_SECURE_AUTH_MODE = 1275 WARN_FIELD_RESOLVED = 1276 BAD_SLAVE_UNTIL_COND = 1277 MISSING_SKIP_SLAVE = 1278 UNTIL_COND_IGNORED = 1279 WRONG_NAME_FOR_INDEX = 1280 WRONG_NAME_FOR_CATALOG = 1281 WARN_QC_RESIZE = 1282 BAD_FT_COLUMN = 1283 UNKNOWN_KEY_CACHE = 1284 WARN_HOSTNAME_WONT_WORK = 1285 UNKNOWN_STORAGE_ENGINE = 1286 WARN_DEPRECATED_SYNTAX = 1287 NON_UPDATABLE_TABLE = 1288 FEATURE_DISABLED = 1289 OPTION_PREVENTS_STATEMENT = 1290 DUPLICATED_VALUE_IN_TYPE = 1291 TRUNCATED_WRONG_VALUE = 1292 TOO_MUCH_AUTO_TIMESTAMP_COLS = 1293 INVALID_ON_UPDATE = 1294 UNSUPPORTED_PS = 1295 GET_ERRMSG = 1296 GET_TEMPORARY_ERRMSG = 1297 UNKNOWN_TIME_ZONE = 1298 WARN_INVALID_TIMESTAMP = 1299 INVALID_CHARACTER_STRING = 1300 WARN_ALLOWED_PACKET_OVERFLOWED = 1301 CONFLICTING_DECLARATIONS = 1302 SP_NO_RECURSIVE_CREATE = 1303 SP_ALREADY_EXISTS = 1304 SP_DOES_NOT_EXIST = 1305 SP_DROP_FAILED = 1306 SP_STORE_FAILED = 1307 SP_LILABEL_MISMATCH = 1308 SP_LABEL_REDEFINE = 1309 SP_LABEL_MISMATCH = 1310 SP_UNINIT_VAR = 1311 SP_BADSELECT = 1312 SP_BADRETURN = 1313 SP_BADSTATEMENT = 1314 UPDATE_LOG_DEPRECATED_IGNORED = 1315 UPDATE_LOG_DEPRECATED_TRANSLATED = 1316 QUERY_INTERRUPTED = 1317 SP_WRONG_NO_OF_ARGS = 1318 SP_COND_MISMATCH = 1319 SP_NORETURN = 1320 SP_NORETURNEND = 1321 SP_BAD_CURSOR_QUERY = 1322 SP_BAD_CURSOR_SELECT = 1323 SP_CURSOR_MISMATCH = 1324 SP_CURSOR_ALREADY_OPEN = 1325 SP_CURSOR_NOT_OPEN = 1326 SP_UNDECLARED_VAR = 1327 SP_WRONG_NO_OF_FETCH_ARGS = 1328 SP_FETCH_NO_DATA = 1329 SP_DUP_PARAM = 1330 SP_DUP_VAR = 1331 SP_DUP_COND = 1332 SP_DUP_CURS = 1333 SP_CANT_ALTER = 1334 SP_SUBSELECT_NYI = 1335 STMT_NOT_ALLOWED_IN_SF_OR_TRG = 1336 SP_VARCOND_AFTER_CURSHNDLR = 1337 SP_CURSOR_AFTER_HANDLER = 1338 SP_CASE_NOT_FOUND = 1339 FPARSER_TOO_BIG_FILE = 1340 FPARSER_BAD_HEADER = 1341 FPARSER_EOF_IN_COMMENT = 1342 FPARSER_ERROR_IN_PARAMETER = 1343 FPARSER_EOF_IN_UNKNOWN_PARAMETER = 1344 VIEW_NO_EXPLAIN = 1345 FRM_UNKNOWN_TYPE = 1346 WRONG_OBJECT = 1347 NONUPDATEABLE_COLUMN = 1348 VIEW_SELECT_DERIVED = 1349 VIEW_SELECT_CLAUSE = 1350 VIEW_SELECT_VARIABLE = 1351 VIEW_SELECT_TMPTABLE = 1352 VIEW_WRONG_LIST = 1353 WARN_VIEW_MERGE = 1354 WARN_VIEW_WITHOUT_KEY = 1355 VIEW_INVALID = 1356 SP_NO_DROP_SP = 1357 SP_GOTO_IN_HNDLR = 1358 TRG_ALREADY_EXISTS = 1359 TRG_DOES_NOT_EXIST = 1360 TRG_ON_VIEW_OR_TEMP_TABLE = 1361 TRG_CANT_CHANGE_ROW = 1362 TRG_NO_SUCH_ROW_IN_TRG = 1363 NO_DEFAULT_FOR_FIELD = 1364 DIVISION_BY_ZERO = 1365 TRUNCATED_WRONG_VALUE_FOR_FIELD = 1366 ILLEGAL_VALUE_FOR_TYPE = 1367 VIEW_NONUPD_CHECK = 1368 VIEW_CHECK_FAILED = 1369 PROCACCESS_DENIED_ERROR = 1370 RELAY_LOG_FAIL = 1371 PASSWD_LENGTH = 1372 UNKNOWN_TARGET_BINLOG = 1373 IO_ERR_LOG_INDEX_READ = 1374 BINLOG_PURGE_PROHIBITED = 1375 FSEEK_FAIL = 1376 BINLOG_PURGE_FATAL_ERR = 1377 LOG_IN_USE = 1378 LOG_PURGE_UNKNOWN_ERR = 1379 RELAY_LOG_INIT = 1380 NO_BINARY_LOGGING = 1381 RESERVED_SYNTAX = 1382 WSAS_FAILED = 1383 DIFF_GROUPS_PROC = 1384 NO_GROUP_FOR_PROC = 1385 ORDER_WITH_PROC = 1386 LOGGING_PROHIBIT_CHANGING_OF = 1387 NO_FILE_MAPPING = 1388 WRONG_MAGIC = 1389 PS_MANY_PARAM = 1390 KEY_PART_0 = 1391 VIEW_CHECKSUM = 1392 VIEW_MULTIUPDATE = 1393 VIEW_NO_INSERT_FIELD_LIST = 1394 VIEW_DELETE_MERGE_VIEW = 1395 CANNOT_USER = 1396 XAER_NOTA = 1397 XAER_INVAL = 1398 XAER_RMFAIL = 1399 XAER_OUTSIDE = 1400 XAER_RMERR = 1401 XA_RBROLLBACK = 1402 NONEXISTING_PROC_GRANT = 1403 PROC_AUTO_GRANT_FAIL = 1404 PROC_AUTO_REVOKE_FAIL = 1405 DATA_TOO_LONG = 1406 SP_BAD_SQLSTATE = 1407 STARTUP = 1408 LOAD_FROM_FIXED_SIZE_ROWS_TO_VAR = 1409 CANT_CREATE_USER_WITH_GRANT = 1410 WRONG_VALUE_FOR_TYPE = 1411 TABLE_DEF_CHANGED = 1412 SP_DUP_HANDLER = 1413 SP_NOT_VAR_ARG = 1414 SP_NO_RETSET = 1415 CANT_CREATE_GEOMETRY_OBJECT = 1416 FAILED_ROUTINE_BREAK_BINLOG = 1417 BINLOG_UNSAFE_ROUTINE = 1418 BINLOG_CREATE_ROUTINE_NEED_SUPER = 1419 EXEC_STMT_WITH_OPEN_CURSOR = 1420 STMT_HAS_NO_OPEN_CURSOR = 1421 COMMIT_NOT_ALLOWED_IN_SF_OR_TRG = 1422 NO_DEFAULT_FOR_VIEW_FIELD = 1423 SP_NO_RECURSION = 1424 TOO_BIG_SCALE = 1425 TOO_BIG_PRECISION = 1426 M_BIGGER_THAN_D = 1427 WRONG_LOCK_OF_SYSTEM_TABLE = 1428 CONNECT_TO_FOREIGN_DATA_SOURCE = 1429 QUERY_ON_FOREIGN_DATA_SOURCE = 1430 FOREIGN_DATA_SOURCE_DOESNT_EXIST = 1431 FOREIGN_DATA_STRING_INVALID_CANT_CREATE = 1432 FOREIGN_DATA_STRING_INVALID = 1433 CANT_CREATE_FEDERATED_TABLE = 1434 TRG_IN_WRONG_SCHEMA = 1435 STACK_OVERRUN_NEED_MORE = 1436 TOO_LONG_BODY = 1437 WARN_CANT_DROP_DEFAULT_KEYCACHE = 1438 TOO_BIG_DISPLAYWIDTH = 1439 XAER_DUPID = 1440 DATETIME_FUNCTION_OVERFLOW = 1441 CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG = 1442 VIEW_PREVENT_UPDATE = 1443 PS_NO_RECURSION = 1444 SP_CANT_SET_AUTOCOMMIT = 1445 MALFORMED_DEFINER = 1446 VIEW_FRM_NO_USER = 1447 VIEW_OTHER_USER = 1448 NO_SUCH_USER = 1449 FORBID_SCHEMA_CHANGE = 1450 ROW_IS_REFERENCED_2 = 1451 NO_REFERENCED_ROW_2 = 1452 SP_BAD_VAR_SHADOW = 1453 TRG_NO_DEFINER = 1454 OLD_FILE_FORMAT = 1455 SP_RECURSION_LIMIT = 1456 SP_PROC_TABLE_CORRUPT = 1457 SP_WRONG_NAME = 1458 TABLE_NEEDS_UPGRADE = 1459 SP_NO_AGGREGATE = 1460 MAX_PREPARED_STMT_COUNT_REACHED = 1461 VIEW_RECURSIVE = 1462 NON_GROUPING_FIELD_USED = 1463 TABLE_CANT_HANDLE_SPKEYS = 1464 NO_TRIGGERS_ON_SYSTEM_SCHEMA = 1465 USERNAME = 1466 HOSTNAME = 1467 WRONG_STRING_LENGTH = 1468 ERROR_LAST = 1468
Python
SERVER_STATUS_IN_TRANS = 1 SERVER_STATUS_AUTOCOMMIT = 2 SERVER_MORE_RESULTS_EXISTS = 8 SERVER_QUERY_NO_GOOD_INDEX_USED = 16 SERVER_QUERY_NO_INDEX_USED = 32 SERVER_STATUS_CURSOR_EXISTS = 64 SERVER_STATUS_LAST_ROW_SENT = 128 SERVER_STATUS_DB_DROPPED = 256 SERVER_STATUS_NO_BACKSLASH_ESCAPES = 512 SERVER_STATUS_METADATA_CHANGED = 1024
Python
LONG_PASSWORD = 1 FOUND_ROWS = 1 << 1 LONG_FLAG = 1 << 2 CONNECT_WITH_DB = 1 << 3 NO_SCHEMA = 1 << 4 COMPRESS = 1 << 5 ODBC = 1 << 6 LOCAL_FILES = 1 << 7 IGNORE_SPACE = 1 << 8 PROTOCOL_41 = 1 << 9 INTERACTIVE = 1 << 10 SSL = 1 << 11 IGNORE_SIGPIPE = 1 << 12 TRANSACTIONS = 1 << 13 SECURE_CONNECTION = 1 << 15 MULTI_STATEMENTS = 1 << 16 MULTI_RESULTS = 1 << 17 CAPABILITIES = LONG_PASSWORD|LONG_FLAG|TRANSACTIONS| \ PROTOCOL_41|SECURE_CONNECTION
Python
#!/usr/bin/env python """ client module for memcached (memory cache daemon) Overview ======== See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached. Usage summary ============= This should give you a feel for how this module operates:: import memcache mc = memcache.Client(['127.0.0.1:11211'], debug=0) mc.set("some_key", "Some value") value = mc.get("some_key") mc.set("another_key", 3) mc.delete("another_key") mc.set("key", "1") # note that the key used for incr/decr must be a string. mc.incr("key") mc.decr("key") The standard way to use memcache with a database is like this:: key = derive_key(obj) obj = mc.get(key) if not obj: obj = backend_api.get(...) mc.set(obj) # we now have obj, and future passes through this code # will use the object from the cache. Detailed Documentation ====================== More detailed documentation is available in the L{Client} class. """ import sys import socket import time import os import re import types try: import cPickle as pickle except ImportError: import pickle try: from zlib import compress, decompress _supports_compress = True except ImportError: _supports_compress = False # quickly define a decompress just in case we recv compressed data. def decompress(val): raise _Error("received compressed data but I don't support compession (import error)") try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from binascii import crc32 # zlib version is not cross-platform serverHashFunction = crc32 __author__ = "Evan Martin <martine@danga.com>" __version__ = "1.44" __copyright__ = "Copyright (C) 2003 Danga Interactive" __license__ = "Python" SERVER_MAX_KEY_LENGTH = 250 # Storing values larger than 1MB requires recompiling memcached. If you do, # this value can be changed by doing "memcache.SERVER_MAX_VALUE_LENGTH = N" # after importing this module. SERVER_MAX_VALUE_LENGTH = 1024*1024 class _Error(Exception): pass try: # Only exists in Python 2.4+ from threading import local except ImportError: # TODO: add the pure-python local implementation class local(object): pass class Client(local): """ Object representing a pool of memcache servers. See L{memcache} for an overview. In all cases where a key is used, the key can be either: 1. A simple hashable type (string, integer, etc.). 2. A tuple of C{(hashvalue, key)}. This is useful if you want to avoid making this module calculate a hash value. You may prefer, for example, to keep all of a given user's objects on the same memcache server, so you could use the user's unique id as the hash value. @group Setup: __init__, set_servers, forget_dead_hosts, disconnect_all, debuglog @group Insertion: set, add, replace, set_multi @group Retrieval: get, get_multi @group Integers: incr, decr @group Removal: delete, delete_multi @sort: __init__, set_servers, forget_dead_hosts, disconnect_all, debuglog,\ set, set_multi, add, replace, get, get_multi, incr, decr, delete, delete_multi """ _FLAG_PICKLE = 1<<0 _FLAG_INTEGER = 1<<1 _FLAG_LONG = 1<<2 _FLAG_COMPRESSED = 1<<3 _SERVER_RETRIES = 10 # how many times to try finding a free server. # exceptions for Client class MemcachedKeyError(Exception): pass class MemcachedKeyLengthError(MemcachedKeyError): pass class MemcachedKeyCharacterError(MemcachedKeyError): pass class MemcachedKeyNoneError(MemcachedKeyError): pass class MemcachedKeyTypeError(MemcachedKeyError): pass class MemcachedStringEncodingError(Exception): pass def __init__(self, servers, debug=0, pickleProtocol=0, pickler=pickle.Pickler, unpickler=pickle.Unpickler, pload=None, pid=None): """ Create a new Client object with the given list of servers. @param servers: C{servers} is passed to L{set_servers}. @param debug: whether to display error messages when a server can't be contacted. @param pickleProtocol: number to mandate protocol used by (c)Pickle. @param pickler: optional override of default Pickler to allow subclassing. @param unpickler: optional override of default Unpickler to allow subclassing. @param pload: optional persistent_load function to call on pickle loading. Useful for cPickle since subclassing isn't allowed. @param pid: optional persistent_id function to call on pickle storing. Useful for cPickle since subclassing isn't allowed. """ local.__init__(self) self.set_servers(servers) self.debug = debug self.stats = {} # Allow users to modify pickling/unpickling behavior self.pickleProtocol = pickleProtocol self.pickler = pickler self.unpickler = unpickler self.persistent_load = pload self.persistent_id = pid # figure out the pickler style file = StringIO() try: pickler = self.pickler(file, protocol = self.pickleProtocol) self.picklerIsKeyword = True except TypeError: self.picklerIsKeyword = False def set_servers(self, servers): """ Set the pool of servers used by this client. @param servers: an array of servers. Servers can be passed in two forms: 1. Strings of the form C{"host:port"}, which implies a default weight of 1. 2. Tuples of the form C{("host:port", weight)}, where C{weight} is an integer weight value. """ self.servers = [_Host(s, self.debuglog) for s in servers] self._init_buckets() def get_stats(self): '''Get statistics from each of the servers. @return: A list of tuples ( server_identifier, stats_dictionary ). The dictionary contains a number of name/value pairs specifying the name of the status field and the string value associated with it. The values are not converted from strings. ''' data = [] for s in self.servers: if not s.connect(): continue if s.family == socket.AF_INET: name = '%s:%s (%s)' % ( s.ip, s.port, s.weight ) else: name = 'unix:%s (%s)' % ( s.address, s.weight ) s.send_cmd('stats') serverData = {} data.append(( name, serverData )) readline = s.readline while 1: line = readline() if not line or line.strip() == 'END': break stats = line.split(' ', 2) serverData[stats[1]] = stats[2] return(data) def get_slabs(self): data = [] for s in self.servers: if not s.connect(): continue if s.family == socket.AF_INET: name = '%s:%s (%s)' % ( s.ip, s.port, s.weight ) else: name = 'unix:%s (%s)' % ( s.address, s.weight ) serverData = {} data.append(( name, serverData )) s.send_cmd('stats items') readline = s.readline while 1: line = readline() if not line or line.strip() == 'END': break item = line.split(' ', 2) #0 = STAT, 1 = ITEM, 2 = Value slab = item[1].split(':', 2) #0 = items, 1 = Slab #, 2 = Name if not serverData.has_key(slab[1]): serverData[slab[1]] = {} serverData[slab[1]][slab[2]] = item[2] return data def flush_all(self): 'Expire all data currently in the memcache servers.' for s in self.servers: if not s.connect(): continue s.send_cmd('flush_all') s.expect("OK") def debuglog(self, str): if self.debug: sys.stderr.write("MemCached: %s\n" % str) def _statlog(self, func): if not self.stats.has_key(func): self.stats[func] = 1 else: self.stats[func] += 1 def forget_dead_hosts(self): """ Reset every host in the pool to an "alive" state. """ for s in self.servers: s.deaduntil = 0 def _init_buckets(self): self.buckets = [] for server in self.servers: for i in range(server.weight): self.buckets.append(server) def _get_server(self, key): if type(key) == types.TupleType: serverhash, key = key else: serverhash = serverHashFunction(key) for i in range(Client._SERVER_RETRIES): server = self.buckets[serverhash % len(self.buckets)] if server.connect(): #print "(using server %s)" % server, return server, key serverhash = serverHashFunction(str(serverhash) + str(i)) return None, None def disconnect_all(self): for s in self.servers: s.close_socket() def delete_multi(self, keys, time=0, key_prefix=''): ''' Delete multiple keys in the memcache doing just one query. >>> notset_keys = mc.set_multi({'key1' : 'val1', 'key2' : 'val2'}) >>> mc.get_multi(['key1', 'key2']) == {'key1' : 'val1', 'key2' : 'val2'} 1 >>> mc.delete_multi(['key1', 'key2']) 1 >>> mc.get_multi(['key1', 'key2']) == {} 1 This method is recommended over iterated regular L{delete}s as it reduces total latency, since your app doesn't have to wait for each round-trip of L{delete} before sending the next one. @param keys: An iterable of keys to clear @param time: number of seconds any subsequent set / update commands should fail. Defaults to 0 for no delay. @param key_prefix: Optional string to prepend to each key when sending to memcache. See docs for L{get_multi} and L{set_multi}. @return: 1 if no failure in communication with any memcacheds. @rtype: int ''' self._statlog('delete_multi') server_keys, prefixed_to_orig_key = self._map_and_prefix_keys(keys, key_prefix) # send out all requests on each server before reading anything dead_servers = [] rc = 1 for server in server_keys.iterkeys(): bigcmd = [] write = bigcmd.append if time != None: for key in server_keys[server]: # These are mangled keys write("delete %s %d\r\n" % (key, time)) else: for key in server_keys[server]: # These are mangled keys write("delete %s\r\n" % key) try: server.send_cmds(''.join(bigcmd)) except socket.error, msg: rc = 0 if type(msg) is types.TupleType: msg = msg[1] server.mark_dead(msg) dead_servers.append(server) # if any servers died on the way, don't expect them to respond. for server in dead_servers: del server_keys[server] notstored = [] # original keys. for server, keys in server_keys.iteritems(): try: for key in keys: server.expect("DELETED") except socket.error, msg: if type(msg) is types.TupleType: msg = msg[1] server.mark_dead(msg) rc = 0 return rc def delete(self, key, time=0): '''Deletes a key from the memcache. @return: Nonzero on success. @param time: number of seconds any subsequent set / update commands should fail. Defaults to 0 for no delay. @rtype: int ''' check_key(key) server, key = self._get_server(key) if not server: return 0 self._statlog('delete') if time != None: cmd = "delete %s %d" % (key, time) else: cmd = "delete %s" % key try: server.send_cmd(cmd) server.expect("DELETED") except socket.error, msg: if type(msg) is types.TupleType: msg = msg[1] server.mark_dead(msg) return 0 return 1 def incr(self, key, delta=1): """ Sends a command to the server to atomically increment the value for C{key} by C{delta}, or by 1 if C{delta} is unspecified. Returns None if C{key} doesn't exist on server, otherwise it returns the new value after incrementing. Note that the value for C{key} must already exist in the memcache, and it must be the string representation of an integer. >>> mc.set("counter", "20") # returns 1, indicating success 1 >>> mc.incr("counter") 21 >>> mc.incr("counter") 22 Overflow on server is not checked. Be aware of values approaching 2**32. See L{decr}. @param delta: Integer amount to increment by (should be zero or greater). @return: New value after incrementing. @rtype: int """ return self._incrdecr("incr", key, delta) def decr(self, key, delta=1): """ Like L{incr}, but decrements. Unlike L{incr}, underflow is checked and new values are capped at 0. If server value is 1, a decrement of 2 returns 0, not -1. @param delta: Integer amount to decrement by (should be zero or greater). @return: New value after decrementing. @rtype: int """ return self._incrdecr("decr", key, delta) def _incrdecr(self, cmd, key, delta): check_key(key) server, key = self._get_server(key) if not server: return 0 self._statlog(cmd) cmd = "%s %s %d" % (cmd, key, delta) try: server.send_cmd(cmd) line = server.readline() return int(line) except ValueError: return None except socket.error, msg: if type(msg) is types.TupleType: msg = msg[1] server.mark_dead(msg) return None def add(self, key, val, time = 0, min_compress_len = 0): ''' Add new key with value. Like L{set}, but only stores in memcache if the key doesn't already exist. @return: Nonzero on success. @rtype: int ''' return self._set("add", key, val, time, min_compress_len) def append(self, key, val, time=0, min_compress_len=0): '''Append the value to the end of the existing key's value. Only stores in memcache if key already exists. Also see L{prepend}. @return: Nonzero on success. @rtype: int ''' return self._set("append", key, val, time, min_compress_len) def prepend(self, key, val, time=0, min_compress_len=0): '''Prepend the value to the beginning of the existing key's value. Only stores in memcache if key already exists. Also see L{append}. @return: Nonzero on success. @rtype: int ''' return self._set("prepend", key, val, time, min_compress_len) def replace(self, key, val, time=0, min_compress_len=0): '''Replace existing key with value. Like L{set}, but only stores in memcache if the key already exists. The opposite of L{add}. @return: Nonzero on success. @rtype: int ''' return self._set("replace", key, val, time, min_compress_len) def set(self, key, val, time=0, min_compress_len=0): '''Unconditionally sets a key to a given value in the memcache. The C{key} can optionally be an tuple, with the first element being the server hash value and the second being the key. If you want to avoid making this module calculate a hash value. You may prefer, for example, to keep all of a given user's objects on the same memcache server, so you could use the user's unique id as the hash value. @return: Nonzero on success. @rtype: int @param time: Tells memcached the time which this value should expire, either as a delta number of seconds, or an absolute unix time-since-the-epoch value. See the memcached protocol docs section "Storage Commands" for more info on <exptime>. We default to 0 == cache forever. @param min_compress_len: The threshold length to kick in auto-compression of the value using the zlib.compress() routine. If the value being cached is a string, then the length of the string is measured, else if the value is an object, then the length of the pickle result is measured. If the resulting attempt at compression yeilds a larger string than the input, then it is discarded. For backwards compatability, this parameter defaults to 0, indicating don't ever try to compress. ''' return self._set("set", key, val, time, min_compress_len) def _map_and_prefix_keys(self, key_iterable, key_prefix): """Compute the mapping of server (_Host instance) -> list of keys to stuff onto that server, as well as the mapping of prefixed key -> original key. """ # Check it just once ... key_extra_len=len(key_prefix) if key_prefix: check_key(key_prefix) # server (_Host) -> list of unprefixed server keys in mapping server_keys = {} prefixed_to_orig_key = {} # build up a list for each server of all the keys we want. for orig_key in key_iterable: if type(orig_key) is types.TupleType: # Tuple of hashvalue, key ala _get_server(). Caller is essentially telling us what server to stuff this on. # Ensure call to _get_server gets a Tuple as well. str_orig_key = str(orig_key[1]) server, key = self._get_server((orig_key[0], key_prefix + str_orig_key)) # Gotta pre-mangle key before hashing to a server. Returns the mangled key. else: str_orig_key = str(orig_key) # set_multi supports int / long keys. server, key = self._get_server(key_prefix + str_orig_key) # Now check to make sure key length is proper ... check_key(str_orig_key, key_extra_len=key_extra_len) if not server: continue if not server_keys.has_key(server): server_keys[server] = [] server_keys[server].append(key) prefixed_to_orig_key[key] = orig_key return (server_keys, prefixed_to_orig_key) def set_multi(self, mapping, time=0, key_prefix='', min_compress_len=0): ''' Sets multiple keys in the memcache doing just one query. >>> notset_keys = mc.set_multi({'key1' : 'val1', 'key2' : 'val2'}) >>> mc.get_multi(['key1', 'key2']) == {'key1' : 'val1', 'key2' : 'val2'} 1 This method is recommended over regular L{set} as it lowers the number of total packets flying around your network, reducing total latency, since your app doesn't have to wait for each round-trip of L{set} before sending the next one. @param mapping: A dict of key/value pairs to set. @param time: Tells memcached the time which this value should expire, either as a delta number of seconds, or an absolute unix time-since-the-epoch value. See the memcached protocol docs section "Storage Commands" for more info on <exptime>. We default to 0 == cache forever. @param key_prefix: Optional string to prepend to each key when sending to memcache. Allows you to efficiently stuff these keys into a pseudo-namespace in memcache: >>> notset_keys = mc.set_multi({'key1' : 'val1', 'key2' : 'val2'}, key_prefix='subspace_') >>> len(notset_keys) == 0 True >>> mc.get_multi(['subspace_key1', 'subspace_key2']) == {'subspace_key1' : 'val1', 'subspace_key2' : 'val2'} True Causes key 'subspace_key1' and 'subspace_key2' to be set. Useful in conjunction with a higher-level layer which applies namespaces to data in memcache. In this case, the return result would be the list of notset original keys, prefix not applied. @param min_compress_len: The threshold length to kick in auto-compression of the value using the zlib.compress() routine. If the value being cached is a string, then the length of the string is measured, else if the value is an object, then the length of the pickle result is measured. If the resulting attempt at compression yeilds a larger string than the input, then it is discarded. For backwards compatability, this parameter defaults to 0, indicating don't ever try to compress. @return: List of keys which failed to be stored [ memcache out of memory, etc. ]. @rtype: list ''' self._statlog('set_multi') server_keys, prefixed_to_orig_key = self._map_and_prefix_keys(mapping.iterkeys(), key_prefix) # send out all requests on each server before reading anything dead_servers = [] for server in server_keys.iterkeys(): bigcmd = [] write = bigcmd.append try: for key in server_keys[server]: # These are mangled keys store_info = self._val_to_store_info(mapping[prefixed_to_orig_key[key]], min_compress_len) write("set %s %d %d %d\r\n%s\r\n" % (key, store_info[0], time, store_info[1], store_info[2])) server.send_cmds(''.join(bigcmd)) except socket.error, msg: if type(msg) is types.TupleType: msg = msg[1] server.mark_dead(msg) dead_servers.append(server) # if any servers died on the way, don't expect them to respond. for server in dead_servers: del server_keys[server] # short-circuit if there are no servers, just return all keys if not server_keys: return(mapping.keys()) notstored = [] # original keys. for server, keys in server_keys.iteritems(): try: for key in keys: line = server.readline() if line == 'STORED': continue else: notstored.append(prefixed_to_orig_key[key]) #un-mangle. except (_Error, socket.error), msg: if type(msg) is types.TupleType: msg = msg[1] server.mark_dead(msg) return notstored def _val_to_store_info(self, val, min_compress_len): """ Transform val to a storable representation, returning a tuple of the flags, the length of the new value, and the new value itself. """ flags = 0 if isinstance(val, str): pass elif isinstance(val, int): flags |= Client._FLAG_INTEGER val = "%d" % val # force no attempt to compress this silly string. min_compress_len = 0 elif isinstance(val, long): flags |= Client._FLAG_LONG val = "%d" % val # force no attempt to compress this silly string. min_compress_len = 0 else: flags |= Client._FLAG_PICKLE file = StringIO() if self.picklerIsKeyword: pickler = self.pickler(file, protocol = self.pickleProtocol) else: pickler = self.pickler(file, self.pickleProtocol) if self.persistent_id: pickler.persistent_id = self.persistent_id pickler.dump(val) val = file.getvalue() lv = len(val) # We should try to compress if min_compress_len > 0 and we could # import zlib and this string is longer than our min threshold. if min_compress_len and _supports_compress and lv > min_compress_len: comp_val = compress(val) # Only retain the result if the compression result is smaller # than the original. if len(comp_val) < lv: flags |= Client._FLAG_COMPRESSED val = comp_val # silently do not store if value length exceeds maximum if len(val) >= SERVER_MAX_VALUE_LENGTH: return(0) return (flags, len(val), val) def _set(self, cmd, key, val, time, min_compress_len = 0): check_key(key) server, key = self._get_server(key) if not server: return 0 self._statlog(cmd) store_info = self._val_to_store_info(val, min_compress_len) if not store_info: return(0) fullcmd = "%s %s %d %d %d\r\n%s" % (cmd, key, store_info[0], time, store_info[1], store_info[2]) try: server.send_cmd(fullcmd) return(server.expect("STORED") == "STORED") except socket.error, msg: if type(msg) is types.TupleType: msg = msg[1] server.mark_dead(msg) return 0 def get(self, key): '''Retrieves a key from the memcache. @return: The value or None. ''' check_key(key) server, key = self._get_server(key) if not server: return None self._statlog('get') try: server.send_cmd("get %s" % key) rkey, flags, rlen, = self._expectvalue(server) if not rkey: return None value = self._recv_value(server, flags, rlen) server.expect("END") except (_Error, socket.error), msg: if type(msg) is types.TupleType: msg = msg[1] server.mark_dead(msg) return None return value def get_multi(self, keys, key_prefix=''): ''' Retrieves multiple keys from the memcache doing just one query. >>> success = mc.set("foo", "bar") >>> success = mc.set("baz", 42) >>> mc.get_multi(["foo", "baz", "foobar"]) == {"foo": "bar", "baz": 42} 1 >>> mc.set_multi({'k1' : 1, 'k2' : 2}, key_prefix='pfx_') == [] 1 This looks up keys 'pfx_k1', 'pfx_k2', ... . Returned dict will just have unprefixed keys 'k1', 'k2'. >>> mc.get_multi(['k1', 'k2', 'nonexist'], key_prefix='pfx_') == {'k1' : 1, 'k2' : 2} 1 get_mult [ and L{set_multi} ] can take str()-ables like ints / longs as keys too. Such as your db pri key fields. They're rotored through str() before being passed off to memcache, with or without the use of a key_prefix. In this mode, the key_prefix could be a table name, and the key itself a db primary key number. >>> mc.set_multi({42: 'douglass adams', 46 : 'and 2 just ahead of me'}, key_prefix='numkeys_') == [] 1 >>> mc.get_multi([46, 42], key_prefix='numkeys_') == {42: 'douglass adams', 46 : 'and 2 just ahead of me'} 1 This method is recommended over regular L{get} as it lowers the number of total packets flying around your network, reducing total latency, since your app doesn't have to wait for each round-trip of L{get} before sending the next one. See also L{set_multi}. @param keys: An array of keys. @param key_prefix: A string to prefix each key when we communicate with memcache. Facilitates pseudo-namespaces within memcache. Returned dictionary keys will not have this prefix. @return: A dictionary of key/value pairs that were available. If key_prefix was provided, the keys in the retured dictionary will not have it present. ''' self._statlog('get_multi') server_keys, prefixed_to_orig_key = self._map_and_prefix_keys(keys, key_prefix) # send out all requests on each server before reading anything dead_servers = [] for server in server_keys.iterkeys(): try: server.send_cmd("get %s" % " ".join(server_keys[server])) except socket.error, msg: if type(msg) is types.TupleType: msg = msg[1] server.mark_dead(msg) dead_servers.append(server) # if any servers died on the way, don't expect them to respond. for server in dead_servers: del server_keys[server] retvals = {} for server in server_keys.iterkeys(): try: line = server.readline() while line and line != 'END': rkey, flags, rlen = self._expectvalue(server, line) # Bo Yang reports that this can sometimes be None if rkey is not None: val = self._recv_value(server, flags, rlen) retvals[prefixed_to_orig_key[rkey]] = val # un-prefix returned key. line = server.readline() except (_Error, socket.error), msg: if type(msg) is types.TupleType: msg = msg[1] server.mark_dead(msg) return retvals def _expectvalue(self, server, line=None): if not line: line = server.readline() if line[:5] == 'VALUE': resp, rkey, flags, len = line.split() flags = int(flags) rlen = int(len) return (rkey, flags, rlen) else: return (None, None, None) def _recv_value(self, server, flags, rlen): rlen += 2 # include \r\n buf = server.recv(rlen) if len(buf) != rlen: raise _Error("received %d bytes when expecting %d" % (len(buf), rlen)) if len(buf) == rlen: buf = buf[:-2] # strip \r\n if flags & Client._FLAG_COMPRESSED: buf = decompress(buf) if flags == 0 or flags == Client._FLAG_COMPRESSED: # Either a bare string or a compressed string now decompressed... val = buf elif flags & Client._FLAG_INTEGER: val = int(buf) elif flags & Client._FLAG_LONG: val = long(buf) elif flags & Client._FLAG_PICKLE: try: file = StringIO(buf) unpickler = self.unpickler(file) if self.persistent_load: unpickler.persistent_load = self.persistent_load val = unpickler.load() except Exception, e: self.debuglog('Pickle error: %s\n' % e) val = None else: self.debuglog("unknown flags on get: %x\n" % flags) return val class _Host: _DEAD_RETRY = 30 # number of seconds before retrying a dead server. _SOCKET_TIMEOUT = 3 # number of seconds before sockets timeout. def __init__(self, host, debugfunc=None): if isinstance(host, types.TupleType): host, self.weight = host else: self.weight = 1 # parse the connection string m = re.match(r'^(?P<proto>unix):(?P<path>.*)$', host) if not m: m = re.match(r'^(?P<proto>inet):' r'(?P<host>[^:]+)(:(?P<port>[0-9]+))?$', host) if not m: m = re.match(r'^(?P<host>[^:]+):(?P<port>[0-9]+)$', host) if not m: raise ValueError('Unable to parse connection string: "%s"' % host) hostData = m.groupdict() if hostData.get('proto') == 'unix': self.family = socket.AF_UNIX self.address = hostData['path'] else: self.family = socket.AF_INET self.ip = hostData['host'] self.port = int(hostData.get('port', 11211)) self.address = ( self.ip, self.port ) if not debugfunc: debugfunc = lambda x: x self.debuglog = debugfunc self.deaduntil = 0 self.socket = None self.buffer = '' def _check_dead(self): if self.deaduntil and self.deaduntil > time.time(): return 1 self.deaduntil = 0 return 0 def connect(self): if self._get_socket(): return 1 return 0 def mark_dead(self, reason): self.debuglog("MemCache: %s: %s. Marking dead." % (self, reason)) self.deaduntil = time.time() + _Host._DEAD_RETRY self.close_socket() def _get_socket(self): if self._check_dead(): return None if self.socket: return self.socket s = socket.socket(self.family, socket.SOCK_STREAM) if hasattr(s, 'settimeout'): s.settimeout(self._SOCKET_TIMEOUT) try: s.connect(self.address) except socket.timeout, msg: self.mark_dead("connect: %s" % msg) return None except socket.error, msg: if type(msg) is types.TupleType: msg = msg[1] self.mark_dead("connect: %s" % msg[1]) return None self.socket = s self.buffer = '' return s def close_socket(self): if self.socket: self.socket.close() self.socket = None def send_cmd(self, cmd): self.socket.sendall(cmd + '\r\n') def send_cmds(self, cmds): """ cmds already has trailing \r\n's applied """ self.socket.sendall(cmds) def readline(self): buf = self.buffer recv = self.socket.recv while True: index = buf.find('\r\n') if index >= 0: break data = recv(4096) if not data: self.mark_dead('Connection closed while reading from %s' % repr(self)) break buf += data if index >= 0: self.buffer = buf[index+2:] buf = buf[:index] else: self.buffer = '' return buf def expect(self, text): line = self.readline() if line != text: self.debuglog("while expecting '%s', got unexpected response '%s'" % (text, line)) return line def recv(self, rlen): self_socket_recv = self.socket.recv buf = self.buffer while len(buf) < rlen: foo = self_socket_recv(4096) buf += foo if len(foo) == 0: raise _Error, ( 'Read %d bytes, expecting %d, ' 'read returned 0 length bytes' % ( len(buf), rlen )) self.buffer = buf[rlen:] return buf[:rlen] def __str__(self): d = '' if self.deaduntil: d = " (dead until %d)" % self.deaduntil if self.family == socket.AF_INET: return "inet:%s:%d%s" % (self.address[0], self.address[1], d) else: return "unix:%s%s" % (self.address, d) def check_key(key, key_extra_len=0): """Checks sanity of key. Fails if: Key length is > SERVER_MAX_KEY_LENGTH (Raises MemcachedKeyLength). Contains control characters (Raises MemcachedKeyCharacterError). Is not a string (Raises MemcachedStringEncodingError) Is an unicode string (Raises MemcachedStringEncodingError) Is not a string (Raises MemcachedKeyError) Is None (Raises MemcachedKeyError) """ if type(key) == types.TupleType: key = key[1] if not key: raise Client.MemcachedKeyNoneError, ("Key is None") if isinstance(key, unicode): raise Client.MemcachedStringEncodingError, ("Keys must be str()'s, not " "unicode. Convert your unicode strings using " "mystring.encode(charset)!") if not isinstance(key, str): raise Client.MemcachedKeyTypeError, ("Key must be str()'s") if isinstance(key, basestring): if len(key) + key_extra_len > SERVER_MAX_KEY_LENGTH: raise Client.MemcachedKeyLengthError, ("Key length is > %s" % SERVER_MAX_KEY_LENGTH) for char in key: if ord(char) < 32 or ord(char) == 127: raise Client.MemcachedKeyCharacterError, "Control characters not allowed" def _doctest(): import doctest, memcache servers = ["127.0.0.1:11211"] mc = Client(servers, debug=1) globs = {"mc": mc} return doctest.testmod(memcache, globs=globs) if __name__ == "__main__": print "Testing docstrings..." _doctest() print "Running tests:" print serverList = [["127.0.0.1:11211"]] if '--do-unix' in sys.argv: serverList.append([os.path.join(os.getcwd(), 'memcached.socket')]) for servers in serverList: mc = Client(servers, debug=1) def to_s(val): if not isinstance(val, types.StringTypes): return "%s (%s)" % (val, type(val)) return "%s" % val def test_setget(key, val): print "Testing set/get {'%s': %s} ..." % (to_s(key), to_s(val)), mc.set(key, val) newval = mc.get(key) if newval == val: print "OK" return 1 else: print "FAIL" return 0 class FooStruct: def __init__(self): self.bar = "baz" def __str__(self): return "A FooStruct" def __eq__(self, other): if isinstance(other, FooStruct): return self.bar == other.bar return 0 test_setget("a_string", "some random string") test_setget("an_integer", 42) if test_setget("long", long(1<<30)): print "Testing delete ...", if mc.delete("long"): print "OK" else: print "FAIL" print "Testing get_multi ...", print mc.get_multi(["a_string", "an_integer"]) print "Testing get(unknown value) ...", print to_s(mc.get("unknown_value")) f = FooStruct() test_setget("foostruct", f) print "Testing incr ...", x = mc.incr("an_integer", 1) if x == 43: print "OK" else: print "FAIL" print "Testing decr ...", x = mc.decr("an_integer", 1) if x == 42: print "OK" else: print "FAIL" # sanity tests print "Testing sending spaces...", try: x = mc.set("this has spaces", 1) except Client.MemcachedKeyCharacterError, msg: print "OK" else: print "FAIL" print "Testing sending control characters...", try: x = mc.set("this\x10has\x11control characters\x02", 1) except Client.MemcachedKeyCharacterError, msg: print "OK" else: print "FAIL" print "Testing using insanely long key...", try: x = mc.set('a'*SERVER_MAX_KEY_LENGTH + 'aaaa', 1) except Client.MemcachedKeyLengthError, msg: print "OK" else: print "FAIL" print "Testing sending a unicode-string key...", try: x = mc.set(u'keyhere', 1) except Client.MemcachedStringEncodingError, msg: print "OK", else: print "FAIL", try: x = mc.set((u'a'*SERVER_MAX_KEY_LENGTH).encode('utf-8'), 1) except: print "FAIL", else: print "OK", import pickle s = pickle.loads('V\\u4f1a\np0\n.') try: x = mc.set((s*SERVER_MAX_KEY_LENGTH).encode('utf-8'), 1) except Client.MemcachedKeyLengthError: print "OK" else: print "FAIL" print "Testing using a value larger than the memcached value limit...", x = mc.set('keyhere', 'a'*SERVER_MAX_VALUE_LENGTH) if mc.get('keyhere') == None: print "OK", else: print "FAIL", x = mc.set('keyhere', 'a'*SERVER_MAX_VALUE_LENGTH + 'aaa') if mc.get('keyhere') == None: print "OK" else: print "FAIL" print "Testing set_multi() with no memcacheds running", mc.disconnect_all() errors = mc.set_multi({'keyhere' : 'a', 'keythere' : 'b'}) if errors != []: print "FAIL" else: print "OK" print "Testing delete_multi() with no memcacheds running", mc.disconnect_all() ret = mc.delete_multi({'keyhere' : 'a', 'keythere' : 'b'}) if ret != 1: print "FAIL" else: print "OK" # vim: ts=4 sw=4 et :
Python
from gluon.contrib.memcache.memcache import Client from gluon.cache import CacheAbstract import time """ examle of usage: cache.memcache = MemcacheClient(request,[127.0.0.1:11211],debug=true) """ import cPickle as pickle import thread locker = thread.allocate_lock() def MemcacheClient(*a, **b): locker.acquire() try: if not hasattr(MemcacheClient, '__mc_instance'): MemcacheClient.__mc_instance = _MemcacheClient(*a, **b) finally: locker.release() return MemcacheClient.__mc_instance class _MemcacheClient(Client): meta_storage = {} def __init__(self, request, servers, debug=0, pickleProtocol=0, pickler=pickle.Pickler, unpickler=pickle.Unpickler, pload=None, pid=None): self.request=request if request: app = request.application else: app = '' Client.__init__(self, servers, debug, pickleProtocol, pickler, unpickler, pload, pid) if not app in self.meta_storage: self.storage = self.meta_storage[app] = { CacheAbstract.cache_stats_name: { 'hit_total': 0, 'misses': 0, }} else: self.storage = self.meta_storage[app] def __call__(self, key, f, time_expire=300): if time_expire == None: time_expire = 10**10 # this must be commented because get and set are redefined # key = self.__keyFormat__(key) value = None obj = self.get(key) if obj: value = obj elif f is None: if obj: self.delete(key) else: value = f() self.set(key, value, time_expire) return value def increment(self, key, value=1, time_expire=300): newKey = self.__keyFormat__(key) obj = self.get(newKey) if obj: return Client.incr(self, newKey, value) else: self.set(newKey, value, time_expire) return value def set(self, key, value, time_expire=300): newKey = self.__keyFormat__(key) return Client.set(self, newKey, value, time_expire) def get(self, key): newKey = self.__keyFormat__(key) return Client.get(self, newKey) def delete(self, key): newKey = self.__keyFormat__(key) return Client.delete(self, newKey) def __keyFormat__(self, key): return '%s/%s' % (self.request.application, key.replace(' ', '_'))
Python
# (c) 2007 Chris AtLee <chris@atlee.ca> # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license.php """ PAM module for python Provides an authenticate function that will allow the caller to authenticate a user against the Pluggable Authentication Modules (PAM) on the system. Implemented using ctypes, so no compilation is necessary. """ __all__ = ['authenticate'] from ctypes import CDLL, POINTER, Structure, CFUNCTYPE, cast, pointer, sizeof from ctypes import c_void_p, c_uint, c_char_p, c_char, c_int from ctypes.util import find_library LIBPAM = CDLL(find_library("pam")) LIBC = CDLL(find_library("c")) CALLOC = LIBC.calloc CALLOC.restype = c_void_p CALLOC.argtypes = [c_uint, c_uint] STRDUP = LIBC.strdup STRDUP.argstypes = [c_char_p] STRDUP.restype = POINTER(c_char) # NOT c_char_p !!!! # Various constants PAM_PROMPT_ECHO_OFF = 1 PAM_PROMPT_ECHO_ON = 2 PAM_ERROR_MSG = 3 PAM_TEXT_INFO = 4 class PamHandle(Structure): """wrapper class for pam_handle_t""" _fields_ = [ ("handle", c_void_p) ] def __init__(self): Structure.__init__(self) self.handle = 0 class PamMessage(Structure): """wrapper class for pam_message structure""" _fields_ = [ ("msg_style", c_int), ("msg", c_char_p), ] def __repr__(self): return "<PamMessage %i '%s'>" % (self.msg_style, self.msg) class PamResponse(Structure): """wrapper class for pam_response structure""" _fields_ = [ ("resp", c_char_p), ("resp_retcode", c_int), ] def __repr__(self): return "<PamResponse %i '%s'>" % (self.resp_retcode, self.resp) CONV_FUNC = CFUNCTYPE(c_int, c_int, POINTER(POINTER(PamMessage)), POINTER(POINTER(PamResponse)), c_void_p) class PamConv(Structure): """wrapper class for pam_conv structure""" _fields_ = [ ("conv", CONV_FUNC), ("appdata_ptr", c_void_p) ] PAM_START = LIBPAM.pam_start PAM_START.restype = c_int PAM_START.argtypes = [c_char_p, c_char_p, POINTER(PamConv), POINTER(PamHandle)] PAM_AUTHENTICATE = LIBPAM.pam_authenticate PAM_AUTHENTICATE.restype = c_int PAM_AUTHENTICATE.argtypes = [PamHandle, c_int] def authenticate(username, password, service='login'): """Returns True if the given username and password authenticate for the given service. Returns False otherwise ``username``: the username to authenticate ``password``: the password in plain text ``service``: the PAM service to authenticate against. Defaults to 'login'""" @CONV_FUNC def my_conv(n_messages, messages, p_response, app_data): """Simple conversation function that responds to any prompt where the echo is off with the supplied password""" # Create an array of n_messages response objects addr = CALLOC(n_messages, sizeof(PamResponse)) p_response[0] = cast(addr, POINTER(PamResponse)) for i in range(n_messages): if messages[i].contents.msg_style == PAM_PROMPT_ECHO_OFF: pw_copy = STRDUP(str(password)) p_response.contents[i].resp = cast(pw_copy, c_char_p) p_response.contents[i].resp_retcode = 0 return 0 handle = PamHandle() conv = PamConv(my_conv, 0) retval = PAM_START(service, username, pointer(conv), pointer(handle)) if retval != 0: # TODO: This is not an authentication error, something # has gone wrong starting up PAM return False retval = PAM_AUTHENTICATE(handle, 0) return retval == 0 if __name__ == "__main__": import getpass print authenticate(getpass.getuser(), getpass.getpass())
Python
#!/usr/bin/python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Modified by Massimo Di Pierro so it works with and without GAE with web2py # the modified version of this file is still released under the original Apache license # and it is not released under the web2py license. # # This should be compatible with the Apache license since it states: # "For the purposes of this License, Derivative Works shall not include works # that remain separable from, or merely link (or bind by name) to the interfaces of, # the Work and Derivative Works thereof." # # In fact this file is Apache-licensed and it is separable from the rest of web2py. """ An interactive, stateful AJAX shell that runs Python code on the server. """ import logging import new import os import cPickle import sys import traceback import types import wsgiref.handlers import StringIO import threading locker = threading.RLock() # Set to True if stack traces should be shown in the browser, etc. _DEBUG = True # The entity kind for shell historys. Feel free to rename to suit your app. _HISTORY_KIND = '_Shell_History' # Types that can't be pickled. UNPICKLABLE_TYPES = ( types.ModuleType, types.TypeType, types.ClassType, types.FunctionType, ) # Unpicklable statements to seed new historys with. INITIAL_UNPICKLABLES = [ 'import logging', 'import os', 'import sys', ] class History: """A shell history. Stores the history's globals. Each history globals is stored in one of two places: If the global is picklable, it's stored in the parallel globals and global_names list properties. (They're parallel lists to work around the unfortunate fact that the datastore can't store dictionaries natively.) If the global is not picklable (e.g. modules, classes, and functions), or if it was created by the same statement that created an unpicklable global, it's not stored directly. Instead, the statement is stored in the unpicklables list property. On each request, before executing the current statement, the unpicklable statements are evaluated to recreate the unpicklable globals. The unpicklable_names property stores all of the names of globals that were added by unpicklable statements. When we pickle and store the globals after executing a statement, we skip the ones in unpicklable_names. Using Text instead of string is an optimization. We don't query on any of these properties, so they don't need to be indexed. """ global_names = [] globals = [] unpicklable_names = [] unpicklables = [] def set_global(self, name, value): """Adds a global, or updates it if it already exists. Also removes the global from the list of unpicklable names. Args: name: the name of the global to remove value: any picklable value """ blob = cPickle.dumps(value) if name in self.global_names: index = self.global_names.index(name) self.globals[index] = blob else: self.global_names.append(name) self.globals.append(blob) self.remove_unpicklable_name(name) def remove_global(self, name): """Removes a global, if it exists. Args: name: string, the name of the global to remove """ if name in self.global_names: index = self.global_names.index(name) del self.global_names[index] del self.globals[index] def globals_dict(self): """Returns a dictionary view of the globals. """ return dict((name, cPickle.loads(val)) for name, val in zip(self.global_names, self.globals)) def add_unpicklable(self, statement, names): """Adds a statement and list of names to the unpicklables. Also removes the names from the globals. Args: statement: string, the statement that created new unpicklable global(s). names: list of strings; the names of the globals created by the statement. """ self.unpicklables.append(statement) for name in names: self.remove_global(name) if name not in self.unpicklable_names: self.unpicklable_names.append(name) def remove_unpicklable_name(self, name): """Removes a name from the list of unpicklable names, if it exists. Args: name: string, the name of the unpicklable global to remove """ if name in self.unpicklable_names: self.unpicklable_names.remove(name) def represent(obj): """Returns a string representing the given object's value, which should allow the code below to determine whether the object changes over time. """ try: return cPickle.dumps(obj) except: return repr(obj) def run(history, statement, env={}): """ Evaluates a python statement in a given history and returns the result. """ history.unpicklables = INITIAL_UNPICKLABLES # extract the statement to be run if not statement: return '' # the python compiler doesn't like network line endings statement = statement.replace('\r\n', '\n') # add a couple newlines at the end of the statement. this makes # single-line expressions such as 'class Foo: pass' evaluate happily. statement += '\n\n' # log and compile the statement up front try: logging.info('Compiling and evaluating:\n%s' % statement) compiled = compile(statement, '<string>', 'single') except: return str(traceback.format_exc()) # create a dedicated module to be used as this statement's __main__ statement_module = new.module('__main__') # use this request's __builtin__, since it changes on each request. # this is needed for import statements, among other things. import __builtin__ statement_module.__builtins__ = __builtin__ # load the history from the datastore history = History() # swap in our custom module for __main__. then unpickle the history # globals, run the statement, and re-pickle the history globals, all # inside it. old_main = sys.modules.get('__main__') output = StringIO.StringIO() try: sys.modules['__main__'] = statement_module statement_module.__name__ = '__main__' statement_module.__dict__.update(env) # re-evaluate the unpicklables for code in history.unpicklables: exec code in statement_module.__dict__ # re-initialize the globals for name, val in history.globals_dict().items(): try: statement_module.__dict__[name] = val except: msg = 'Dropping %s since it could not be unpickled.\n' % name output.write(msg) logging.warning(msg + traceback.format_exc()) history.remove_global(name) # run! old_globals = dict((key,represent(value)) for key,value in statement_module.__dict__.items()) try: old_stdout, old_stderr = sys.stdout, sys.stderr try: sys.stderr = sys.stdout = output locker.acquire() exec compiled in statement_module.__dict__ finally: locker.release() sys.stdout, sys.stderr = old_stdout, old_stderr except: output.write(str(traceback.format_exc())) return output.getvalue() # extract the new globals that this statement added new_globals = {} for name, val in statement_module.__dict__.items(): if name not in old_globals or represent(val) != old_globals[name]: new_globals[name] = val if True in [isinstance(val, UNPICKLABLE_TYPES) for val in new_globals.values()]: # this statement added an unpicklable global. store the statement and # the names of all of the globals it added in the unpicklables. history.add_unpicklable(statement, new_globals.keys()) logging.debug('Storing this statement as an unpicklable.') else: # this statement didn't add any unpicklables. pickle and store the # new globals back into the datastore. for name, val in new_globals.items(): if not name.startswith('__'): history.set_global(name, val) finally: sys.modules['__main__'] = old_main return output.getvalue() if __name__=='__main__': history=History() while True: print run(history, raw_input('>>> ')).rstrip()
Python
def autoretry_datastore_timeouts(attempts=5.0, interval=0.1, exponent=2.0): """ Copyright (C) 2009 twitter.com/rcb Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ====================================================================== This function wraps the AppEngine Datastore API to autoretry datastore timeouts at the lowest accessible level. The benefits of this approach are: 1. Small Footprint: Does not monkey with Model internals which may break in future releases. 2. Max Performance: Retrying at this lowest level means serialization and key formatting is not needlessly repeated on each retry. At initialization time, execute this: >>> autoretry_datastore_timeouts() Should only be called once, subsequent calls have no effect. >>> autoretry_datastore_timeouts() # no effect Default (5) attempts: .1, .2, .4, .8, 1.6 seconds Parameters can each be specified as floats. :param attempts: maximum number of times to retry. :param interval: base seconds to sleep between retries. :param exponent: rate of exponential back-off. """ import time, logging from google.appengine.api import apiproxy_stub_map from google.appengine.runtime import apiproxy_errors from google.appengine.datastore import datastore_pb attempts = float(attempts) interval = float(interval) exponent = float(exponent) wrapped = apiproxy_stub_map.MakeSyncCall errors = {datastore_pb.Error.TIMEOUT:'Timeout', datastore_pb.Error.CONCURRENT_TRANSACTION:'TransactionFailedError'} def wrapper(*args, **kwargs): count = 0.0 while True: try: return wrapped(*args, **kwargs) except apiproxy_errors.ApplicationError, err: errno = err.application_error if errno not in errors: raise sleep = (exponent ** count) * interval count += 1.0 if count > attempts: raise msg = "Datastore %s: retry #%d in %s seconds.\n%s" vals = '' if count == 1.0: vals = '\n'.join([str(a) for a in args]) logging.warning(msg % (errors[errno], count, sleep, vals)) time.sleep(sleep) setattr(wrapper, '_autoretry_datastore_timeouts', False) if getattr(wrapped, '_autoretry_datastore_timeouts', True): apiproxy_stub_map.MakeSyncCall = wrapper
Python
from types import StringType, ListType, TupleType from copy import deepcopy from Elements import * DEFAULT_TAB_WIDTH = 720 ParagraphAlignmentMap = { ParagraphPropertySet.LEFT : 'ql', ParagraphPropertySet.RIGHT : 'qr', ParagraphPropertySet.CENTER : 'qc', ParagraphPropertySet.JUSTIFY : 'qj', ParagraphPropertySet.DISTRIBUTE : 'qd' } TabAlignmentMap = { TabPropertySet.LEFT : '', TabPropertySet.RIGHT : 'tqr', TabPropertySet.CENTER : 'tqc', TabPropertySet.DECIMAL : 'tqdec' } TableAlignmentMap = { Table.LEFT : 'trql', Table.RIGHT : 'trqr', Table.CENTER : 'trqc' } CellAlignmentMap = { Cell.ALIGN_TOP : '', # clvertalt Cell.ALIGN_CENTER : 'clvertalc', Cell.ALIGN_BOTTOM : 'clvertalb' } CellFlowMap = { Cell.FLOW_LR_TB : '', # cltxlrtb, Text in a cell flows from left to right and top to bottom (default) Cell.FLOW_RL_TB : 'cltxtbrl', # Text in a cell flows right to left and top to bottom Cell.FLOW_LR_BT : 'cltxbtlr', # Text in a cell flows left to right and bottom to top Cell.FLOW_VERTICAL_LR_TB : 'cltxlrtbv', # Text in a cell flows left to right and top to bottom, vertical Cell.FLOW_VERTICAL_TB_RL : 'cltxtbrlv' } # Text in a cell flows top to bottom and right to left, vertical ShadingPatternMap = { ShadingPropertySet.HORIZONTAL : 'bghoriz', ShadingPropertySet.VERTICAL : 'bgvert', ShadingPropertySet.FORWARD_DIAGONAL : 'bgfdiag', ShadingPropertySet.BACKWARD_DIAGONAL : 'bgbdiag', ShadingPropertySet.VERTICAL_CROSS : 'bgcross', ShadingPropertySet.DIAGONAL_CROSS : 'bgdcross', ShadingPropertySet.DARK_HORIZONTAL : 'bgdkhoriz', ShadingPropertySet.DARK_VERTICAL : 'bgdkvert', ShadingPropertySet.DARK_FORWARD_DIAGONAL : 'bgdkfdiag', ShadingPropertySet.DARK_BACKWARD_DIAGONAL : 'bgdkbdiag', ShadingPropertySet.DARK_VERTICAL_CROSS : 'bgdkcross', ShadingPropertySet.DARK_DIAGONAL_CROSS : 'bgdkdcross' } TabLeaderMap = { TabPropertySet.DOTS : 'tldot', TabPropertySet.HYPHENS : 'tlhyph', TabPropertySet.UNDERLINE : 'tlul', TabPropertySet.THICK_LINE : 'tlth', TabPropertySet.EQUAL_SIGN : 'tleq' } BorderStyleMap = { BorderPropertySet.SINGLE : 'brdrs', BorderPropertySet.DOUBLE : 'brdrth', BorderPropertySet.SHADOWED : 'brdrsh', BorderPropertySet.DOUBLED : 'brdrdb', BorderPropertySet.DOTTED : 'brdrdot', BorderPropertySet.DASHED : 'brdrdash', BorderPropertySet.HAIRLINE : 'brdrhair' } SectionBreakTypeMap = { Section.NONE : 'sbknone', Section.COLUMN : 'sbkcol', Section.PAGE : 'sbkpage', Section.EVEN : 'sbkeven', Section.ODD : 'sbkodd' } class Settings( list ) : def __init__( self ) : super( Settings, self ).__init__() self._append = super( Settings, self ).append def append( self, value, mask=None, fallback=None ) : if (value is not 0) and value in [ False, None, '' ] : if fallback : self._append( self, fallback ) else : if mask : if value is True : value = mask else : value = mask % value self._append( value ) def Join( self ) : if self : return r'\%s' % '\\'.join( self ) return '' def __repr__( self ) : return self.Join() class Renderer : def __init__( self, write_custom_element_callback=None ) : self.character_style_map = {} self.paragraph_style_map = {} self.WriteCustomElement = write_custom_element_callback # # All of the Rend* Functions populate a Settings object with values # def _RendPageProperties( self, section, settings, in_section ) : # this one is different from the others as it takes the settings from a if in_section : #paper_size_code = 'psz%s' paper_width_code = 'pgwsxn%s' paper_height_code = 'pghsxn%s' landscape = 'lndscpsxn' margin_suffix = 'sxn' else : #paper_size_code = 'psz%s' paper_width_code = 'paperw%s' paper_height_code = 'paperh%s' landscape = 'landscape' margin_suffix = '' #settings.append( section.Paper.Code, paper_size_code ) settings.append( section.Paper.Width, paper_width_code ) settings.append( section.Paper.Height, paper_height_code ) if section.Landscape : settings.append( landscape ) if section.FirstPageNumber : settings.append( section.FirstPageNumber, 'pgnstarts%s' ) settings.append( 'pgnrestart' ) self._RendMarginsPropertySet( section.Margins, settings, margin_suffix ) def _RendShadingPropertySet( self, shading_props, settings, prefix='' ) : if not shading_props : return settings.append( shading_props.Shading, prefix + 'shading%s' ) settings.append( ShadingPatternMap.get( shading_props.Pattern, False ) ) settings.append( self._colour_map.get( shading_props.Foreground, False ), prefix + 'cfpat%s' ) settings.append( self._colour_map.get( shading_props.Background, False ), prefix + 'cbpat%s' ) def _RendBorderPropertySet( self, edge_props, settings ) : settings.append( BorderStyleMap[ edge_props.Style ] ) settings.append( edge_props.Width , 'brdrw%s' ) settings.append( self._colour_map.get( edge_props.Colour, False ), 'brdrcf%s' ) settings.append( edge_props.Spacing or False , 'brsp%s' ) def _RendFramePropertySet( self, frame_props, settings, tag_prefix='' ) : if not frame_props : return if frame_props.Top : settings.append( tag_prefix + 'brdrt' ) self._RendBorderPropertySet( frame_props.Top, settings ) if frame_props.Left : settings.append( tag_prefix + 'brdrl' ) self._RendBorderPropertySet( frame_props.Left, settings ) if frame_props.Bottom : settings.append( tag_prefix + 'brdrb' ) self._RendBorderPropertySet( frame_props.Bottom, settings ) if frame_props.Right : settings.append( tag_prefix + 'brdrr' ) self._RendBorderPropertySet( frame_props.Right, settings ) def _RendMarginsPropertySet( self, margin_props, settings, suffix='' ) : if not margin_props : return settings.append( margin_props.Top, 'margt' + suffix + '%s' ) settings.append( margin_props.Left, 'margl' + suffix + '%s' ) settings.append( margin_props.Bottom, 'margb' + suffix + '%s' ) settings.append( margin_props.Right, 'margr' + suffix + '%s' ) def _RendParagraphPropertySet( self, paragraph_props, settings ) : if not paragraph_props : return settings.append( ParagraphAlignmentMap[ paragraph_props.Alignment ] ) settings.append( paragraph_props.SpaceBefore, 'sb%s' ) settings.append( paragraph_props.SpaceAfter, 'sa%s' ) # then we have to find out all of the tabs width = 0 for tab in paragraph_props.Tabs : settings.append( TabAlignmentMap[ tab.Alignment ] ) settings.append( TabLeaderMap.get( tab.Leader, '' ) ) width += tab.Width or DEFAULT_TAB_WIDTH settings.append( 'tx%s' % width ) settings.append( paragraph_props.PageBreakBefore, 'pagebb' ) settings.append( paragraph_props.FirstLineIndent, 'fi%s' ) settings.append( paragraph_props.LeftIndent, 'li%s' ) settings.append( paragraph_props.RightIndent, 'ri%s' ) if paragraph_props.SpaceBetweenLines : if paragraph_props.SpaceBetweenLines < 0 : settings.append( paragraph_props.SpaceBetweenLines, r'sl%s\slmult0' ) else : settings.append( paragraph_props.SpaceBetweenLines, r'sl%s\slmult1' ) def _RendTextPropertySet( self, text_props, settings ) : if not text_props : return if text_props.Expansion : settings.append( text_props.Expansion, 'expndtw%s' ) settings.append( text_props.Bold, 'b' ) settings.append( text_props.Italic, 'i' ) settings.append( text_props.Underline, 'ul' ) settings.append( text_props.DottedUnderline, 'uld' ) settings.append( text_props.DoubleUnderline, 'uldb' ) settings.append( text_props.WordUnderline, 'ulw' ) settings.append( self._font_map.get( text_props.Font, False ), 'f%s' ) settings.append( text_props.Size, 'fs%s' ) settings.append( self._colour_map.get( text_props.Colour, False ), 'cf%s' ) if text_props.Frame : frame = text_props.Frame settings.append( 'chbrdr' ) settings.append( BorderStyleMap[ frame.Style ] ) settings.append( frame.Width , 'brdrw%s' ) settings.append( self._colour_map.get( frame.Colour, False ), 'brdrcf%s' ) # # All of the Write* functions will write to the internal file object # # the _ ones probably don't need to be used by anybody outside # but the other ones like WriteTextElement could be used in the Custom # callback. def Write( self, document, fout ) : # write all of the standard stuff based upon the first document self._doc = document self._fout = fout self._WriteDocument () self._WriteColours () self._WriteFonts () self._WriteStyleSheet() settings = Settings() self._RendPageProperties( self._doc.Sections[ 0 ], settings, in_section=False ) self._write( repr( settings ) ) # handle the simplest case first, we don't need to do anymore mucking around # with section headers, etc we can just rip the document out if len( document.Sections ) == 1 : self._WriteSection( document.Sections[ 0 ], is_first = True, add_header = False ) else : for section_idx, section in enumerate( document.Sections ) : is_first = section_idx == 0 add_header = True self._WriteSection( section, is_first, add_header ) self._write( '}' ) del self._fout, self._doc, self._CurrentStyle def _write( self, data, *params ) : #---------------------------------- # begin modification # by Herbert Weinhandl # to convert accented characters # to their rtf-compatible form #for c in range( 128, 256 ) : # data = data.replace( chr(c), "\'%x" % c) # end modification # # This isn't the right place for this as it is going to do # this loop for all sorts of writes, including settings, control codes, etc. # # I will create a def _WriteText (or something) method that is used when the # actual string that is to be viewed in the document is written, this can then # do the final accented character check. # # I left it here so that I remember to do the right thing when I have time #---------------------------------- if params : data = data % params self._fout.write( data ) def _WriteDocument( self ) : settings = Settings() assert Languages.IsValid ( self._doc.DefaultLanguage ) assert ViewKind.IsValid ( self._doc.ViewKind ) assert ViewZoomKind.IsValid( self._doc.ViewZoomKind ) assert ViewScale.IsValid ( self._doc.ViewScale ) settings.append( self._doc.DefaultLanguage, 'deflang%s' ) settings.append( self._doc.ViewKind , 'viewkind%s' ) settings.append( self._doc.ViewZoomKind , 'viewzk%s' ) settings.append( self._doc.ViewScale , 'viewscale%s' ) self._write( "{\\rtf1\\ansi\\ansicpg1252\\deff0%s\n" % settings ) def _WriteColours( self ) : self._write( r"{\colortbl ;" ) self._colour_map = {} offset = 0 for colour in self._doc.StyleSheet.Colours : self._write( r'\red%s\green%s\blue%s;', colour.Red, colour.Green, colour.Blue ) self._colour_map[ colour ] = offset + 1 offset += 1 self._write( "}\n" ) def _WriteFonts( self ) : self._write( r'{\fonttbl' ) self._font_map = {} offset = 0 for font in self._doc.StyleSheet.Fonts : pitch = '' panose = '' alternate = '' if font.Pitch : pitch = r'\fprq%s' % font.Pitch if font.Panose : panose = r'{\*\panose %s}' % font.Panose if font.Alternate : alternate = r'{\*\falt %s}' % font.Alternate.Name self._write( r'{\f%s\f%s%s\fcharset%s%s %s%s;}', offset, font.Family, pitch, font.CharacterSet, panose, font.Name, alternate ) self._font_map[ font ] = offset offset += 1 self._write( "}\n" ) def _WriteStyleSheet( self ) : self._write( r"{\stylesheet" ) # TO DO: character styles, does anybody actually use them? offset_map = {} for idx, style in enumerate( self._doc.StyleSheet.ParagraphStyles ) : offset_map[ style ] = idx # paragraph styles self.paragraph_style_map = {} for idx, style in enumerate( self._doc.StyleSheet.ParagraphStyles ) : if idx == 0 : default = style else : self._write( '\n' ) settings = Settings() # paragraph properties self._RendParagraphPropertySet( style.ParagraphPropertySet, settings ) self._RendFramePropertySet ( style.FramePropertySet, settings ) self._RendShadingPropertySet ( style.ShadingPropertySet, settings ) # text properties self._RendTextPropertySet ( style.TextStyle.TextPropertySet, settings ) self._RendShadingPropertySet( style.TextStyle.ShadingPropertySet, settings ) # have to take based_on = '\\sbasedon%s' % offset_map.get( style.BasedOn, 0 ) next = '\\snext%s' % offset_map.get( style.Next, 0 ) inln = '\\s%s%s' % ( idx, settings ) self._write( "{%s%s%s %s;}", inln, based_on, next, style.Name ) self.paragraph_style_map[ style ] = inln # if now style is specified for the first paragraph to be written, this one # will be used self._CurrentStyle = self.paragraph_style_map[ default ] self._write( "}\n" ) def _WriteSection( self, section, is_first, add_header ) : def WriteHF( hf, rtfword ) : #if not hf : return # if we don't have anything in the header/footer then include # a blank paragraph, this stops it from picking up the header/footer # from the previous section # if not hf : hf = [ Paragraph( '' ) ] if not hf : hf = [] self._write( '{\\%s' % rtfword ) self._WriteElements( hf ) self._write( '}\n' ) settings = Settings() if not is_first : # we need to finish off the preceding section # and reset all of our defaults back to standard settings.append( 'sect' ) # reset to our defaults settings.append( 'sectd' ) if add_header : settings.append( SectionBreakTypeMap[ section.BreakType ] ) self._RendPageProperties( section, settings, in_section=True ) settings.append( section.HeaderY, 'headery%s' ) settings.append( section.FooterY, 'footery%s' ) # write all of these out now as we need to do a write elements in the # next section self._write( repr( settings ) ) # finally after all that has settled down we can do the # headers and footers if section.FirstHeader or section.FirstFooter : # include the titlepg flag if the first page has a special format self._write( r'\titlepg' ) WriteHF( section.FirstHeader, 'headerf' ) WriteHF( section.FirstFooter, 'footerf' ) WriteHF( section.Header, 'header' ) WriteHF( section.Footer, 'footer' ) # and at last the contents of the section that actually appear on the page self._WriteElements( section ) def _WriteElements( self, elements ) : new_line = '' for element in elements : self._write( new_line ) new_line = '\n' clss = element.__class__ if clss == Paragraph : self.WriteParagraphElement( element ) elif clss == Table : self.WriteTableElement( element ) elif clss == StringType : self.WriteParagraphElement( Paragraph( element ) ) elif clss in [ RawCode, Image ] : self.WriteRawCode( element ) #elif clss == List : # self._HandleListElement( element ) elif self.WriteCustomElement : self.WriteCustomElement( self, element ) else : raise Exception( "Don't know how to handle elements of type %s" % clss ) def WriteParagraphElement( self, paragraph_elem, tag_prefix='', tag_suffix=r'\par', opening='{', closing='}' ) : # the tag_prefix and the tag_suffix take care of paragraphs in tables. A # paragraph in a table requires and extra tag at the front (intbl) and we # don't want the ending tag everytime. We want it for all paragraphs but # the last. overrides = Settings() self._RendParagraphPropertySet( paragraph_elem.Properties, overrides ) self._RendFramePropertySet ( paragraph_elem.Frame, overrides ) self._RendShadingPropertySet ( paragraph_elem.Shading, overrides ) # when writing the RTF the style is carried from the previous paragraph to the next, # so if the currently written paragraph has a style then make it the current one, # otherwise leave it as it was self._CurrentStyle = self.paragraph_style_map.get( paragraph_elem.Style, self._CurrentStyle ) self._write( r'%s\pard\plain%s %s%s ' % ( opening, tag_prefix, self._CurrentStyle, overrides ) ) for element in paragraph_elem : if isinstance( element, StringType ) : self._write( element ) elif isinstance( element, RawCode ) : self._write( element.Data ) elif isinstance( element, Text ) : self.WriteTextElement( element ) elif isinstance( element, Inline ) : self.WriteInlineElement( element ) elif element == TAB : self._write( r'\tab ' ) elif element == LINE : self._write( r'\line ' ) elif self.WriteCustomElement : self.WriteCustomElement( self, element ) else : raise Exception( 'Don\'t know how to handle %s' % element ) self._write( tag_suffix + closing ) def WriteRawCode( self, raw_elem ) : self._write( raw_elem.Data ) def WriteTextElement( self, text_elem ) : overrides = Settings() self._RendTextPropertySet ( text_elem.Properties, overrides ) self._RendShadingPropertySet( text_elem.Shading, overrides, 'ch' ) # write the wrapper and then let the custom handler have a go if overrides : self._write( '{%s ' % repr( overrides ) ) # if the data is just a string then we can now write it if isinstance( text_elem.Data, StringType ) : self._write( text_elem.Data or '' ) elif text_elem.Data == TAB : self._write( r'\tab ' ) else : self.WriteCustomElement( self, text_elem.Data ) if overrides : self._write( '}' ) def WriteInlineElement( self, inline_elem ) : overrides = Settings() self._RendTextPropertySet ( inline_elem.Properties, overrides ) self._RendShadingPropertySet( inline_elem.Shading, overrides, 'ch' ) # write the wrapper and then let the custom handler have a go if overrides : self._write( '{%s ' % repr( overrides ) ) for element in inline_elem : # if the data is just a string then we can now write it if isinstance( element, StringType ) : self._write( element ) elif isinstance( element, RawCode ) : self._write( element.Data ) elif element == TAB : self._write( r'\tab ' ) elif element == LINE : self._write( r'\line ' ) else : self.WriteCustomElement( self, element ) if overrides : self._write( '}' ) def WriteText( self, text ) : self._write( text or '' ) def WriteTableElement( self, table_elem ) : vmerge = [ False ] * table_elem.ColumnCount for height, cells in table_elem.Rows : # calculate the right hand edge of the cells taking into account the spans offset = table_elem.LeftOffset or 0 cellx = [] cell_idx = 0 for cell in cells : cellx.append( offset + sum( table_elem.ColumnWidths[ : cell_idx + cell.Span ] ) ) cell_idx += cell.Span self._write( r'{\trowd' ) settings = Settings() # the spec says that this value is mandatory and I think that 108 is the default value # so I'll take care of it here settings.append( table_elem.GapBetweenCells or 108, 'trgaph%s' ) settings.append( TableAlignmentMap[ table_elem.Alignment ] ) settings.append( height, 'trrh%s' ) settings.append( table_elem.LeftOffset, 'trleft%s' ) width = table_elem.LeftOffset or 0 for idx, cell in enumerate( cells ) : self._RendFramePropertySet ( cell.Frame, settings, 'cl' ) # cells don't have margins so I don't know why I was doing this # I think it might have an affect in some versions of some WPs. #self._RendMarginsPropertySet( cell.Margins, settings, 'cl' ) # if we are starting to merge or if this one is the first in what is # probably a series of merges then start the vertical merging if cell.StartVerticalMerge or (cell.VerticalMerge and not vmerge[ idx ]) : settings.append( 'clvmgf' ) vmerge[ idx ] = True elif cell.VerticalMerge : #..continuing a merge settings.append( 'clvmrg' ) else : #..no merging going on so make sure that it is off vmerge[ idx ] = False # for any cell in the next row that is covered by this span we # need to run off the vertical merging as we don't want them # merging up into this spanned cell for vmerge_idx in range( idx + 1, idx + cell.Span - 1 ) : vmerge[ vmerge_idx ] = False settings.append( CellAlignmentMap[ cell.Alignment ] ) settings.append( CellFlowMap[ cell.Flow ] ) # this terminates the definition of a cell and represents the right most edge of the cell from the left margin settings.append( cellx[ idx ], 'cellx%s' ) self._write( repr( settings ) ) for cell in cells : if len( cell ) : last_idx = len( cell ) - 1 for element_idx, element in enumerate( cell ) : # wrap plain strings in paragraph tags if isinstance( element, StringType ) : element = Paragraph( element ) # don't forget the prefix or else word crashes and does all sorts of strange things if element_idx == last_idx : self.WriteParagraphElement( element, tag_prefix=r'\intbl', tag_suffix='', opening='', closing='' ) else : self.WriteParagraphElement( element, tag_prefix=r'\intbl', opening='', closing='' ) self._write( r'\cell' ) else : self._write( r'\pard\intbl\cell' ) self._write( '\\row}\n' )
Python
from types import IntType, FloatType, LongType, StringTypes from copy import deepcopy from binascii import hexlify from Constants import * from Styles import * class UnhandledParamError( Exception ) : def __init__( self, param ) : Exception.__init__( self, "Don't know what to do with param %s" % param ) # red green blue StandardColours = Colours() StandardColours.append( Colour( 'Black', 0, 0, 0 ) ) StandardColours.append( Colour( 'Blue', 0, 0, 255 ) ) StandardColours.append( Colour( 'Turquoise', 0, 255, 255 ) ) StandardColours.append( Colour( 'Green', 0, 255, 0 ) ) StandardColours.append( Colour( 'Pink', 255, 0, 255 ) ) StandardColours.append( Colour( 'Red', 255, 0, 0 ) ) StandardColours.append( Colour( 'Yellow', 255, 255, 0 ) ) StandardColours.append( Colour( 'White', 255, 255, 255 ) ) StandardColours.append( Colour( 'Blue Dark', 0, 0, 128 ) ) StandardColours.append( Colour( 'Teal', 0, 128, 128 ) ) StandardColours.append( Colour( 'Green Dark', 0, 128, 0 ) ) StandardColours.append( Colour( 'Violet', 128, 0, 128 ) ) StandardColours.append( Colour( 'Red Dark', 128, 0, 0 ) ) StandardColours.append( Colour( 'Yellow Dark', 128, 128, 0 ) ) StandardColours.append( Colour( 'Grey Dark', 128, 128, 128 ) ) StandardColours.append( Colour( 'Grey', 192, 192, 192 ) ) StandardFonts = Fonts() StandardFonts.append( Font( 'Arial' , 'swiss' , 0, 2, '020b0604020202020204' ) ) StandardFonts.append( Font( 'Arial Black' , 'swiss' , 0, 2, '020b0a04020102020204' ) ) StandardFonts.append( Font( 'Arial Narrow' , 'swiss' , 0, 2, '020b0506020202030204' ) ) StandardFonts.append( Font( 'Bitstream Vera Sans Mono', 'modern', 0, 1, '020b0609030804020204' ) ) StandardFonts.append( Font( 'Bitstream Vera Sans' , 'swiss' , 0, 2, '020b0603030804020204' ) ) StandardFonts.append( Font( 'Bitstream Vera Serif' , 'roman' , 0, 2, '02060603050605020204' ) ) StandardFonts.append( Font( 'Book Antiqua' , 'roman' , 0, 2, '02040602050305030304' ) ) StandardFonts.append( Font( 'Bookman Old Style' , 'roman' , 0, 2, '02050604050505020204' ) ) StandardFonts.append( Font( 'Castellar' , 'roman' , 0, 2, '020a0402060406010301' ) ) StandardFonts.append( Font( 'Century Gothic' , 'swiss' , 0, 2, '020b0502020202020204' ) ) StandardFonts.append( Font( 'Comic Sans MS' , 'script', 0, 2, '030f0702030302020204' ) ) StandardFonts.append( Font( 'Courier New' , 'modern', 0, 1, '02070309020205020404' ) ) StandardFonts.append( Font( 'Franklin Gothic Medium' , 'swiss' , 0, 2, '020b0603020102020204' ) ) StandardFonts.append( Font( 'Garamond' , 'roman' , 0, 2, '02020404030301010803' ) ) StandardFonts.append( Font( 'Georgia' , 'roman' , 0, 2, '02040502050405020303' ) ) StandardFonts.append( Font( 'Haettenschweiler' , 'swiss' , 0, 2, '020b0706040902060204' ) ) StandardFonts.append( Font( 'Impact' , 'swiss' , 0, 2, '020b0806030902050204' ) ) StandardFonts.append( Font( 'Lucida Console' , 'modern', 0, 1, '020b0609040504020204' ) ) StandardFonts.append( Font( 'Lucida Sans Unicode' , 'swiss' , 0, 2, '020b0602030504020204' ) ) StandardFonts.append( Font( 'Microsoft Sans Serif' , 'swiss' , 0, 2, '020b0604020202020204' ) ) StandardFonts.append( Font( 'Monotype Corsiva' , 'script', 0, 2, '03010101010201010101' ) ) StandardFonts.append( Font( 'Palatino Linotype' , 'roman' , 0, 2, '02040502050505030304' ) ) StandardFonts.append( Font( 'Papyrus' , 'script', 0, 2, '03070502060502030205' ) ) StandardFonts.append( Font( 'Sylfaen' , 'roman' , 0, 2, '010a0502050306030303' ) ) StandardFonts.append( Font( 'Symbol' , 'roman' , 2, 2, '05050102010706020507' ) ) StandardFonts.append( Font( 'Tahoma' , 'swiss' , 0, 2, '020b0604030504040204' ) ) StandardFonts.append( Font( 'Times New Roman' , 'roman' , 0, 2, '02020603050405020304' ) ) StandardFonts.append( Font( 'Trebuchet MS' , 'swiss' , 0, 2, '020b0603020202020204' ) ) StandardFonts.append( Font( 'Verdana' , 'swiss' , 0, 2, '020b0604030504040204' ) ) StandardFonts.Castellar.SetAlternate( StandardFonts.Georgia ) """ Found the following definition at http://www.pbdr.com/vbtips/gen/convtwip.htm Twips are screen-independent units used to ensure that the placement and proportion of screen elements in your screen application are the same on all display systems. A twip is a unit of screen measurement equal to 1/20 of a printer's point. The conversion between twips and inches/centimeters/millimeters is as follows: There are approximately 1440 twips to a inch (the length of a screen item measuring one inch when printed). As there are 2.54 centimeters to 1 inch, then there are approximately 567 twips to a centimeter (the length of a screen item measuring one centimeter when printed). Or in millimeters, as there are 25.4 millimeters to 1 inch, therefore there are approximately 56.7 twips to a millimeter (the length of a screen item measuring one millimeter when printed).""" # Width default is 12240, Height default is 15840 StandardPaper = Papers() StandardPaper.append( Paper( 'LETTER' , 1, 'Letter 8 1/2 x 11 in' , 12240, 15840 ) ) StandardPaper.append( Paper( 'LETTERSMALL' , 2, 'Letter Small 8 1/2 x 11 in' , 12240, 15840 ) ) StandardPaper.append( Paper( 'TABLOID' , 3, 'Tabloid 11 x 17 in' , 15840, 24480 ) ) StandardPaper.append( Paper( 'LEDGER' , 4, 'Ledger 17 x 11 in' , 24480, 15840 ) ) StandardPaper.append( Paper( 'LEGAL' , 5, 'Legal 8 1/2 x 14 in' , 12240, 20160 ) ) StandardPaper.append( Paper( 'STATEMENT' , 6, 'Statement 5 1/2 x 8 1/2 in' , 7920, 12240 ) ) StandardPaper.append( Paper( 'EXECUTIVE' , 7, 'Executive 7 1/4 x 10 1/2 in' , 10440, 15120 ) ) StandardPaper.append( Paper( 'A3' , 8, 'A3 297 x 420 mm' , 16838, 23811 ) ) StandardPaper.append( Paper( 'A4' , 9, 'A4 210 x 297 mm' , 11907, 16838 ) ) StandardPaper.append( Paper( 'A4SMALL' , 10, 'A4 Small 210 x 297 mm' , 11907, 16838 ) ) StandardPaper.append( Paper( 'A5' , 11, 'A5 148 x 210 mm' , 8391, 11907 ) ) StandardPaper.append( Paper( 'B4' , 12, 'B4 (JIS) 250 x 354' , 14175, 20072 ) ) StandardPaper.append( Paper( 'B5' , 13, 'B5 (JIS) 182 x 257 mm' , 10319, 14572 ) ) StandardPaper.append( Paper( 'FOLIO' , 14, 'Folio 8 1/2 x 13 in' , 12240, 18720 ) ) StandardPaper.append( Paper( 'QUARTO' , 15, 'Quarto 215 x 275 mm' , 12191, 15593 ) ) StandardPaper.append( Paper( '10X14' , 16, '10x14 in' , 14400, 20160 ) ) StandardPaper.append( Paper( '11X17' , 17, '11x17 in' , 15840, 24480 ) ) StandardPaper.append( Paper( 'NOTE' , 18, 'Note 8 1/2 x 11 in' , 12240, 15840 ) ) StandardPaper.append( Paper( 'ENV_9' , 19, 'Envelope #9 3 7/8 x 8 7/8' , 5580, 12780 ) ) StandardPaper.append( Paper( 'ENV_10' , 20, 'Envelope #10 4 1/8 x 9 1/2' , 5940, 13680 ) ) StandardPaper.append( Paper( 'ENV_11' , 21, 'Envelope #11 4 1/2 x 10 3/8' , 6480, 14940 ) ) StandardPaper.append( Paper( 'ENV_12' , 22, 'Envelope #12 4 3/4 x 11' , 6840, 15840 ) ) StandardPaper.append( Paper( 'ENV_14' , 23, 'Envelope #14 5 x 11 1/2' , 7200, 16560 ) ) StandardPaper.append( Paper( 'CSHEET' , 24, 'C size sheet 18 x 24 in' , 29520, 34560 ) ) StandardPaper.append( Paper( 'DSHEET' , 25, 'D size sheet 22 x 34 in' , 31680, 48960 ) ) StandardPaper.append( Paper( 'ESHEET' , 26, 'E size sheet 34 x 44 in' , 48960, 63360 ) ) StandardPaper.append( Paper( 'ENV_DL' , 27, 'Envelope DL 110 x 220mm' , 6237, 12474 ) ) StandardPaper.append( Paper( 'ENV_C5' , 28, 'Envelope C5 162 x 229 mm' , 9185, 12984 ) ) StandardPaper.append( Paper( 'ENV_C3' , 29, 'Envelope C3 324 x 458 mm' , 18371, 25969 ) ) StandardPaper.append( Paper( 'ENV_C4' , 30, 'Envelope C4 229 x 324 mm' , 12984, 18371 ) ) StandardPaper.append( Paper( 'ENV_C6' , 31, 'Envelope C6 114 x 162 mm' , 6464, 9185 ) ) StandardPaper.append( Paper( 'ENV_C65' , 32, 'Envelope C65 114 x 229 mm' , 6464, 12984 ) ) StandardPaper.append( Paper( 'ENV_B4' , 33, 'Envelope B4 250 x 353 mm' , 14175, 20015 ) ) StandardPaper.append( Paper( 'ENV_B5' , 34, 'Envelope B5 176 x 250 mm' , 9979, 14175 ) ) StandardPaper.append( Paper( 'ENV_B6' , 35, 'Envelope B6 176 x 125 mm' , 9979, 7088 ) ) StandardPaper.append( Paper( 'ENV_ITALY' , 36, 'Envelope 110 x 230 mm' , 6237, 13041 ) ) StandardPaper.append( Paper( 'ENV_MONARCH' , 37, 'Envelope Monarch 3.875 x 7.5 in' , 5580, 10800 ) ) StandardPaper.append( Paper( 'ENV_PERSONAL' , 38, '6 3/4 Envelope 3 5/8 x 6 1/2 in' , 5220, 9360 ) ) StandardPaper.append( Paper( 'FANFOLD_US' , 39, 'US Std Fanfold 14 7/8 x 11 in' , 21420, 15840 ) ) StandardPaper.append( Paper( 'FANFOLD_STD_GERMAN' , 40, 'German Std Fanfold 8 1/2 x 12 in' , 12240, 17280 ) ) StandardPaper.append( Paper( 'FANFOLD_LGL_GERMAN' , 41, 'German Legal Fanfold 8 1/2 x 13 in' , 12240, 18720 ) ) # # Finally a StyleSheet in which all of this stuff is put together # class StyleSheet : def __init__( self, colours=None, fonts=None ) : self.Colours = colours or deepcopy( StandardColours ) self.Fonts = fonts or deepcopy( StandardFonts ) self.TextStyles = AttributedList() self.ParagraphStyles = AttributedList() class Section( list ) : NONE = 1 COLUMN = 2 PAGE = 3 EVEN = 4 ODD = 5 BREAK_TYPES = [ NONE, COLUMN, PAGE, EVEN, ODD ] def __init__( self, paper=None, margins=None, break_type=None, headery=None, footery=None, landscape=None, first_page_number=None ) : super( Section, self ).__init__() self.Paper = paper or StandardPaper.A4 self.SetMargins( margins ) self.Header = [] self.Footer = [] self.FirstHeader = [] self.FirstFooter = [] self.SetBreakType( break_type or self.NONE ) self.SetHeaderY( headery ) self.SetFooterY( footery ) self.SetLandscape( landscape ) self.SetFirstPageNumber( first_page_number ) def TwipsToRightMargin( self ) : return self.Paper.Width - ( self.Margins.Left + self.Margins.Right ) def SetMargins( self, value ) : self.Margins = value or MarginsPropertySet( top=1000, left=1200, bottom=1000, right=1200 ) self.Width = self.Paper.Width - ( self.Margins.Left + self.Margins.Right ) def SetBreakType( self, value ) : assert value in self.BREAK_TYPES self.BreakType = value return self def SetHeaderY( self, value ) : self.HeaderY = value return self def SetFooterY( self, value ) : self.FooterY = value return self def SetLandscape( self, value ) : self.Landscape = False if value : self.Landscape = True return self def SetFirstPageNumber( self, value ) : self.FirstPageNumber = value return self def MakeDefaultStyleSheet( ) : result = StyleSheet() NormalText = TextStyle( TextPropertySet( result.Fonts.Arial, 22 ) ) ps = ParagraphStyle( 'Normal', NormalText.Copy(), ParagraphPropertySet( space_before = 60, space_after = 60 ) ) result.ParagraphStyles.append( ps ) ps = ParagraphStyle( 'Normal Short', NormalText.Copy() ) result.ParagraphStyles.append( ps ) NormalText.TextPropertySet.SetSize( 32 ) ps = ParagraphStyle( 'Heading 1', NormalText.Copy(), ParagraphPropertySet( space_before = 240, space_after = 60 ) ) result.ParagraphStyles.append( ps ) NormalText.TextPropertySet.SetSize( 24 ).SetBold( True ) ps = ParagraphStyle( 'Heading 2', NormalText.Copy(), ParagraphPropertySet( space_before = 240, space_after = 60 ) ) result.ParagraphStyles.append( ps ) # Add some more in that are based on the normal template but that # have some indenting set that makes them suitable for doing numbered normal_numbered = result.ParagraphStyles.Normal.Copy() normal_numbered.SetName( 'Normal Numbered' ) normal_numbered.ParagraphPropertySet.SetFirstLineIndent( TabPropertySet.DEFAULT_WIDTH * -1 ) normal_numbered.ParagraphPropertySet.SetLeftIndent ( TabPropertySet.DEFAULT_WIDTH ) result.ParagraphStyles.append( normal_numbered ) normal_numbered2 = result.ParagraphStyles.Normal.Copy() normal_numbered2.SetName( 'Normal Numbered 2' ) normal_numbered2.ParagraphPropertySet.SetFirstLineIndent( TabPropertySet.DEFAULT_WIDTH * -1 ) normal_numbered2.ParagraphPropertySet.SetLeftIndent ( TabPropertySet.DEFAULT_WIDTH * 2 ) result.ParagraphStyles.append( normal_numbered2 ) ## LIST STYLES for idx, indent in [ (1, TabPS.DEFAULT_WIDTH ), (2, TabPS.DEFAULT_WIDTH * 2), (3, TabPS.DEFAULT_WIDTH * 3) ] : indent = TabPropertySet.DEFAULT_WIDTH ps = ParagraphStyle( 'List %s' % idx, TextStyle( TextPropertySet( result.Fonts.Arial, 22 ) ), ParagraphPropertySet( space_before = 60, space_after = 60, first_line_indent = -indent, left_indent = indent) ) result.ParagraphStyles.append( ps ) return result class TAB : pass class LINE : pass class RawCode : def __init__( self, data ) : self.Data = data PAGE_NUMBER = RawCode( r'{\field{\fldinst page}}' ) TOTAL_PAGES = RawCode( r'{\field{\fldinst numpages}}' ) SECTION_PAGES = RawCode( r'{\field{\fldinst sectionpages}}' ) ARIAL_BULLET = RawCode( r'{\f2\'95}' ) def _get_jpg_dimensions( fin ): """ converted from: http://dev.w3.org/cvsweb/Amaya/libjpeg/rdjpgcom.c?rev=1.2 """ M_SOF0 = chr( 0xC0 ) # /* Start Of Frame N */ M_SOF1 = chr( 0xC1 ) # /* N indicates which compression process */ M_SOF2 = chr( 0xC2 ) # /* Only SOF0-SOF2 are now in common use */ M_SOF3 = chr( 0xC3 ) # M_SOF5 = chr( 0xC5 ) # /* NB: codes C4 and CC are NOT SOF markers */ M_SOF6 = chr( 0xC6 ) # M_SOF7 = chr( 0xC7 ) # M_SOF9 = chr( 0xC9 ) # M_SOF10 = chr( 0xCA ) # M_SOF11 = chr( 0xCB ) # M_SOF13 = chr( 0xCD ) # M_SOF14 = chr( 0xCE ) # M_SOF15 = chr( 0xCF ) # M_SOI = chr( 0xD8 ) # /* Start Of Image (beginning of datastream) */ M_EOI = chr( 0xD9 ) # /* End Of Image (end of datastream) */ M_FF = chr( 0xFF ) MARKERS = [ M_SOF0, M_SOF1, M_SOF2, M_SOF3, M_SOF5, M_SOF6, M_SOF7, M_SOF9, M_SOF10,M_SOF11, M_SOF13, M_SOF14, M_SOF15 ] def get_length() : b1 = fin.read( 1 ) b2 = fin.read( 1 ) return (ord(b1) << 8) + ord(b2) def next_marker() : # markers come straight after an 0xFF so skip everything # up to the first 0xFF that we find while fin.read(1) != M_FF : pass # there can be more than one 0xFF as they can be used # for padding so we are now looking for the first byte # that isn't an 0xFF, this will be the marker while True : result = fin.read(1) if result != M_FF : return result raise Exception( 'Invalid JPEG' ) # BODY OF THE FUNCTION if not ((fin.read(1) == M_FF) and (fin.read(1) == M_SOI)) : raise Exception( 'Invalid Jpeg' ) while True : marker = next_marker() # the marker is always followed by two bytes representing the length of the data field length = get_length () if length < 2 : raise Exception( "Erroneous JPEG marker length" ) # if it is a compression process marker then it will contain the dimension of the image if marker in MARKERS : # the next byte is the data precision, just skip it fin.read(1) # bingo image_height = get_length() image_width = get_length() return image_width, image_height # just skip whatever data it contains fin.read( length - 2 ) raise Exception( 'Invalid JPEG, end of stream reached' ) _PNG_HEADER = '\x89\x50\x4e' def _get_png_dimensions( data ) : if data[0:3] != _PNG_HEADER : raise Exception( 'Invalid PNG image' ) width = (ord(data[18]) * 256) + (ord(data[19])) height = (ord(data[22]) * 256) + (ord(data[23])) return width, height def _get_emf_dimensions( fin ): import struct def get_DWORD(): return struct.unpack("<L",fin.read(4))[0] def get_LONG(): return struct.unpack("<l",fin.read(4))[0] def get_WORD(): return struct.unpack("<H",fin.read(2))[0] class Empty: pass header = Empty() header.RecordType = get_DWORD() # Record type header.RecordSize = get_DWORD() # Size of the record in bytes header.BoundsLeft = get_LONG() # Left inclusive bounds header.BoundsTop = get_LONG() # Top inclusive bounds header.BoundsRight = get_LONG() # Right inclusive bounds header.BoundsBottom = get_LONG() # Bottom inclusive bounds header.FrameLeft = get_LONG() # Left side of inclusive picture frame header.FrameTop = get_LONG() # Top side of inclusive picture frame header.FrameRight = get_LONG() # Right side of inclusive picture frame header.FrameBottom = get_LONG() # Bottom side of inclusive picture frame header.Signature = get_DWORD() # Signature ID (always 0x464D4520) header.Version = get_DWORD() # Version of the metafile header.Size = get_DWORD() # Size of the metafile in bytes header.NumOfRecords = get_DWORD() # Number of records in the metafile header.NumOfHandles = get_WORD() # Number of handles in the handle table header.Reserved = get_WORD() # Not used (always 0) header.SizeOfDescrip = get_DWORD() # Size of description string in WORDs header.OffsOfDescrip = get_DWORD() # Offset of description string in metafile header.NumPalEntries = get_DWORD() # Number of color palette entries header.WidthDevPixels = get_LONG() # Width of reference device in pixels header.HeightDevPixels = get_LONG() # Height of reference device in pixels header.WidthDevMM = get_LONG() # Width of reference device in millimeters header.HeightDevMM = get_LONG() # Height of reference device in millimeters if 0: klist = header.__dict__.keys() klist.sort() for k in klist: print "%20s:%s" % (k,header.__dict__[k]) dw = header.FrameRight-header.FrameLeft dh = header.FrameBottom-header.FrameTop # convert from 0.01mm units to 1/72in units return int(dw * 72.0/2540.0), int(dh * 72.0/2540.0) class Image( RawCode ) : # Need to add in the width and height in twips as it crashes # word xp with these values. Still working out the most # efficient way of getting these values. # \picscalex100\picscaley100\piccropl0\piccropr0\piccropt0\piccropb0 # picwgoal900\pichgoal281 PNG_LIB = 'pngblip' JPG_LIB = 'jpegblip' EMF_LIB = 'emfblip' PICT_TYPES = { 'png' : PNG_LIB, 'jpg' : JPG_LIB, 'emf' : EMF_LIB} def __init__( self, infile, **kwargs ) : if hasattr( infile, 'read' ): fin = infile if 'datatype' not in kwargs.keys(): msg = "If passing in a file object, you must also specify type='xxx' where xxx is one of %s" % self.PICT_TYPES.keys() raise ValueError,msg file_name = kwargs.pop('datatype') else: fin = file( infile, 'rb' ) file_name = infile pict_type = self.PICT_TYPES[ file_name[ -3 : ].lower() ] if pict_type == self.PNG_LIB : width, height = _get_png_dimensions( fin.read( 100 ) ) elif pict_type == self.JPG_LIB : width, height = _get_jpg_dimensions( fin ) elif pict_type == self.EMF_LIB : width, height = _get_emf_dimensions( fin ) # if user specified height or width but not both, then # scale unspecified dimension to maintain aspect ratio if ('width' in kwargs) and ('height' not in kwargs): height = int(height * float(kwargs['width'])/width) elif ('height' in kwargs) and ('width' not in kwargs): width = int(width * float(kwargs['height'])/height) width = kwargs.pop('width',width) height = kwargs.pop('height', height) codes = [ pict_type, 'picwgoal%s' % (width * 20), 'pichgoal%s' % (height * 20) ] # let user specify global scaling scale = kwargs.pop('scale',100) for kwarg, code, default in [ ( 'scale_x', 'scalex', scale ), ( 'scale_y', 'scaley', scale ), ( 'crop_left', 'cropl', '0' ), ( 'crop_right', 'cropr', '0' ), ( 'crop_top', 'cropt', '0' ), ( 'crop_bottom', 'cropb', '0' ) ] : codes.append( 'pic%s%s' % ( code, kwargs.pop( kwarg, default ) ) ) # reset back to the start of the file to get all of it and now # turn it into hex. fin.seek( 0, 0 ) image = hexlify( fin.read() ) fin.close() data = [] for i in range( 0, len( image ), 128 ) : data.append( image[ i : i + 128 ] ) data = r'{\pict{\%s}%s}' % ( '\\'.join( codes ), '\n'.join( data ) ) RawCode.__init__( self, data ) def ToRawCode( self, var_name ) : return '%s = RawCode( """%s""" )' % ( var_name, self.Data ) class Text : def __init__( self, *params ) : self.Data = None self.Style = None self.Properties = None self.Shading = None for param in params : if isinstance( param, TextStyle ) : self.Style = param elif isinstance( param, TextPS ) : self.Properties = param elif isinstance( param, ShadingPS ) : self.Shading = param else : # otherwise let the rendering custom handler sort it out itself self.Data = param def SetData( self, value ) : self.Data = value class Inline( list ) : def __init__( self, *params ) : super( Inline, self ).__init__() self.Style = None self.Properties = None self.Shading = None self._append = super( Inline, self ).append for param in params : if isinstance( param, TextStyle ) : self.Style = param elif isinstance( param, TextPS ) : self.Properties = param elif isinstance( param, ShadingPS ) : self.Shading = param else : # otherwise we add to it to our list of elements and let # the rendering custom handler sort it out itself. self.append( param ) def append( self, *params ) : # filter out any that are explicitly None [ self._append( param ) for param in params if param is not None ] class Paragraph( list ) : def __init__( self, *params ) : super( Paragraph, self ).__init__() self.Style = None self.Properties = None self.Frame = None self.Shading = None self._append = super( Paragraph, self ).append for param in params : if isinstance( param, ParagraphStyle ) : self.Style = param elif isinstance( param, ParagraphPS ) : self.Properties = param elif isinstance( param, FramePS ) : self.Frame = param elif isinstance( param, ShadingPS ) : self.Shading = param else : # otherwise we add to it to our list of elements and let # the rendering custom handler sort it out itself. self.append( param ) def append( self, *params ) : # filter out any that are explicitly None [ self._append( param ) for param in params if param is not None ] def insert( self, index, value ) : if value is not None : super( Paragraph, self ).insert( index, value ) class Table : LEFT = 1 RIGHT = 2 CENTER = 3 ALIGNMENT = [ LEFT, RIGHT, CENTER ] NO_WRAPPING = 1 WRAP_AROUND = 2 WRAPPING = [ NO_WRAPPING, WRAP_AROUND ] # trrh height of row, 0 means automatically adjust, use negative for an absolute # trgaph is half of the space between a table cell in width, reduce this one # to get a really tiny column def __init__( self, *column_widths, **kwargs ) : self.Rows = [] self.SetAlignment ( kwargs.pop( 'alignment', self.LEFT ) ) self.SetLeftOffset ( kwargs.pop( 'left_offset', None ) ) self.SetGapBetweenCells( kwargs.pop( 'gap_between_cells', None ) ) self.SetColumnWidths ( *column_widths ) assert not kwargs, 'invalid keyword args %s' % kwargs def SetAlignment( self, value ) : assert value is None or value in self.ALIGNMENT self.Alignment = value or self.LEFT return self def SetLeftOffset( self, value ) : self.LeftOffset = value return self def SetGapBetweenCells( self, value ) : self.GapBetweenCells = value return self def SetColumnWidths( self, *column_widths ) : self.ColumnWidths = column_widths self.ColumnCount = len( column_widths ) return self def AddRow( self, *cells ) : height = None if isinstance( cells[ 0 ], (IntType, FloatType, LongType) ): height = int( cells[ 0 ] ) cells = cells[ 1 : ] # make sure all of the spans add up to the number of columns # otherwise the table will get corrupted if self.ColumnCount != sum( [ cell.Span for cell in cells ] ) : raise Exception( 'ColumnCount != the total of this row\'s cell.Spans.' ) self.Rows.append( ( height, cells ) ) append = AddRow class Cell( list ) : """ \clvertalt Text is top-aligned in cell (the default). \clvertalc Text is centered vertically in cell. \clvertalb Text is bottom-aligned in cell. \cltxlrtb Vertical text aligned left (direction bottom up). \cltxtbrl Vertical text aligned right (direction top down). """ ALIGN_TOP = 1 ALIGN_CENTER = 2 ALIGN_BOTTOM = 3 FLOW_LR_TB = 1 FLOW_RL_TB = 2 FLOW_LR_BT = 3 FLOW_VERTICAL_LR_TB = 4 FLOW_VERTICAL_TB_RL = 5 def __init__( self, *params, **kwargs ) : super( Cell, self ).__init__() self.SetFrame ( None ) self.SetMargins( None ) self.SetAlignment( kwargs.get( 'alignment', self.ALIGN_TOP ) ) self.SetFlow ( kwargs.get( 'flow' , self.FLOW_LR_TB ) ) self.SetSpan ( kwargs.get( 'span', 1 ) ) self.SetStartVerticalMerge( kwargs.get( 'start_vertical_merge', False ) ) self.SetVerticalMerge ( kwargs.get( 'vertical_merge', False ) ) self._append = super( Cell, self ).append for param in params : if isinstance( param, StringType ) : self.append ( param ) elif isinstance( param, Paragraph ) : self.append ( param ) elif isinstance( param, FramePS ) : self.SetFrame ( param ) elif isinstance( param, MarginsPS ) : self.SetMargins( param ) def SetFrame( self, value ) : self.Frame = value return self def SetMargins( self, value ) : self.Margins = value return self def SetAlignment( self, value ) : assert value in [ self.ALIGN_TOP, self.ALIGN_CENTER, self.ALIGN_BOTTOM ] #, self.ALIGN_TEXT_TOP_DOWN, self.ALIGN_TEXT_BOTTOM_UP ] self.Alignment = value def SetFlow( self, value ) : assert value in [ self.FLOW_LR_TB, self.FLOW_RL_TB, self.FLOW_LR_BT, self.FLOW_VERTICAL_LR_TB, self.FLOW_VERTICAL_TB_RL ] self.Flow = value def SetSpan( self, value ) : # must be a positive integer self.Span = int( max( value, 1 ) ) return self def SetStartVerticalMerge( self, value ) : self.StartVerticalMerge = False if value : self.StartVerticalMerge = True return self def SetVerticalMerge( self, value ) : self.VerticalMerge = False if value : self.VerticalMerge = True return self def append( self, *params ) : [ self._append( param ) for param in params ] class Document : def __init__( self, style_sheet=None, default_language=None, view_kind=None, view_zoom_kind=None, view_scale=None ) : self.StyleSheet = style_sheet or MakeDefaultStyleSheet() self.Sections = AttributedList( Section ) self.SetTitle( None ) self.DefaultLanguage = default_language or Languages.DEFAULT self.ViewKind = view_kind or ViewKind.DEFAULT self.ViewZoomKind = view_zoom_kind self.ViewScale = view_scale def NewSection( self, *params, **kwargs ) : result = Section( *params, **kwargs ) self.Sections.append( result ) return result def SetTitle( self, value ) : self.Title = value return self def Copy( self ) : result = Document( style_sheet = self.StyleSheet.Copy(), default_language = self.DefaultLanguage, view_kind = self.ViewKind, view_zoom_kind = self.ViewZoomKind, view_scale = self.ViewScale ) result.SetTitle( self.Title ) result.Sections = self.Sections.Copy() return result def TEXT( *params, **kwargs ) : text_props = TextPropertySet() text_props.SetFont ( kwargs.get( 'font', None ) ) text_props.SetSize ( kwargs.get( 'size', None ) ) text_props.SetBold ( kwargs.get( 'bold', False ) ) text_props.SetItalic ( kwargs.get( 'italic', False ) ) text_props.SetUnderline( kwargs.get( 'underline', False ) ) text_props.SetColour ( kwargs.get( 'colour', None ) ) if len( params ) == 1 : return Text( params[ 0 ], text_props ) result = Inline( text_props ) apply( result.append, params ) return result def B( *params ) : text_props = TextPropertySet( bold=True ) if len( params ) == 1 : return Text( params[ 0 ], text_props ) result = Inline( text_props ) apply( result.append, params ) return result def I( *params ) : text_props = TextPropertySet( italic=True ) if len( params ) == 1 : return Text( params[ 0 ], text_props ) result = Inline( text_props ) apply( result.append, params ) return result def U( *params ) : text_props = TextPropertySet( underline=True ) if len( params ) == 1 : return Text( params[ 0 ], text_props ) result = Inline( text_props ) apply( result.append, params ) return result
Python
""" A Styles is a collection of PropertySets that can be applied to a particular RTF element. At present there are only two, Text and Paragraph but ListStyles will be added soon too. """ from PropertySets import * class TextStyle : def __init__( self, text_props, name=None, shading_props=None ) : self.SetTextPropertySet ( text_props ) self.SetName ( name ) self.SetShadingPropertySet( shading_props ) def Copy( self ) : return deepcopy( self ) def SetName( self, value ) : self.Name = value return self def SetTextPropertySet( self, value ) : assert isinstance( value, TextPropertySet ) self.TextPropertySet = value return self def SetShadingPropertySet( self, value ) : assert value is None or isinstance( value, ShadingPropertySet ) self.ShadingPropertySet = value or ShadingPropertySet() return self class ParagraphStyle : def __init__( self, name, text_style, paragraph_props=None, frame_props=None, shading_props=None ) : # A style must have Font and a Font Size but the Text property set doesn't # make these mandatory so that they can be used for overrides so at this point # we need to make sure that that we have these values set if not text_style.TextPropertySet.Font : raise Exception( 'Paragraph Styles must have a Font specified.' ) if not text_style.TextPropertySet.Size : raise Exception( 'Paragraph Styles must have a Font Size specified.' ) self.SetName ( name ) self.SetTextStyle ( text_style ) self.SetParagraphPropertySet( paragraph_props ) self.SetFramePropertySet ( frame_props ) self.SetShadingPropertySet ( shading_props ) self.SetBasedOn( None ) self.SetNext ( None ) def Copy( self ) : return deepcopy( self ) def SetName( self, value ) : self.Name = value return self def SetTextStyle( self, value ) : assert isinstance( value, TextStyle ) self.TextStyle = value return self def SetParagraphPropertySet( self, value ) : assert value is None or isinstance( value, ParagraphPropertySet ) self.ParagraphPropertySet = value or ParagraphPropertySet() return self def SetFramePropertySet( self, value ) : assert value is None or isinstance( value, FramePropertySet ) self.FramePropertySet = value or FramePropertySet() return self def SetShadingPropertySet( self, value ) : """Set the background shading for the paragraph.""" assert value is None or isinstance( value, ShadingPropertySet ) self.ShadingPropertySet = value or ShadingPropertySet() return self def SetBasedOn( self, value ) : """Set the Paragraph Style that this one is based on.""" assert not value or isinstance( value, ParagraphStyle ) self.BasedOn = value return self def SetNext( self, value ) : """Set the Paragraph Style that should follow this one.""" assert not value or isinstance( value, ParagraphStyle ) self.Next = value return self
Python
""" PropertySets group common attributes together, each property set is used to control a specific part of the rendering. PropertySets can be used in different elements of the document. For example the FramePropertySet is used in paragraphs, tables, cells, etc. The TextPropertySet can be used for text or in a Paragraph Style. """ from types import StringType from copy import deepcopy # # We need some basic Type like fonts, colours and paper definitions # def MakeAttributeName( value ) : assert value and type( value ) is StringType value = value.replace( ' ', '' ) return value class AttributedList( list ) : def __init__( self, accepted_type=None ) : super( AttributedList, self ).__init__() self.AcceptedType = accepted_type self._append = super( AttributedList, self ).append def append( self, *values ) : for value in values : if self.AcceptedType : assert isinstance( value, self.AcceptedType ) self._append( value ) name = getattr( value, 'Name', None ) if name : name = MakeAttributeName( value.Name ) setattr( self, name, value ) def __deepcopy__( self, memo ) : result = self.__class__() result.append( *self[:] ) return result class Colour : def __init__( self, name, red, green, blue ) : self.SetName ( name ) self.SetRed ( red ) self.SetGreen( green ) self.SetBlue ( blue ) def SetName( self, value ) : self.Name = value return self def SetRed( self, value ) : self.Red = value return self def SetGreen( self, value ) : self.Green = value return self def SetBlue( self, value ) : self.Blue = value return self class Colours( AttributedList ) : def __init__( self ) : super( Colours, self ).__init__( Colour ) class Font : def __init__( self, name, family, character_set = 0, pitch = None, panose = None, alternate = None ) : self.SetName ( name ) self.SetFamily ( family ) self.SetCharacterSet( character_set ) self.SetPitch ( pitch ) self.SetPanose ( panose ) self.SetAlternate ( alternate ) def SetName( self, value ) : self.Name = value return self def SetFamily( self, value ) : self.Family = value return self def SetCharacterSet( self, value ) : self.CharacterSet = value return self def SetPitch( self, value ) : self.Pitch = value return self def SetPanose( self, value ) : self.Panose = value return self def SetAlternate( self, value ) : self.Alternate = value return self class Fonts( AttributedList ) : def __init__( self ) : super( Fonts, self ).__init__( Font ) class Paper : def __init__( self, name, code, description, width, height ) : self.SetName ( name ) self.SetCode ( code ) self.SetDescription( description ) self.SetWidth ( width ) self.SetHeight ( height ) def SetName( self, value ) : self.Name = value return self def SetCode( self, value ) : self.Code = value return self def SetDescription( self, value ) : self.Description = value return self def SetWidth( self, value ) : self.Width = value return self def SetHeight( self, value ) : self.Height = value return self class Papers( AttributedList ) : def __init__( self ) : super( Papers, self ).__init__( Paper ) # # Then we have property sets which represent different aspects of Styles # class MarginsPropertySet : def __init__( self, top=None, left=None, bottom=None, right=None ) : self.SetTop ( top ) self.SetLeft ( left ) self.SetBottom( bottom ) self.SetRight ( right ) def SetTop( self, value ) : self.Top = value return self def SetLeft( self, value ) : self.Left = value return self def SetBottom( self, value ) : self.Bottom = value return self def SetRight( self, value ) : self.Right = value return self class ShadingPropertySet : HORIZONTAL = 1 VERTICAL = 2 FORWARD_DIAGONAL = 3 BACKWARD_DIAGONAL = 4 VERTICAL_CROSS = 5 DIAGONAL_CROSS = 6 DARK_HORIZONTAL = 7 DARK_VERTICAL = 8 DARK_FORWARD_DIAGONAL = 9 DARK_BACKWARD_DIAGONAL = 10 DARK_VERTICAL_CROSS = 11 DARK_DIAGONAL_CROSS = 12 PATTERNS = [ HORIZONTAL, VERTICAL, FORWARD_DIAGONAL, BACKWARD_DIAGONAL, VERTICAL_CROSS, DIAGONAL_CROSS, DARK_HORIZONTAL, DARK_VERTICAL, DARK_FORWARD_DIAGONAL, DARK_BACKWARD_DIAGONAL, DARK_VERTICAL_CROSS, DARK_DIAGONAL_CROSS ] def __init__( self, shading=None, pattern=None, foreground=None, background=None ) : self.SetShading ( shading ) self.SetForeground( foreground ) self.SetBackground( background ) self.SetPattern ( pattern ) def __deepcopy__( self, memo ) : return ShadingPropertySet( self.Shading, self.Foreground, self.Background, self.Pattern ) def SetShading( self, value ) : self.Shading = value return self def SetPattern( self, value ) : assert value is None or value in self.PATTERNS self.Pattern = value return self def SetForeground( self, value ) : assert not value or isinstance( value, Colour ) self.Foreground = value return self def SetBackground( self, value ) : assert not value or isinstance( value, Colour ) self.Background = value return self class BorderPropertySet : SINGLE = 1 DOUBLE = 2 SHADOWED = 3 DOUBLED = 4 DOTTED = 5 DASHED = 6 HAIRLINE = 7 STYLES = [ SINGLE, DOUBLE, SHADOWED, DOUBLED, DOTTED, DASHED, HAIRLINE ] def __init__( self, width=None, style=None, colour=None, spacing=None ) : self.SetWidth ( width ) self.SetStyle ( style or self.SINGLE ) self.SetColour ( colour ) self.SetSpacing( spacing ) def SetWidth( self, value ) : self.Width = value return self def SetStyle( self, value ) : assert value is None or value in self.STYLES self.Style = value return self def SetColour( self, value ) : assert value is None or isinstance( value, Colour ) self.Colour = value return self def SetSpacing( self, value ) : self.Spacing = value return self class FramePropertySet : def __init__( self, top=None, left=None, bottom=None, right=None ) : self.SetTop ( top ) self.SetLeft ( left ) self.SetBottom( bottom ) self.SetRight ( right ) def SetTop( self, value ) : assert value is None or isinstance( value, BorderPropertySet ) self.Top = value return self def SetLeft( self, value ) : assert value is None or isinstance( value, BorderPropertySet ) self.Left = value return self def SetBottom( self, value ) : assert value is None or isinstance( value, BorderPropertySet ) self.Bottom = value return self def SetRight( self, value ) : assert value is None or isinstance( value, BorderPropertySet ) self.Right = value return self class TabPropertySet : DEFAULT_WIDTH = 720 LEFT = 1 RIGHT = 2 CENTER = 3 DECIMAL = 4 ALIGNMENT = [ LEFT, RIGHT, CENTER, DECIMAL ] DOTS = 1 HYPHENS = 2 UNDERLINE = 3 THICK_LINE = 4 EQUAL_SIGN = 5 LEADERS = [ DOTS, HYPHENS, UNDERLINE, THICK_LINE, EQUAL_SIGN ] def __init__( self, width=None, alignment=None, leader=None ) : self.SetWidth ( width ) self.SetAlignment( alignment or self.LEFT ) self.SetLeader ( leader ) def SetWidth( self, value ) : self.Width = value return self def SetAlignment( self, value ) : assert value in self.ALIGNMENT self.Alignment = value return self def SetLeader( self, value ) : assert not value or value in self.LEADERS self.Leader = value return self class TextPropertySet : def __init__( self, font=None, size=None, bold=None, italic=None, underline=None, colour=None, frame=None, expansion=None ) : self.SetFont ( font ) self.SetSize ( size ) self.SetBold ( bold or False ) self.SetItalic ( italic or False ) self.SetUnderline ( underline or False ) self.SetColour( colour ) self.SetFrame ( frame ) self.SetStrikeThrough ( False ) self.SetDottedUnderline( False ) self.SetDoubleUnderline( False ) self.SetWordUnderline ( False ) self.SetExpansion ( expansion ) def Copy( self ) : return deepcopy( self ) def __deepcopy__( self, memo ) : # the font must remain a reference to the same font that we are looking at # so we want to stop the recursiveness at this point and return an object # with the right references. result = TextPropertySet( self.Font, self.Size, self.Bold, self.Italic, self.Underline, self.Colour, deepcopy( self.Frame, memo ) ) result.SetStrikeThrough( self.StrikeThrough ) return result def SetFont( self, value ) : assert not value or isinstance( value, Font ) self.Font = value return self def SetSize( self, value ) : self.Size = value return self def SetBold( self, value ) : self.Bold = False if value : self.Bold = True return self def SetItalic( self, value ) : self.Italic = False if value : self.Italic = True return self def SetUnderline( self, value ) : self.Underline = False if value : self.Underline = True return self def SetColour( self, value ) : assert value is None or isinstance( value, Colour ) self.Colour = value return self def SetFrame( self, value ) : assert value is None or isinstance( value, BorderPropertySet ) self.Frame = value return self def SetStrikeThrough( self, value ) : self.StrikeThrough = False if value : self.StrikeThrough = True return self def SetDottedUnderline( self, value ) : self.DottedUnderline = False if value : self.DottedUnderline = True return self def SetDoubleUnderline( self, value ) : self.DoubleUnderline = False if value : self.DoubleUnderline = True return self def SetWordUnderline( self, value ) : self.WordUnderline = False if value : self.WordUnderline = True return self def SetExpansion( self, value ) : self.Expansion = value return self class ParagraphPropertySet : LEFT = 1 RIGHT = 2 CENTER = 3 JUSTIFY = 4 DISTRIBUTE = 5 ALIGNMENT = [ LEFT, RIGHT, CENTER, JUSTIFY, DISTRIBUTE ] def __init__( self, alignment=None, space_before=None, space_after=None, tabs=None, first_line_indent=None, left_indent=None, right_indent=None, page_break_before=None ) : self.SetAlignment ( alignment or self.LEFT ) self.SetSpaceBefore( space_before ) self.SetSpaceAfter ( space_after ) self.Tabs = [] if tabs : apply( self.SetTabs, tabs ) self.SetFirstLineIndent( first_line_indent or None ) self.SetLeftIndent ( left_indent or None ) self.SetRightIndent ( right_indent or None ) self.SetPageBreakBefore( page_break_before ) self.SetSpaceBetweenLines( None ) def Copy( self ) : return deepcopy( self ) def SetAlignment( self, value ) : assert not value or value in self.ALIGNMENT self.Alignment = value or self.LEFT return self def SetSpaceBefore( self, value ) : self.SpaceBefore = value return self def SetSpaceAfter( self, value ) : self.SpaceAfter = value return self def SetTabs( self, *params ) : self.Tabs = params return self def SetFirstLineIndent( self, value ) : self.FirstLineIndent = value return self def SetLeftIndent( self, value ) : self.LeftIndent = value return self def SetRightIndent( self, value ) : self.RightIndent = value return self def SetSpaceBetweenLines( self, value ) : self.SpaceBetweenLines = value return self def SetPageBreakBefore( self, value ) : self.PageBreakBefore = False if value : self.PageBreakBefore = True return self # Some short cuts to make the code a bit easier to read MarginsPS = MarginsPropertySet ShadingPS = ShadingPropertySet BorderPS = BorderPropertySet FramePS = FramePropertySet TabPS = TabPropertySet TextPS = TextPropertySet ParagraphPS = ParagraphPropertySet
Python
from PropertySets import * from Elements import * from Styles import * from Renderer import * def dumps(doc): import cStringIO s=cStringIO.StringIO() r=Renderer() r.Write(doc,s) return s.getvalue()
Python
class ViewKind : """An integer (0-5) that represents the view mode of the document.""" NONE = 0 PageLayout = 1 Outline = 2 MasterDocument = 3 Normal = 4 OnlineLayout = 5 DEFAULT = PageLayout def _IsValid( cls, value ) : return value in [ 0, 1, 2, 3, 4, 5 ] IsValid = classmethod( _IsValid ) class ViewScale : """Zoom level of the document; the N argument is a value representing a percentage (the default is 100).""" def _IsValid( cls, value ) : return value is None or (0 < value < 101) IsValid = classmethod( _IsValid ) class ViewZoomKind : """An integer (0 to 2) that represents the zoom kind of the document.""" NONE = 0 FullPage = 1 BestFit = 2 def _IsValid( cls, value ) : return value in [ None, 0, 1, 2 ] IsValid = classmethod( _IsValid ) class Languages : NoLanguage = 1024 Albanian = 1052 Arabic = 1025 Bahasa = 1057 BelgianDutch = 2067 BelgianFrench = 2060 BrazilianPortuguese = 1046 Bulgarian = 1026 Catalan = 1027 CroatoSerbianLatin = 1050 Czech = 1029 Danish = 1030 Dutch = 1043 EnglishAustralian = 3081 EnglishUK = 2057 EnglishUS = 1033 Finnish = 1035 French = 1036 FrenchCanadian = 3084 German = 1031 Greek = 1032 Hebrew = 1037 Hungarian = 1038 Icelandic = 1039 Italian = 1040 Japanese = 1041 Korean = 1042 NorwegianBokmal = 1044 NorwegianNynorsk = 2068 Polish = 1045 Portuguese = 2070 RhaetoRomanic = 1047 Romanian = 1048 Russian = 1049 SerboCroatianCyrillic = 2074 SimplifiedChinese = 2052 Slovak = 1051 SpanishCastilian = 1034 SpanishMexican = 2058 Swedish = 1053 SwissFrench = 4108 SwissGerman = 2055 SwissItalian = 2064 Thai = 1054 TraditionalChinese = 1028 Turkish = 1055 Urdu = 1056 SesothoSotho = 1072 Afrikaans = 1078 Zulu = 1077 Xhosa = 1076 Venda = 1075 Tswana = 1074 Tsonga = 1073 FarsiPersian = 1065 Codes = [ 1024, 1052, 1025, 1057, 2067, 2060, 1046, 1026, 1027, 1050, 1029, 1030, 1043, 3081, 2057, 1033, 1035, 1036, 3084, 1031, 1032, 1037, 1038, 1039, 1040, 1041, 1042, 1044, 2068, 1045, 2070, 1047, 1048, 1049, 2074, 2052, 1051, 1034, 2058, 1053, 4108, 2055, 2064, 1054, 1028, 1055, 1056, 1072, 1078, 1077, 1076, 1075, 1074, 1073, 1065 ] # make it Australian as that is what I use most of the time DEFAULT = EnglishAustralian def _IsValid( cls, value ) : return value in cls.Codes IsValid = classmethod( _IsValid ) if __name__ == '__main__' : PrintHexTable()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Developed by Robin Bhattacharyya (memecache for GAE) Released under the web2py license (LGPL) from gluon.contrib.gae_memcache import MemcacheClient cache.ram=cache.disk=MemcacheClient(request) """ import time from google.appengine.api.memcache import Client class MemcacheClient(Client): def __init__(self, request): self.request = request Client.__init__(self) def __call__( self, key, f, time_expire=300, ): key = '%s/%s' % (self.request.application, key) dt = time_expire value = None obj = self.get(key) if obj and (dt == None or obj[0] > time.time() - dt): value = obj[1] elif f is None: if obj: self.delete(key) else: value = f() self.set(key, (time.time(), value)) return value def increment(self, key, value=1): key = '%s/%s' % (self.request.application, key) obj = self.get(key) if obj: value = obj[1] + value self.set((time.time(), value)) return value
Python
"""Implementation of JSONDecoder """ import re import sys import struct from scanner import make_scanner def _import_c_scanstring(): try: raise ImportError # because assumes simplejson in path from simplejson._speedups import scanstring return scanstring except ImportError: return None c_scanstring = _import_c_scanstring() __all__ = ['JSONDecoder'] FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL def _floatconstants(): _BYTES = '7FF80000000000007FF0000000000000'.decode('hex') # The struct module in Python 2.4 would get frexp() out of range here # when an endian is specified in the format string. Fixed in Python 2.5+ if sys.byteorder != 'big': _BYTES = _BYTES[:8][::-1] + _BYTES[8:][::-1] nan, inf = struct.unpack('dd', _BYTES) return nan, inf, -inf NaN, PosInf, NegInf = _floatconstants() class JSONDecodeError(ValueError): """Subclass of ValueError with the following additional properties: msg: The unformatted error message doc: The JSON document being parsed pos: The start index of doc where parsing failed end: The end index of doc where parsing failed (may be None) lineno: The line corresponding to pos colno: The column corresponding to pos endlineno: The line corresponding to end (may be None) endcolno: The column corresponding to end (may be None) """ def __init__(self, msg, doc, pos, end=None): ValueError.__init__(self, errmsg(msg, doc, pos, end=end)) self.msg = msg self.doc = doc self.pos = pos self.end = end self.lineno, self.colno = linecol(doc, pos) if end is not None: self.endlineno, self.endcolno = linecol(doc, end) else: self.endlineno, self.endcolno = None, None def linecol(doc, pos): lineno = doc.count('\n', 0, pos) + 1 if lineno == 1: colno = pos else: colno = pos - doc.rindex('\n', 0, pos) return lineno, colno def errmsg(msg, doc, pos, end=None): # Note that this function is called from _speedups lineno, colno = linecol(doc, pos) if end is None: #fmt = '{0}: line {1} column {2} (char {3})' #return fmt.format(msg, lineno, colno, pos) fmt = '%s: line %d column %d (char %d)' return fmt % (msg, lineno, colno, pos) endlineno, endcolno = linecol(doc, end) #fmt = '{0}: line {1} column {2} - line {3} column {4} (char {5} - {6})' #return fmt.format(msg, lineno, colno, endlineno, endcolno, pos, end) fmt = '%s: line %d column %d - line %d column %d (char %d - %d)' return fmt % (msg, lineno, colno, endlineno, endcolno, pos, end) _CONSTANTS = { '-Infinity': NegInf, 'Infinity': PosInf, 'NaN': NaN, } STRINGCHUNK = re.compile(r'(.*?)(["\\\x00-\x1f])', FLAGS) BACKSLASH = { '"': u'"', '\\': u'\\', '/': u'/', 'b': u'\b', 'f': u'\f', 'n': u'\n', 'r': u'\r', 't': u'\t', } DEFAULT_ENCODING = "utf-8" def py_scanstring(s, end, encoding=None, strict=True, _b=BACKSLASH, _m=STRINGCHUNK.match): """Scan the string s for a JSON string. End is the index of the character in s after the quote that started the JSON string. Unescapes all valid JSON string escape sequences and raises ValueError on attempt to decode an invalid string. If strict is False then literal control characters are allowed in the string. Returns a tuple of the decoded string and the index of the character in s after the end quote.""" if encoding is None: encoding = DEFAULT_ENCODING chunks = [] _append = chunks.append begin = end - 1 while 1: chunk = _m(s, end) if chunk is None: raise JSONDecodeError( "Unterminated string starting at", s, begin) end = chunk.end() content, terminator = chunk.groups() # Content is contains zero or more unescaped string characters if content: if not isinstance(content, unicode): content = unicode(content, encoding) _append(content) # Terminator is the end of string, a literal control character, # or a backslash denoting that an escape sequence follows if terminator == '"': break elif terminator != '\\': if strict: msg = "Invalid control character %r at" % (terminator,) #msg = "Invalid control character {0!r} at".format(terminator) raise JSONDecodeError(msg, s, end) else: _append(terminator) continue try: esc = s[end] except IndexError: raise JSONDecodeError( "Unterminated string starting at", s, begin) # If not a unicode escape sequence, must be in the lookup table if esc != 'u': try: char = _b[esc] except KeyError: msg = "Invalid \\escape: " + repr(esc) raise JSONDecodeError(msg, s, end) end += 1 else: # Unicode escape sequence esc = s[end + 1:end + 5] next_end = end + 5 if len(esc) != 4: msg = "Invalid \\uXXXX escape" raise JSONDecodeError(msg, s, end) uni = int(esc, 16) # Check for surrogate pair on UCS-4 systems if 0xd800 <= uni <= 0xdbff and sys.maxunicode > 65535: msg = "Invalid \\uXXXX\\uXXXX surrogate pair" if not s[end + 5:end + 7] == '\\u': raise JSONDecodeError(msg, s, end) esc2 = s[end + 7:end + 11] if len(esc2) != 4: raise JSONDecodeError(msg, s, end) uni2 = int(esc2, 16) uni = 0x10000 + (((uni - 0xd800) << 10) | (uni2 - 0xdc00)) next_end += 6 char = unichr(uni) end = next_end # Append the unescaped character _append(char) return u''.join(chunks), end # Use speedup if available scanstring = c_scanstring or py_scanstring WHITESPACE = re.compile(r'[ \t\n\r]*', FLAGS) WHITESPACE_STR = ' \t\n\r' def JSONObject((s, end), encoding, strict, scan_once, object_hook, object_pairs_hook, memo=None, _w=WHITESPACE.match, _ws=WHITESPACE_STR): # Backwards compatibility if memo is None: memo = {} memo_get = memo.setdefault pairs = [] # Use a slice to prevent IndexError from being raised, the following # check will raise a more specific ValueError if the string is empty nextchar = s[end:end + 1] # Normally we expect nextchar == '"' if nextchar != '"': if nextchar in _ws: end = _w(s, end).end() nextchar = s[end:end + 1] # Trivial empty object if nextchar == '}': if object_pairs_hook is not None: result = object_pairs_hook(pairs) return result, end + 1 pairs = {} if object_hook is not None: pairs = object_hook(pairs) return pairs, end + 1 elif nextchar != '"': raise JSONDecodeError("Expecting property name", s, end) end += 1 while True: key, end = scanstring(s, end, encoding, strict) key = memo_get(key, key) # To skip some function call overhead we optimize the fast paths where # the JSON key separator is ": " or just ":". if s[end:end + 1] != ':': end = _w(s, end).end() if s[end:end + 1] != ':': raise JSONDecodeError("Expecting : delimiter", s, end) end += 1 try: if s[end] in _ws: end += 1 if s[end] in _ws: end = _w(s, end + 1).end() except IndexError: pass try: value, end = scan_once(s, end) except StopIteration: raise JSONDecodeError("Expecting object", s, end) pairs.append((key, value)) try: nextchar = s[end] if nextchar in _ws: end = _w(s, end + 1).end() nextchar = s[end] except IndexError: nextchar = '' end += 1 if nextchar == '}': break elif nextchar != ',': raise JSONDecodeError("Expecting , delimiter", s, end - 1) try: nextchar = s[end] if nextchar in _ws: end += 1 nextchar = s[end] if nextchar in _ws: end = _w(s, end + 1).end() nextchar = s[end] except IndexError: nextchar = '' end += 1 if nextchar != '"': raise JSONDecodeError("Expecting property name", s, end - 1) if object_pairs_hook is not None: result = object_pairs_hook(pairs) return result, end pairs = dict(pairs) if object_hook is not None: pairs = object_hook(pairs) return pairs, end def JSONArray((s, end), scan_once, _w=WHITESPACE.match, _ws=WHITESPACE_STR): values = [] nextchar = s[end:end + 1] if nextchar in _ws: end = _w(s, end + 1).end() nextchar = s[end:end + 1] # Look-ahead for trivial empty array if nextchar == ']': return values, end + 1 _append = values.append while True: try: value, end = scan_once(s, end) except StopIteration: raise JSONDecodeError("Expecting object", s, end) _append(value) nextchar = s[end:end + 1] if nextchar in _ws: end = _w(s, end + 1).end() nextchar = s[end:end + 1] end += 1 if nextchar == ']': break elif nextchar != ',': raise JSONDecodeError("Expecting , delimiter", s, end) try: if s[end] in _ws: end += 1 if s[end] in _ws: end = _w(s, end + 1).end() except IndexError: pass return values, end class JSONDecoder(object): """Simple JSON <http://json.org> decoder Performs the following translations in decoding by default: +---------------+-------------------+ | JSON | Python | +===============+===================+ | object | dict | +---------------+-------------------+ | array | list | +---------------+-------------------+ | string | unicode | +---------------+-------------------+ | number (int) | int, long | +---------------+-------------------+ | number (real) | float | +---------------+-------------------+ | true | True | +---------------+-------------------+ | false | False | +---------------+-------------------+ | null | None | +---------------+-------------------+ It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as their corresponding ``float`` values, which is outside the JSON spec. """ def __init__(self, encoding=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None): """ *encoding* determines the encoding used to interpret any :class:`str` objects decoded by this instance (``'utf-8'`` by default). It has no effect when decoding :class:`unicode` objects. Note that currently only encodings that are a superset of ASCII work, strings of other encodings should be passed in as :class:`unicode`. *object_hook*, if specified, will be called with the result of every JSON object decoded and its return value will be used in place of the given :class:`dict`. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting). *object_pairs_hook* is an optional function that will be called with the result of any object literal decode with an ordered list of pairs. The return value of *object_pairs_hook* will be used instead of the :class:`dict`. This feature can be used to implement custom decoders that rely on the order that the key and value pairs are decoded (for example, :func:`collections.OrderedDict` will remember the order of insertion). If *object_hook* is also defined, the *object_pairs_hook* takes priority. *parse_float*, if specified, will be called with the string of every JSON float to be decoded. By default, this is equivalent to ``float(num_str)``. This can be used to use another datatype or parser for JSON floats (e.g. :class:`decimal.Decimal`). *parse_int*, if specified, will be called with the string of every JSON int to be decoded. By default, this is equivalent to ``int(num_str)``. This can be used to use another datatype or parser for JSON integers (e.g. :class:`float`). *parse_constant*, if specified, will be called with one of the following strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``. This can be used to raise an exception if invalid JSON numbers are encountered. *strict* controls the parser's behavior when it encounters an invalid control character in a string. The default setting of ``True`` means that unescaped control characters are parse errors, if ``False`` then control characters will be allowed in strings. """ self.encoding = encoding self.object_hook = object_hook self.object_pairs_hook = object_pairs_hook self.parse_float = parse_float or float self.parse_int = parse_int or int self.parse_constant = parse_constant or _CONSTANTS.__getitem__ self.strict = strict self.parse_object = JSONObject self.parse_array = JSONArray self.parse_string = scanstring self.memo = {} self.scan_once = make_scanner(self) def decode(self, s, _w=WHITESPACE.match): """Return the Python representation of ``s`` (a ``str`` or ``unicode`` instance containing a JSON document) """ obj, end = self.raw_decode(s, idx=_w(s, 0).end()) end = _w(s, end).end() if end != len(s): raise JSONDecodeError("Extra data", s, end, len(s)) return obj def raw_decode(self, s, idx=0): """Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning with a JSON document) and return a 2-tuple of the Python representation and the index in ``s`` where the document ended. This can be used to decode a JSON document from a string that may have extraneous data at the end. """ try: obj, end = self.scan_once(s, idx) except StopIteration: raise JSONDecodeError("No JSON object could be decoded", s, idx) return obj, end
Python
"""Drop-in replacement for collections.OrderedDict by Raymond Hettinger http://code.activestate.com/recipes/576693/ """ from UserDict import DictMixin # Modified from original to support Python 2.4, see # http://code.google.com/p/simplejson/issues/detail?id=53 try: all except NameError: def all(seq): for elem in seq: if not elem: return False return True class OrderedDict(dict, DictMixin): def __init__(self, *args, **kwds): if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) try: self.__end except AttributeError: self.clear() self.update(*args, **kwds) def clear(self): self.__end = end = [] end += [None, end, end] # sentinel node for doubly linked list self.__map = {} # key --> [key, prev, next] dict.clear(self) def __setitem__(self, key, value): if key not in self: end = self.__end curr = end[1] curr[2] = end[1] = self.__map[key] = [key, curr, end] dict.__setitem__(self, key, value) def __delitem__(self, key): dict.__delitem__(self, key) key, prev, next = self.__map.pop(key) prev[2] = next next[1] = prev def __iter__(self): end = self.__end curr = end[2] while curr is not end: yield curr[0] curr = curr[2] def __reversed__(self): end = self.__end curr = end[1] while curr is not end: yield curr[0] curr = curr[1] def popitem(self, last=True): if not self: raise KeyError('dictionary is empty') # Modified from original to support Python 2.4, see # http://code.google.com/p/simplejson/issues/detail?id=53 if last: key = reversed(self).next() else: key = iter(self).next() value = self.pop(key) return key, value def __reduce__(self): items = [[k, self[k]] for k in self] tmp = self.__map, self.__end del self.__map, self.__end inst_dict = vars(self).copy() self.__map, self.__end = tmp if inst_dict: return (self.__class__, (items,), inst_dict) return self.__class__, (items,) def keys(self): return list(self) setdefault = DictMixin.setdefault update = DictMixin.update pop = DictMixin.pop values = DictMixin.values items = DictMixin.items iterkeys = DictMixin.iterkeys itervalues = DictMixin.itervalues iteritems = DictMixin.iteritems def __repr__(self): if not self: return '%s()' % (self.__class__.__name__,) return '%s(%r)' % (self.__class__.__name__, self.items()) def copy(self): return self.__class__(self) @classmethod def fromkeys(cls, iterable, value=None): d = cls() for key in iterable: d[key] = value return d def __eq__(self, other): if isinstance(other, OrderedDict): return len(self)==len(other) and \ all(p==q for p, q in zip(self.items(), other.items())) return dict.__eq__(self, other) def __ne__(self, other): return not self == other
Python
"""JSON token scanner """ import re def _import_c_make_scanner(): try: raise ImportError # because assumes simplejson in path from simplejson._speedups import make_scanner return make_scanner except ImportError: return None c_make_scanner = _import_c_make_scanner() __all__ = ['make_scanner'] NUMBER_RE = re.compile( r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?', (re.VERBOSE | re.MULTILINE | re.DOTALL)) def py_make_scanner(context): parse_object = context.parse_object parse_array = context.parse_array parse_string = context.parse_string match_number = NUMBER_RE.match encoding = context.encoding strict = context.strict parse_float = context.parse_float parse_int = context.parse_int parse_constant = context.parse_constant object_hook = context.object_hook object_pairs_hook = context.object_pairs_hook memo = context.memo def _scan_once(string, idx): try: nextchar = string[idx] except IndexError: raise StopIteration if nextchar == '"': return parse_string(string, idx + 1, encoding, strict) elif nextchar == '{': return parse_object((string, idx + 1), encoding, strict, _scan_once, object_hook, object_pairs_hook, memo) elif nextchar == '[': return parse_array((string, idx + 1), _scan_once) elif nextchar == 'n' and string[idx:idx + 4] == 'null': return None, idx + 4 elif nextchar == 't' and string[idx:idx + 4] == 'true': return True, idx + 4 elif nextchar == 'f' and string[idx:idx + 5] == 'false': return False, idx + 5 m = match_number(string, idx) if m is not None: integer, frac, exp = m.groups() if frac or exp: res = parse_float(integer + (frac or '') + (exp or '')) else: res = parse_int(integer) return res, m.end() elif nextchar == 'N' and string[idx:idx + 3] == 'NaN': return parse_constant('NaN'), idx + 3 elif nextchar == 'I' and string[idx:idx + 8] == 'Infinity': return parse_constant('Infinity'), idx + 8 elif nextchar == '-' and string[idx:idx + 9] == '-Infinity': return parse_constant('-Infinity'), idx + 9 else: raise StopIteration def scan_once(string, idx): try: return _scan_once(string, idx) finally: memo.clear() return scan_once make_scanner = c_make_scanner or py_make_scanner
Python
"""Implementation of JSONEncoder """ import re from decimal import Decimal def _import_speedups(): try: raise ImportError # because assumes simplejson in path from simplejson import _speedups return _speedups.encode_basestring_ascii, _speedups.make_encoder except ImportError: return None, None c_encode_basestring_ascii, c_make_encoder = _import_speedups() from decoder import PosInf ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]') ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])') HAS_UTF8 = re.compile(r'[\x80-\xff]') ESCAPE_DCT = { '\\': '\\\\', '"': '\\"', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t', } for i in range(0x20): #ESCAPE_DCT.setdefault(chr(i), '\\u{0:04x}'.format(i)) ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,)) FLOAT_REPR = repr def encode_basestring(s): """Return a JSON representation of a Python string """ if isinstance(s, str) and HAS_UTF8.search(s) is not None: s = s.decode('utf-8') def replace(match): return ESCAPE_DCT[match.group(0)] return u'"' + ESCAPE.sub(replace, s) + u'"' def py_encode_basestring_ascii(s): """Return an ASCII-only JSON representation of a Python string """ if isinstance(s, str) and HAS_UTF8.search(s) is not None: s = s.decode('utf-8') def replace(match): s = match.group(0) try: return ESCAPE_DCT[s] except KeyError: n = ord(s) if n < 0x10000: #return '\\u{0:04x}'.format(n) return '\\u%04x' % (n,) else: # surrogate pair n -= 0x10000 s1 = 0xd800 | ((n >> 10) & 0x3ff) s2 = 0xdc00 | (n & 0x3ff) #return '\\u{0:04x}\\u{1:04x}'.format(s1, s2) return '\\u%04x\\u%04x' % (s1, s2) return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"' encode_basestring_ascii = ( c_encode_basestring_ascii or py_encode_basestring_ascii) class JSONEncoder(object): """Extensible JSON <http://json.org> encoder for Python data structures. Supports the following objects and types by default: +-------------------+---------------+ | Python | JSON | +===================+===============+ | dict | object | +-------------------+---------------+ | list, tuple | array | +-------------------+---------------+ | str, unicode | string | +-------------------+---------------+ | int, long, float | number | +-------------------+---------------+ | True | true | +-------------------+---------------+ | False | false | +-------------------+---------------+ | None | null | +-------------------+---------------+ To extend this to recognize other objects, subclass and implement a ``.default()`` method with another method that returns a serializable object for ``o`` if possible, otherwise it should call the superclass implementation (to raise ``TypeError``). """ item_separator = ', ' key_separator = ': ' def __init__(self, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=False): """Constructor for JSONEncoder, with sensible defaults. If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, long, float or None. If skipkeys is True, such items are simply skipped. If ensure_ascii is true, the output is guaranteed to be str objects with all incoming unicode characters escaped. If ensure_ascii is false, the output will be unicode object. If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place. If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats. If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis. If indent is a string, then JSON array elements and object members will be pretty-printed with a newline followed by that string repeated for each level of nesting. ``None`` (the default) selects the most compact representation without any newlines. For backwards compatibility with versions of simplejson earlier than 2.1.0, an integer is also accepted and is converted to a string with that many spaces. If specified, separators should be a (item_separator, key_separator) tuple. The default is (', ', ': '). To get the most compact JSON representation you should specify (',', ':') to eliminate whitespace. If specified, default is a function that gets called for objects that can't otherwise be serialized. It should return a JSON encodable version of the object or raise a ``TypeError``. If encoding is not None, then all input strings will be transformed into unicode using that encoding prior to JSON-encoding. The default is UTF-8. If use_decimal is true (not the default), ``decimal.Decimal`` will be supported directly by the encoder. For the inverse, decode JSON with ``parse_float=decimal.Decimal``. """ self.skipkeys = skipkeys self.ensure_ascii = ensure_ascii self.check_circular = check_circular self.allow_nan = allow_nan self.sort_keys = sort_keys self.use_decimal = use_decimal if isinstance(indent, (int, long)): indent = ' ' * indent self.indent = indent if separators is not None: self.item_separator, self.key_separator = separators if default is not None: self.default = default self.encoding = encoding def default(self, o): """Implement this method in a subclass such that it returns a serializable object for ``o``, or calls the base implementation (to raise a ``TypeError``). For example, to support arbitrary iterators, you could implement default like this:: def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, o) """ raise TypeError(repr(o) + " is not JSON serializable") def encode(self, o): """Return a JSON string representation of a Python data structure. >>> from simplejson import JSONEncoder >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) '{"foo": ["bar", "baz"]}' """ # This is for extremely simple cases and benchmarks. if isinstance(o, basestring): if isinstance(o, str): _encoding = self.encoding if (_encoding is not None and not (_encoding == 'utf-8')): o = o.decode(_encoding) if self.ensure_ascii: return encode_basestring_ascii(o) else: return encode_basestring(o) # This doesn't pass the iterator directly to ''.join() because the # exceptions aren't as detailed. The list call should be roughly # equivalent to the PySequence_Fast that ''.join() would do. chunks = self.iterencode(o, _one_shot=True) if not isinstance(chunks, (list, tuple)): chunks = list(chunks) if self.ensure_ascii: return ''.join(chunks) else: return u''.join(chunks) def iterencode(self, o, _one_shot=False): """Encode the given object and yield each string representation as available. For example:: for chunk in JSONEncoder().iterencode(bigobject): mysocket.write(chunk) """ if self.check_circular: markers = {} else: markers = None if self.ensure_ascii: _encoder = encode_basestring_ascii else: _encoder = encode_basestring if self.encoding != 'utf-8': def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding): if isinstance(o, str): o = o.decode(_encoding) return _orig_encoder(o) def floatstr(o, allow_nan=self.allow_nan, _repr=FLOAT_REPR, _inf=PosInf, _neginf=-PosInf): # Check for specials. Note that this type of test is processor # and/or platform-specific, so do tests which don't depend on # the internals. if o != o: text = 'NaN' elif o == _inf: text = 'Infinity' elif o == _neginf: text = '-Infinity' else: return _repr(o) if not allow_nan: raise ValueError( "Out of range float values are not JSON compliant: " + repr(o)) return text key_memo = {} if (_one_shot and c_make_encoder is not None and self.indent is None): _iterencode = c_make_encoder( markers, self.default, _encoder, self.indent, self.key_separator, self.item_separator, self.sort_keys, self.skipkeys, self.allow_nan, key_memo, self.use_decimal) else: _iterencode = _make_iterencode( markers, self.default, _encoder, self.indent, floatstr, self.key_separator, self.item_separator, self.sort_keys, self.skipkeys, _one_shot, self.use_decimal) try: return _iterencode(o, 0) finally: key_memo.clear() class JSONEncoderForHTML(JSONEncoder): """An encoder that produces JSON safe to embed in HTML. To embed JSON content in, say, a script tag on a web page, the characters &, < and > should be escaped. They cannot be escaped with the usual entities (e.g. &amp;) because they are not expanded within <script> tags. """ def encode(self, o): # Override JSONEncoder.encode because it has hacks for # performance that make things more complicated. chunks = self.iterencode(o, True) if self.ensure_ascii: return ''.join(chunks) else: return u''.join(chunks) def iterencode(self, o, _one_shot=False): chunks = super(JSONEncoderForHTML, self).iterencode(o, _one_shot) for chunk in chunks: chunk = chunk.replace('&', '\\u0026') chunk = chunk.replace('<', '\\u003c') chunk = chunk.replace('>', '\\u003e') yield chunk def _make_iterencode(markers, _default, _encoder, _indent, _floatstr, _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot, _use_decimal, ## HACK: hand-optimized bytecode; turn globals into locals False=False, True=True, ValueError=ValueError, basestring=basestring, Decimal=Decimal, dict=dict, float=float, id=id, int=int, isinstance=isinstance, list=list, long=long, str=str, tuple=tuple, ): def _iterencode_list(lst, _current_indent_level): if not lst: yield '[]' return if markers is not None: markerid = id(lst) if markerid in markers: raise ValueError("Circular reference detected") markers[markerid] = lst buf = '[' if _indent is not None: _current_indent_level += 1 newline_indent = '\n' + (_indent * _current_indent_level) separator = _item_separator + newline_indent buf += newline_indent else: newline_indent = None separator = _item_separator first = True for value in lst: if first: first = False else: buf = separator if isinstance(value, basestring): yield buf + _encoder(value) elif value is None: yield buf + 'null' elif value is True: yield buf + 'true' elif value is False: yield buf + 'false' elif isinstance(value, (int, long)): yield buf + str(value) elif isinstance(value, float): yield buf + _floatstr(value) elif _use_decimal and isinstance(value, Decimal): yield buf + str(value) else: yield buf if isinstance(value, (list, tuple)): chunks = _iterencode_list(value, _current_indent_level) elif isinstance(value, dict): chunks = _iterencode_dict(value, _current_indent_level) else: chunks = _iterencode(value, _current_indent_level) for chunk in chunks: yield chunk if newline_indent is not None: _current_indent_level -= 1 yield '\n' + (_indent * _current_indent_level) yield ']' if markers is not None: del markers[markerid] def _iterencode_dict(dct, _current_indent_level): if not dct: yield '{}' return if markers is not None: markerid = id(dct) if markerid in markers: raise ValueError("Circular reference detected") markers[markerid] = dct yield '{' if _indent is not None: _current_indent_level += 1 newline_indent = '\n' + (_indent * _current_indent_level) item_separator = _item_separator + newline_indent yield newline_indent else: newline_indent = None item_separator = _item_separator first = True if _sort_keys: items = dct.items() items.sort(key=lambda kv: kv[0]) else: items = dct.iteritems() for key, value in items: if isinstance(key, basestring): pass # JavaScript is weakly typed for these, so it makes sense to # also allow them. Many encoders seem to do something like this. elif isinstance(key, float): key = _floatstr(key) elif key is True: key = 'true' elif key is False: key = 'false' elif key is None: key = 'null' elif isinstance(key, (int, long)): key = str(key) elif _skipkeys: continue else: raise TypeError("key " + repr(key) + " is not a string") if first: first = False else: yield item_separator yield _encoder(key) yield _key_separator if isinstance(value, basestring): yield _encoder(value) elif value is None: yield 'null' elif value is True: yield 'true' elif value is False: yield 'false' elif isinstance(value, (int, long)): yield str(value) elif isinstance(value, float): yield _floatstr(value) elif _use_decimal and isinstance(value, Decimal): yield str(value) else: if isinstance(value, (list, tuple)): chunks = _iterencode_list(value, _current_indent_level) elif isinstance(value, dict): chunks = _iterencode_dict(value, _current_indent_level) else: chunks = _iterencode(value, _current_indent_level) for chunk in chunks: yield chunk if newline_indent is not None: _current_indent_level -= 1 yield '\n' + (_indent * _current_indent_level) yield '}' if markers is not None: del markers[markerid] def _iterencode(o, _current_indent_level): if isinstance(o, basestring): yield _encoder(o) elif o is None: yield 'null' elif o is True: yield 'true' elif o is False: yield 'false' elif isinstance(o, (int, long)): yield str(o) elif isinstance(o, float): yield _floatstr(o) elif isinstance(o, (list, tuple)): for chunk in _iterencode_list(o, _current_indent_level): yield chunk elif isinstance(o, dict): for chunk in _iterencode_dict(o, _current_indent_level): yield chunk elif _use_decimal and isinstance(o, Decimal): yield str(o) else: if markers is not None: markerid = id(o) if markerid in markers: raise ValueError("Circular reference detected") markers[markerid] = o o = _default(o) for chunk in _iterencode(o, _current_indent_level): yield chunk if markers is not None: del markers[markerid] return _iterencode
Python
r"""JSON (JavaScript Object Notation) <http://json.org> is a subset of JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data interchange format. :mod:`simplejson` exposes an API familiar to users of the standard library :mod:`marshal` and :mod:`pickle` modules. It is the externally maintained version of the :mod:`json` library contained in Python 2.6, but maintains compatibility with Python 2.4 and Python 2.5 and (currently) has significant performance advantages, even without using the optional C extension for speedups. Encoding basic Python object hierarchies:: >>> import simplejson as json >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) '["foo", {"bar": ["baz", null, 1.0, 2]}]' >>> print json.dumps("\"foo\bar") "\"foo\bar" >>> print json.dumps(u'\u1234') "\u1234" >>> print json.dumps('\\') "\\" >>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True) {"a": 0, "b": 0, "c": 0} >>> from StringIO import StringIO >>> io = StringIO() >>> json.dump(['streaming API'], io) >>> io.getvalue() '["streaming API"]' Compact encoding:: >>> import simplejson as json >>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':')) '[1,2,3,{"4":5,"6":7}]' Pretty printing:: >>> import simplejson as json >>> s = json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=' ') >>> print '\n'.join([l.rstrip() for l in s.splitlines()]) { "4": 5, "6": 7 } Decoding JSON:: >>> import simplejson as json >>> obj = [u'foo', {u'bar': [u'baz', None, 1.0, 2]}] >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj True >>> json.loads('"\\"foo\\bar"') == u'"foo\x08ar' True >>> from StringIO import StringIO >>> io = StringIO('["streaming API"]') >>> json.load(io)[0] == 'streaming API' True Specializing JSON object decoding:: >>> import simplejson as json >>> def as_complex(dct): ... if '__complex__' in dct: ... return complex(dct['real'], dct['imag']) ... return dct ... >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}', ... object_hook=as_complex) (1+2j) >>> from decimal import Decimal >>> json.loads('1.1', parse_float=Decimal) == Decimal('1.1') True Specializing JSON object encoding:: >>> import simplejson as json >>> def encode_complex(obj): ... if isinstance(obj, complex): ... return [obj.real, obj.imag] ... raise TypeError(repr(o) + " is not JSON serializable") ... >>> json.dumps(2 + 1j, default=encode_complex) '[2.0, 1.0]' >>> json.JSONEncoder(default=encode_complex).encode(2 + 1j) '[2.0, 1.0]' >>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j)) '[2.0, 1.0]' Using simplejson.tool from the shell to validate and pretty-print:: $ echo '{"json":"obj"}' | python -m simplejson.tool { "json": "obj" } $ echo '{ 1.2:3.4}' | python -m simplejson.tool Expecting property name: line 1 column 2 (char 2) """ __version__ = '2.1.3' __all__ = [ 'dump', 'dumps', 'load', 'loads', 'JSONDecoder', 'JSONDecodeError', 'JSONEncoder', 'OrderedDict', ] __author__ = 'Bob Ippolito <bob@redivi.com>' from decimal import Decimal from decoder import JSONDecoder, JSONDecodeError from encoder import JSONEncoder def _import_OrderedDict(): import collections try: return collections.OrderedDict except AttributeError: import ordered_dict return ordered_dict.OrderedDict OrderedDict = _import_OrderedDict() def _import_c_make_encoder(): try: raise ImportError # because assumes simplejson in path from simplejson._speedups import make_encoder return make_encoder except ImportError: return None _default_encoder = JSONEncoder( skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=False, ) def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=False, **kw): """Serialize ``obj`` as a JSON formatted stream to ``fp`` (a ``.write()``-supporting file-like object). If ``skipkeys`` is true then ``dict`` keys that are not basic types (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) will be skipped instead of raising a ``TypeError``. If ``ensure_ascii`` is false, then the some chunks written to ``fp`` may be ``unicode`` instances, subject to normal Python ``str`` to ``unicode`` coercion rules. Unless ``fp.write()`` explicitly understands ``unicode`` (as in ``codecs.getwriter()``) this is likely to cause an error. If ``check_circular`` is false, then the circular reference check for container types will be skipped and a circular reference will result in an ``OverflowError`` (or worse). If ``allow_nan`` is false, then it will be a ``ValueError`` to serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). If *indent* is a string, then JSON array elements and object members will be pretty-printed with a newline followed by that string repeated for each level of nesting. ``None`` (the default) selects the most compact representation without any newlines. For backwards compatibility with versions of simplejson earlier than 2.1.0, an integer is also accepted and is converted to a string with that many spaces. If ``separators`` is an ``(item_separator, dict_separator)`` tuple then it will be used instead of the default ``(', ', ': ')`` separators. ``(',', ':')`` is the most compact JSON representation. ``encoding`` is the character encoding for str instances, default is UTF-8. ``default(obj)`` is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. If *use_decimal* is true (default: ``False``) then decimal.Decimal will be natively serialized to JSON with full precision. To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the ``.default()`` method to serialize additional types), specify it with the ``cls`` kwarg. """ # cached encoder if (not skipkeys and ensure_ascii and check_circular and allow_nan and cls is None and indent is None and separators is None and encoding == 'utf-8' and default is None and not use_decimal and not kw): iterable = _default_encoder.iterencode(obj) else: if cls is None: cls = JSONEncoder iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, encoding=encoding, default=default, use_decimal=use_decimal, **kw).iterencode(obj) # could accelerate with writelines in some versions of Python, at # a debuggability cost for chunk in iterable: fp.write(chunk) def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=False, **kw): """Serialize ``obj`` to a JSON formatted ``str``. If ``skipkeys`` is false then ``dict`` keys that are not basic types (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) will be skipped instead of raising a ``TypeError``. If ``ensure_ascii`` is false, then the return value will be a ``unicode`` instance subject to normal Python ``str`` to ``unicode`` coercion rules instead of being escaped to an ASCII ``str``. If ``check_circular`` is false, then the circular reference check for container types will be skipped and a circular reference will result in an ``OverflowError`` (or worse). If ``allow_nan`` is false, then it will be a ``ValueError`` to serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). If ``indent`` is a string, then JSON array elements and object members will be pretty-printed with a newline followed by that string repeated for each level of nesting. ``None`` (the default) selects the most compact representation without any newlines. For backwards compatibility with versions of simplejson earlier than 2.1.0, an integer is also accepted and is converted to a string with that many spaces. If ``separators`` is an ``(item_separator, dict_separator)`` tuple then it will be used instead of the default ``(', ', ': ')`` separators. ``(',', ':')`` is the most compact JSON representation. ``encoding`` is the character encoding for str instances, default is UTF-8. ``default(obj)`` is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. If *use_decimal* is true (default: ``False``) then decimal.Decimal will be natively serialized to JSON with full precision. To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the ``.default()`` method to serialize additional types), specify it with the ``cls`` kwarg. """ # cached encoder if (not skipkeys and ensure_ascii and check_circular and allow_nan and cls is None and indent is None and separators is None and encoding == 'utf-8' and default is None and not use_decimal and not kw): return _default_encoder.encode(obj) if cls is None: cls = JSONEncoder return cls( skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, encoding=encoding, default=default, use_decimal=use_decimal, **kw).encode(obj) _default_decoder = JSONDecoder(encoding=None, object_hook=None, object_pairs_hook=None) def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, use_decimal=False, **kw): """Deserialize ``fp`` (a ``.read()``-supporting file-like object containing a JSON document) to a Python object. *encoding* determines the encoding used to interpret any :class:`str` objects decoded by this instance (``'utf-8'`` by default). It has no effect when decoding :class:`unicode` objects. Note that currently only encodings that are a superset of ASCII work, strings of other encodings should be passed in as :class:`unicode`. *object_hook*, if specified, will be called with the result of every JSON object decoded and its return value will be used in place of the given :class:`dict`. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting). *object_pairs_hook* is an optional function that will be called with the result of any object literal decode with an ordered list of pairs. The return value of *object_pairs_hook* will be used instead of the :class:`dict`. This feature can be used to implement custom decoders that rely on the order that the key and value pairs are decoded (for example, :func:`collections.OrderedDict` will remember the order of insertion). If *object_hook* is also defined, the *object_pairs_hook* takes priority. *parse_float*, if specified, will be called with the string of every JSON float to be decoded. By default, this is equivalent to ``float(num_str)``. This can be used to use another datatype or parser for JSON floats (e.g. :class:`decimal.Decimal`). *parse_int*, if specified, will be called with the string of every JSON int to be decoded. By default, this is equivalent to ``int(num_str)``. This can be used to use another datatype or parser for JSON integers (e.g. :class:`float`). *parse_constant*, if specified, will be called with one of the following strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``. This can be used to raise an exception if invalid JSON numbers are encountered. If *use_decimal* is true (default: ``False``) then it implies parse_float=decimal.Decimal for parity with ``dump``. To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg. """ return loads(fp.read(), encoding=encoding, cls=cls, object_hook=object_hook, parse_float=parse_float, parse_int=parse_int, parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, use_decimal=use_decimal, **kw) def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, use_decimal=False, **kw): """Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON document) to a Python object. *encoding* determines the encoding used to interpret any :class:`str` objects decoded by this instance (``'utf-8'`` by default). It has no effect when decoding :class:`unicode` objects. Note that currently only encodings that are a superset of ASCII work, strings of other encodings should be passed in as :class:`unicode`. *object_hook*, if specified, will be called with the result of every JSON object decoded and its return value will be used in place of the given :class:`dict`. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting). *object_pairs_hook* is an optional function that will be called with the result of any object literal decode with an ordered list of pairs. The return value of *object_pairs_hook* will be used instead of the :class:`dict`. This feature can be used to implement custom decoders that rely on the order that the key and value pairs are decoded (for example, :func:`collections.OrderedDict` will remember the order of insertion). If *object_hook* is also defined, the *object_pairs_hook* takes priority. *parse_float*, if specified, will be called with the string of every JSON float to be decoded. By default, this is equivalent to ``float(num_str)``. This can be used to use another datatype or parser for JSON floats (e.g. :class:`decimal.Decimal`). *parse_int*, if specified, will be called with the string of every JSON int to be decoded. By default, this is equivalent to ``int(num_str)``. This can be used to use another datatype or parser for JSON integers (e.g. :class:`float`). *parse_constant*, if specified, will be called with one of the following strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``. This can be used to raise an exception if invalid JSON numbers are encountered. If *use_decimal* is true (default: ``False``) then it implies parse_float=decimal.Decimal for parity with ``dump``. To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg. """ if (cls is None and encoding is None and object_hook is None and parse_int is None and parse_float is None and parse_constant is None and object_pairs_hook is None and not use_decimal and not kw): return _default_decoder.decode(s) if cls is None: cls = JSONDecoder if object_hook is not None: kw['object_hook'] = object_hook if object_pairs_hook is not None: kw['object_pairs_hook'] = object_pairs_hook if parse_float is not None: kw['parse_float'] = parse_float if parse_int is not None: kw['parse_int'] = parse_int if parse_constant is not None: kw['parse_constant'] = parse_constant if use_decimal: if parse_float is not None: raise TypeError("use_decimal=True implies parse_float=Decimal") kw['parse_float'] = Decimal return cls(encoding=encoding, **kw).decode(s) def _toggle_speedups(enabled): import decoder as dec import encoder as enc import scanner as scan c_make_encoder = _import_c_make_encoder() if enabled: dec.scanstring = dec.c_scanstring or dec.py_scanstring enc.c_make_encoder = c_make_encoder enc.encode_basestring_ascii = (enc.c_encode_basestring_ascii or enc.py_encode_basestring_ascii) scan.make_scanner = scan.c_make_scanner or scan.py_make_scanner else: dec.scanstring = dec.py_scanstring enc.c_make_encoder = None enc.encode_basestring_ascii = enc.py_encode_basestring_ascii scan.make_scanner = scan.py_make_scanner dec.make_scanner = scan.make_scanner global _default_decoder _default_decoder = JSONDecoder( encoding=None, object_hook=None, object_pairs_hook=None, ) global _default_encoder _default_encoder = JSONEncoder( skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, indent=None, separators=None, encoding='utf-8', default=None, )
Python
r"""Command-line tool to validate and pretty-print JSON Usage:: $ echo '{"json":"obj"}' | python -m simplejson.tool { "json": "obj" } $ echo '{ 1.2:3.4}' | python -m simplejson.tool Expecting property name: line 1 column 2 (char 2) """ import sys import simplejson as json def main(): if len(sys.argv) == 1: infile = sys.stdin outfile = sys.stdout elif len(sys.argv) == 2: infile = open(sys.argv[1], 'rb') outfile = sys.stdout elif len(sys.argv) == 3: infile = open(sys.argv[1], 'rb') outfile = open(sys.argv[2], 'wb') else: raise SystemExit(sys.argv[0] + " [infile [outfile]]") try: try: obj = json.load(infile, object_pairs_hook=json.OrderedDict, use_decimal=True) except ValueError, e: raise SystemExit(e) json.dump(obj, outfile, sort_keys=True, indent=' ', use_decimal=True) outfile.write('\n') finally: infile.close() outfile.close() if __name__ == '__main__': main()
Python
#!/usr/bin/env python # Copyright (c) 2007-2008 ActiveState Corp. # License: MIT (http://www.opensource.org/licenses/mit-license.php) r"""A fast and complete Python implementation of Markdown. [from http://daringfireball.net/projects/markdown/] > Markdown is a text-to-HTML filter; it translates an easy-to-read / > easy-to-write structured text format into HTML. Markdown's text > format is most similar to that of plain text email, and supports > features such as headers, *emphasis*, code blocks, blockquotes, and > links. > > Markdown's syntax is designed not as a generic markup language, but > specifically to serve as a front-end to (X)HTML. You can use span-level > HTML tags anywhere in a Markdown document, and you can use block level > HTML tags (like <div> and <table> as well). Module usage: >>> import markdown2 >>> markdown2.markdown("*boo!*") # or use `html = markdown_path(PATH)` u'<p><em>boo!</em></p>\n' >>> markdowner = Markdown() >>> markdowner.convert("*boo!*") u'<p><em>boo!</em></p>\n' >>> markdowner.convert("**boom!**") u'<p><strong>boom!</strong></p>\n' This implementation of Markdown implements the full "core" syntax plus a number of extras (e.g., code syntax coloring, footnotes) as described on <http://code.google.com/p/python-markdown2/wiki/Extras>. """ cmdln_desc = """A fast and complete Python implementation of Markdown, a text-to-HTML conversion tool for web writers. """ # Dev Notes: # - There is already a Python markdown processor # (http://www.freewisdom.org/projects/python-markdown/). # - Python's regex syntax doesn't have '\z', so I'm using '\Z'. I'm # not yet sure if there implications with this. Compare 'pydoc sre' # and 'perldoc perlre'. __version_info__ = (1, 0, 1, 16) # first three nums match Markdown.pl __version__ = '1.0.1.16' __author__ = "Trent Mick" import os import sys from pprint import pprint import re import logging try: from hashlib import md5 except ImportError: from md5 import md5 import optparse from random import random, randint import codecs from urllib import quote #---- Python version compat if sys.version_info[:2] < (2,4): from sets import Set as set def reversed(sequence): for i in sequence[::-1]: yield i def _unicode_decode(s, encoding, errors='xmlcharrefreplace'): return unicode(s, encoding, errors) else: def _unicode_decode(s, encoding, errors='strict'): return s.decode(encoding, errors) #---- globals DEBUG = False log = logging.getLogger("markdown") DEFAULT_TAB_WIDTH = 4 try: import uuid except ImportError: SECRET_SALT = str(randint(0, 1000000)) else: SECRET_SALT = str(uuid.uuid4()) def _hash_ascii(s): #return md5(s).hexdigest() # Markdown.pl effectively does this. return 'md5-' + md5(SECRET_SALT + s).hexdigest() def _hash_text(s): return 'md5-' + md5(SECRET_SALT + s.encode("utf-8")).hexdigest() # Table of hash values for escaped characters: g_escape_table = dict([(ch, _hash_ascii(ch)) for ch in '\\`*_{}[]()>#+-.!']) #---- exceptions class MarkdownError(Exception): pass #---- public api def markdown_path(path, encoding="utf-8", html4tags=False, tab_width=DEFAULT_TAB_WIDTH, safe_mode=None, extras=None, link_patterns=None, use_file_vars=False): fp = codecs.open(path, 'r', encoding) try: text = fp.read() finally: fp.close() return Markdown(html4tags=html4tags, tab_width=tab_width, safe_mode=safe_mode, extras=extras, link_patterns=link_patterns, use_file_vars=use_file_vars).convert(text) def markdown(text, html4tags=False, tab_width=DEFAULT_TAB_WIDTH, safe_mode=None, extras=None, link_patterns=None, use_file_vars=False): return Markdown(html4tags=html4tags, tab_width=tab_width, safe_mode=safe_mode, extras=extras, link_patterns=link_patterns, use_file_vars=use_file_vars).convert(text) class Markdown(object): # The dict of "extras" to enable in processing -- a mapping of # extra name to argument for the extra. Most extras do not have an # argument, in which case the value is None. # # This can be set via (a) subclassing and (b) the constructor # "extras" argument. extras = None urls = None titles = None html_blocks = None html_spans = None html_removed_text = "[HTML_REMOVED]" # for compat with markdown.py # Used to track when we're inside an ordered or unordered list # (see _ProcessListItems() for details): list_level = 0 _ws_only_line_re = re.compile(r"^[ \t]+$", re.M) def __init__(self, html4tags=False, tab_width=4, safe_mode=None, extras=None, link_patterns=None, use_file_vars=False): if html4tags: self.empty_element_suffix = ">" else: self.empty_element_suffix = " />" self.tab_width = tab_width # For compatibility with earlier markdown2.py and with # markdown.py's safe_mode being a boolean, # safe_mode == True -> "replace" if safe_mode is True: self.safe_mode = "replace" else: self.safe_mode = safe_mode if self.extras is None: self.extras = {} elif not isinstance(self.extras, dict): self.extras = dict([(e, None) for e in self.extras]) if extras: if not isinstance(extras, dict): extras = dict([(e, None) for e in extras]) self.extras.update(extras) assert isinstance(self.extras, dict) self._instance_extras = self.extras.copy() self.link_patterns = link_patterns self.use_file_vars = use_file_vars self._outdent_re = re.compile(r'^(\t|[ ]{1,%d})' % tab_width, re.M) def reset(self): self.urls = {} self.titles = {} self.html_blocks = {} self.html_spans = {} self.list_level = 0 self.extras = self._instance_extras.copy() if "footnotes" in self.extras: self.footnotes = {} self.footnote_ids = [] def convert(self, text): """Convert the given text.""" # Main function. The order in which other subs are called here is # essential. Link and image substitutions need to happen before # _EscapeSpecialChars(), so that any *'s or _'s in the <a> # and <img> tags get encoded. # Clear the global hashes. If we don't clear these, you get conflicts # from other articles when generating a page which contains more than # one article (e.g. an index page that shows the N most recent # articles): self.reset() if not isinstance(text, unicode): #TODO: perhaps shouldn't presume UTF-8 for string input? text = unicode(text, 'utf-8') if self.use_file_vars: # Look for emacs-style file variable hints. emacs_vars = self._get_emacs_vars(text) if "markdown-extras" in emacs_vars: splitter = re.compile("[ ,]+") for e in splitter.split(emacs_vars["markdown-extras"]): if '=' in e: ename, earg = e.split('=', 1) try: earg = int(earg) except ValueError: pass else: ename, earg = e, None self.extras[ename] = earg # Standardize line endings: text = re.sub("\r\n|\r", "\n", text) # Make sure $text ends with a couple of newlines: text += "\n\n" # Convert all tabs to spaces. text = self._detab(text) # Strip any lines consisting only of spaces and tabs. # This makes subsequent regexen easier to write, because we can # match consecutive blank lines with /\n+/ instead of something # contorted like /[ \t]*\n+/ . text = self._ws_only_line_re.sub("", text) if self.safe_mode: text = self._hash_html_spans(text) # Turn block-level HTML blocks into hash entries text = self._hash_html_blocks(text, raw=True) # Strip link definitions, store in hashes. if "footnotes" in self.extras: # Must do footnotes first because an unlucky footnote defn # looks like a link defn: # [^4]: this "looks like a link defn" text = self._strip_footnote_definitions(text) text = self._strip_link_definitions(text) text = self._run_block_gamut(text) if "footnotes" in self.extras: text = self._add_footnotes(text) text = self._unescape_special_chars(text) if self.safe_mode: text = self._unhash_html_spans(text) text += "\n" return text _emacs_oneliner_vars_pat = re.compile(r"-\*-\s*([^\r\n]*?)\s*-\*-", re.UNICODE) # This regular expression is intended to match blocks like this: # PREFIX Local Variables: SUFFIX # PREFIX mode: Tcl SUFFIX # PREFIX End: SUFFIX # Some notes: # - "[ \t]" is used instead of "\s" to specifically exclude newlines # - "(\r\n|\n|\r)" is used instead of "$" because the sre engine does # not like anything other than Unix-style line terminators. _emacs_local_vars_pat = re.compile(r"""^ (?P<prefix>(?:[^\r\n|\n|\r])*?) [\ \t]*Local\ Variables:[\ \t]* (?P<suffix>.*?)(?:\r\n|\n|\r) (?P<content>.*?\1End:) """, re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE) def _get_emacs_vars(self, text): """Return a dictionary of emacs-style local variables. Parsing is done loosely according to this spec (and according to some in-practice deviations from this): http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html#Specifying-File-Variables """ emacs_vars = {} SIZE = pow(2, 13) # 8kB # Search near the start for a '-*-'-style one-liner of variables. head = text[:SIZE] if "-*-" in head: match = self._emacs_oneliner_vars_pat.search(head) if match: emacs_vars_str = match.group(1) assert '\n' not in emacs_vars_str emacs_var_strs = [s.strip() for s in emacs_vars_str.split(';') if s.strip()] if len(emacs_var_strs) == 1 and ':' not in emacs_var_strs[0]: # While not in the spec, this form is allowed by emacs: # -*- Tcl -*- # where the implied "variable" is "mode". This form # is only allowed if there are no other variables. emacs_vars["mode"] = emacs_var_strs[0].strip() else: for emacs_var_str in emacs_var_strs: try: variable, value = emacs_var_str.strip().split(':', 1) except ValueError: log.debug("emacs variables error: malformed -*- " "line: %r", emacs_var_str) continue # Lowercase the variable name because Emacs allows "Mode" # or "mode" or "MoDe", etc. emacs_vars[variable.lower()] = value.strip() tail = text[-SIZE:] if "Local Variables" in tail: match = self._emacs_local_vars_pat.search(tail) if match: prefix = match.group("prefix") suffix = match.group("suffix") lines = match.group("content").splitlines(0) #print "prefix=%r, suffix=%r, content=%r, lines: %s"\ # % (prefix, suffix, match.group("content"), lines) # Validate the Local Variables block: proper prefix and suffix # usage. for i, line in enumerate(lines): if not line.startswith(prefix): log.debug("emacs variables error: line '%s' " "does not use proper prefix '%s'" % (line, prefix)) return {} # Don't validate suffix on last line. Emacs doesn't care, # neither should we. if i != len(lines)-1 and not line.endswith(suffix): log.debug("emacs variables error: line '%s' " "does not use proper suffix '%s'" % (line, suffix)) return {} # Parse out one emacs var per line. continued_for = None for line in lines[:-1]: # no var on the last line ("PREFIX End:") if prefix: line = line[len(prefix):] # strip prefix if suffix: line = line[:-len(suffix)] # strip suffix line = line.strip() if continued_for: variable = continued_for if line.endswith('\\'): line = line[:-1].rstrip() else: continued_for = None emacs_vars[variable] += ' ' + line else: try: variable, value = line.split(':', 1) except ValueError: log.debug("local variables error: missing colon " "in local variables entry: '%s'" % line) continue # Do NOT lowercase the variable name, because Emacs only # allows "mode" (and not "Mode", "MoDe", etc.) in this block. value = value.strip() if value.endswith('\\'): value = value[:-1].rstrip() continued_for = variable else: continued_for = None emacs_vars[variable] = value # Unquote values. for var, val in emacs_vars.items(): if len(val) > 1 and (val.startswith('"') and val.endswith('"') or val.startswith('"') and val.endswith('"')): emacs_vars[var] = val[1:-1] return emacs_vars # Cribbed from a post by Bart Lateur: # <http://www.nntp.perl.org/group/perl.macperl.anyperl/154> _detab_re = re.compile(r'(.*?)\t', re.M) def _detab_sub(self, match): g1 = match.group(1) return g1 + (' ' * (self.tab_width - len(g1) % self.tab_width)) def _detab(self, text): r"""Remove (leading?) tabs from a file. >>> m = Markdown() >>> m._detab("\tfoo") ' foo' >>> m._detab(" \tfoo") ' foo' >>> m._detab("\t foo") ' foo' >>> m._detab(" foo") ' foo' >>> m._detab(" foo\n\tbar\tblam") ' foo\n bar blam' """ if '\t' not in text: return text return self._detab_re.subn(self._detab_sub, text)[0] _block_tags_a = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del' _strict_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching </\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_a, re.X | re.M) _block_tags_b = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math' _liberal_tag_block_re = re.compile(r""" ( # save in \1 ^ # start of line (with re.M) <(%s) # start tag = \2 \b # word break (.*\n)*? # any number of lines, minimally matching .*</\2> # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) """ % _block_tags_b, re.X | re.M) def _hash_html_block_sub(self, match, raw=False): html = match.group(1) if raw and self.safe_mode: html = self._sanitize_html(html) key = _hash_text(html) self.html_blocks[key] = html return "\n\n" + key + "\n\n" def _hash_html_blocks(self, text, raw=False): """Hashify HTML blocks We only want to do this for block-level HTML tags, such as headers, lists, and tables. That's because we still want to wrap <p>s around "paragraphs" that are wrapped in non-block-level tags, such as anchors, phrase emphasis, and spans. The list of tags we're looking for is hard-coded. @param raw {boolean} indicates if these are raw HTML blocks in the original source. It makes a difference in "safe" mode. """ if '<' not in text: return text # Pass `raw` value into our calls to self._hash_html_block_sub. hash_html_block_sub = _curry(self._hash_html_block_sub, raw=raw) # First, look for nested blocks, e.g.: # <div> # <div> # tags for inner block must be indented. # </div> # </div> # # The outermost tags must start at the left margin for this to match, and # the inner nested divs must be indented. # We need to do this before the next, more liberal match, because the next # match will start at the first `<div>` and stop at the first `</div>`. text = self._strict_tag_block_re.sub(hash_html_block_sub, text) # Now match more liberally, simply from `\n<tag>` to `</tag>\n` text = self._liberal_tag_block_re.sub(hash_html_block_sub, text) # Special case just for <hr />. It was easier to make a special # case than to make the other regex more complicated. if "<hr" in text: _hr_tag_re = _hr_tag_re_from_tab_width(self.tab_width) text = _hr_tag_re.sub(hash_html_block_sub, text) # Special case for standalone HTML comments: if "<!--" in text: start = 0 while True: # Delimiters for next comment block. try: start_idx = text.index("<!--", start) except ValueError, ex: break try: end_idx = text.index("-->", start_idx) + 3 except ValueError, ex: break # Start position for next comment block search. start = end_idx # Validate whitespace before comment. if start_idx: # - Up to `tab_width - 1` spaces before start_idx. for i in range(self.tab_width - 1): if text[start_idx - 1] != ' ': break start_idx -= 1 if start_idx == 0: break # - Must be preceded by 2 newlines or hit the start of # the document. if start_idx == 0: pass elif start_idx == 1 and text[0] == '\n': start_idx = 0 # to match minute detail of Markdown.pl regex elif text[start_idx-2:start_idx] == '\n\n': pass else: break # Validate whitespace after comment. # - Any number of spaces and tabs. while end_idx < len(text): if text[end_idx] not in ' \t': break end_idx += 1 # - Must be following by 2 newlines or hit end of text. if text[end_idx:end_idx+2] not in ('', '\n', '\n\n'): continue # Escape and hash (must match `_hash_html_block_sub`). html = text[start_idx:end_idx] if raw and self.safe_mode: html = self._sanitize_html(html) key = _hash_text(html) self.html_blocks[key] = html text = text[:start_idx] + "\n\n" + key + "\n\n" + text[end_idx:] if "xml" in self.extras: # Treat XML processing instructions and namespaced one-liner # tags as if they were block HTML tags. E.g., if standalone # (i.e. are their own paragraph), the following do not get # wrapped in a <p> tag: # <?foo bar?> # # <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="chapter_1.md"/> _xml_oneliner_re = _xml_oneliner_re_from_tab_width(self.tab_width) text = _xml_oneliner_re.sub(hash_html_block_sub, text) return text def _strip_link_definitions(self, text): # Strips link definitions from text, stores the URLs and titles in # hash references. less_than_tab = self.tab_width - 1 # Link defs are in the form: # [id]: url "optional title" _link_def_re = re.compile(r""" ^[ ]{0,%d}\[(.+)\]: # id = \1 [ \t]* \n? # maybe *one* newline [ \t]* <?(.+?)>? # url = \2 [ \t]* (?: \n? # maybe one newline [ \t]* (?<=\s) # lookbehind for whitespace ['"(] ([^\n]*) # title = \3 ['")] [ \t]* )? # title is optional (?:\n+|\Z) """ % less_than_tab, re.X | re.M | re.U) return _link_def_re.sub(self._extract_link_def_sub, text) def _extract_link_def_sub(self, match): id, url, title = match.groups() key = id.lower() # Link IDs are case-insensitive self.urls[key] = self._encode_amps_and_angles(url) if title: self.titles[key] = title.replace('"', '&quot;') return "" def _extract_footnote_def_sub(self, match): id, text = match.groups() text = _dedent(text, skip_first_line=not text.startswith('\n')).strip() normed_id = re.sub(r'\W', '-', id) # Ensure footnote text ends with a couple newlines (for some # block gamut matches). self.footnotes[normed_id] = text + "\n\n" return "" def _strip_footnote_definitions(self, text): """A footnote definition looks like this: [^note-id]: Text of the note. May include one or more indented paragraphs. Where, - The 'note-id' can be pretty much anything, though typically it is the number of the footnote. - The first paragraph may start on the next line, like so: [^note-id]: Text of the note. """ less_than_tab = self.tab_width - 1 footnote_def_re = re.compile(r''' ^[ ]{0,%d}\[\^(.+)\]: # id = \1 [ \t]* ( # footnote text = \2 # First line need not start with the spaces. (?:\s*.*\n+) (?: (?:[ ]{%d} | \t) # Subsequent lines must be indented. .*\n+ )* ) # Lookahead for non-space at line-start, or end of doc. (?:(?=^[ ]{0,%d}\S)|\Z) ''' % (less_than_tab, self.tab_width, self.tab_width), re.X | re.M) return footnote_def_re.sub(self._extract_footnote_def_sub, text) _hr_res = [ re.compile(r"^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$", re.M), re.compile(r"^[ ]{0,2}([ ]?\-[ ]?){3,}[ \t]*$", re.M), re.compile(r"^[ ]{0,2}([ ]?\_[ ]?){3,}[ \t]*$", re.M), ] def _run_block_gamut(self, text): # These are all the transformations that form block-level # tags like paragraphs, headers, and list items. text = self._do_headers(text) # Do Horizontal Rules: hr = "\n<hr"+self.empty_element_suffix+"\n" for hr_re in self._hr_res: text = hr_re.sub(hr, text) text = self._do_lists(text) if "pyshell" in self.extras: text = self._prepare_pyshell_blocks(text) text = self._do_code_blocks(text) text = self._do_block_quotes(text) # We already ran _HashHTMLBlocks() before, in Markdown(), but that # was to escape raw HTML in the original Markdown source. This time, # we're escaping the markup we've just created, so that we don't wrap # <p> tags around block-level tags. text = self._hash_html_blocks(text) text = self._form_paragraphs(text) return text def _pyshell_block_sub(self, match): lines = match.group(0).splitlines(0) _dedentlines(lines) indent = ' ' * self.tab_width s = ('\n' # separate from possible cuddled paragraph + indent + ('\n'+indent).join(lines) + '\n\n') return s def _prepare_pyshell_blocks(self, text): """Ensure that Python interactive shell sessions are put in code blocks -- even if not properly indented. """ if ">>>" not in text: return text less_than_tab = self.tab_width - 1 _pyshell_block_re = re.compile(r""" ^([ ]{0,%d})>>>[ ].*\n # first line ^(\1.*\S+.*\n)* # any number of subsequent lines ^\n # ends with a blank line """ % less_than_tab, re.M | re.X) return _pyshell_block_re.sub(self._pyshell_block_sub, text) def _run_span_gamut(self, text): # These are all the transformations that occur *within* block-level # tags like paragraphs, headers, and list items. text = self._do_code_spans(text) text = self._escape_special_chars(text) # Process anchor and image tags. text = self._do_links(text) # Make links out of things like `<http://example.com/>` # Must come after _do_links(), because you can use < and > # delimiters in inline links like [this](<url>). text = self._do_auto_links(text) if "link-patterns" in self.extras: text = self._do_link_patterns(text) text = self._encode_amps_and_angles(text) text = self._do_italics_and_bold(text) # Do hard breaks: text = re.sub(r" {2,}\n", " <br%s\n" % self.empty_element_suffix, text) return text # "Sorta" because auto-links are identified as "tag" tokens. _sorta_html_tokenize_re = re.compile(r""" ( # tag </? (?:\w+) # tag name (?:\s+(?:[\w-]+:)?[\w-]+=(?:".*?"|'.*?'))* # attributes \s*/?> | # auto-link (e.g., <http://www.activestate.com/>) <\w+[^>]*> | <!--.*?--> # comment | <\?.*?\?> # processing instruction ) """, re.X) def _escape_special_chars(self, text): # Python markdown note: the HTML tokenization here differs from # that in Markdown.pl, hence the behaviour for subtle cases can # differ (I believe the tokenizer here does a better job because # it isn't susceptible to unmatched '<' and '>' in HTML tags). # Note, however, that '>' is not allowed in an auto-link URL # here. escaped = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup: # Within tags/HTML-comments/auto-links, encode * and _ # so they don't conflict with their use in Markdown for # italics and strong. We're replacing each such # character with its corresponding MD5 checksum value; # this is likely overkill, but it should prevent us from # colliding with the escape values by accident. escaped.append(token.replace('*', g_escape_table['*']) .replace('_', g_escape_table['_'])) else: escaped.append(self._encode_backslash_escapes(token)) is_html_markup = not is_html_markup return ''.join(escaped) def _hash_html_spans(self, text): # Used for safe_mode. def _is_auto_link(s): if ':' in s and self._auto_link_re.match(s): return True elif '@' in s and self._auto_email_link_re.match(s): return True return False tokens = [] is_html_markup = False for token in self._sorta_html_tokenize_re.split(text): if is_html_markup and not _is_auto_link(token): sanitized = self._sanitize_html(token) key = _hash_text(sanitized) self.html_spans[key] = sanitized tokens.append(key) else: tokens.append(token) is_html_markup = not is_html_markup return ''.join(tokens) def _unhash_html_spans(self, text): for key, sanitized in self.html_spans.items(): text = text.replace(key, sanitized) return text def _sanitize_html(self, s): if self.safe_mode == "replace": return self.html_removed_text elif self.safe_mode == "escape": replacements = [ ('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;'), ] for before, after in replacements: s = s.replace(before, after) return s else: raise MarkdownError("invalid value for 'safe_mode': %r (must be " "'escape' or 'replace')" % self.safe_mode) _tail_of_inline_link_re = re.compile(r''' # Match tail of: [text](/url/) or [text](/url/ "title") \( # literal paren [ \t]* (?P<url> # \1 <.*?> | .*? ) [ \t]* ( # \2 (['"]) # quote char = \3 (?P<title>.*?) \3 # matching quote )? # title is optional \) ''', re.X | re.S) _tail_of_reference_link_re = re.compile(r''' # Match tail of: [text][id] [ ]? # one optional space (?:\n[ ]*)? # one optional newline followed by spaces \[ (?P<id>.*?) \] ''', re.X | re.S) def _do_links(self, text): """Turn Markdown link shortcuts into XHTML <a> and <img> tags. This is a combination of Markdown.pl's _DoAnchors() and _DoImages(). They are done together because that simplified the approach. It was necessary to use a different approach than Markdown.pl because of the lack of atomic matching support in Python's regex engine used in $g_nested_brackets. """ MAX_LINK_TEXT_SENTINEL = 3000 # markdown2 issue 24 # `anchor_allowed_pos` is used to support img links inside # anchors, but not anchors inside anchors. An anchor's start # pos must be `>= anchor_allowed_pos`. anchor_allowed_pos = 0 curr_pos = 0 while True: # Handle the next link. # The next '[' is the start of: # - an inline anchor: [text](url "title") # - a reference anchor: [text][id] # - an inline img: ![text](url "title") # - a reference img: ![text][id] # - a footnote ref: [^id] # (Only if 'footnotes' extra enabled) # - a footnote defn: [^id]: ... # (Only if 'footnotes' extra enabled) These have already # been stripped in _strip_footnote_definitions() so no # need to watch for them. # - a link definition: [id]: url "title" # These have already been stripped in # _strip_link_definitions() so no need to watch for them. # - not markup: [...anything else... try: start_idx = text.index('[', curr_pos) except ValueError: break text_length = len(text) # Find the matching closing ']'. # Markdown.pl allows *matching* brackets in link text so we # will here too. Markdown.pl *doesn't* currently allow # matching brackets in img alt text -- we'll differ in that # regard. bracket_depth = 0 for p in range(start_idx+1, min(start_idx+MAX_LINK_TEXT_SENTINEL, text_length)): ch = text[p] if ch == ']': bracket_depth -= 1 if bracket_depth < 0: break elif ch == '[': bracket_depth += 1 else: # Closing bracket not found within sentinel length. # This isn't markup. curr_pos = start_idx + 1 continue link_text = text[start_idx+1:p] # Possibly a footnote ref? if "footnotes" in self.extras and link_text.startswith("^"): normed_id = re.sub(r'\W', '-', link_text[1:]) if normed_id in self.footnotes: self.footnote_ids.append(normed_id) result = '<sup class="footnote-ref" id="fnref-%s">' \ '<a href="#fn-%s">%s</a></sup>' \ % (normed_id, normed_id, len(self.footnote_ids)) text = text[:start_idx] + result + text[p+1:] else: # This id isn't defined, leave the markup alone. curr_pos = p+1 continue # Now determine what this is by the remainder. p += 1 if p == text_length: return text # Inline anchor or img? if text[p] == '(': # attempt at perf improvement match = self._tail_of_inline_link_re.match(text, p) if match: # Handle an inline anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 url, title = match.group("url"), match.group("title") if url and url[0] == '<': url = url[1:-1] # '<url>' -> 'url' # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', g_escape_table['*']) \ .replace('_', g_escape_table['_']) if title: title_str = ' title="%s"' \ % title.replace('*', g_escape_table['*']) \ .replace('_', g_escape_table['_']) \ .replace('"', '&quot;') else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), link_text.replace('"', '&quot;'), title_str, self.empty_element_suffix) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 continue # Reference anchor or img? else: match = self._tail_of_reference_link_re.match(text, p) if match: # Handle a reference-style anchor or img. is_img = start_idx > 0 and text[start_idx-1] == "!" if is_img: start_idx -= 1 link_id = match.group("id").lower() if not link_id: link_id = link_text.lower() # for links like [this][] if link_id in self.urls: url = self.urls[link_id] # We've got to encode these to avoid conflicting # with italics/bold. url = url.replace('*', g_escape_table['*']) \ .replace('_', g_escape_table['_']) title = self.titles.get(link_id) if title: title = title.replace('*', g_escape_table['*']) \ .replace('_', g_escape_table['_']) title_str = ' title="%s"' % title else: title_str = '' if is_img: result = '<img src="%s" alt="%s"%s%s' \ % (url.replace('"', '&quot;'), link_text.replace('"', '&quot;'), title_str, self.empty_element_suffix) curr_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] elif start_idx >= anchor_allowed_pos: result = '<a href="%s"%s>%s</a>' \ % (url, title_str, link_text) result_head = '<a href="%s"%s>' % (url, title_str) result = '%s%s</a>' % (result_head, link_text) # <img> allowed from curr_pos on, <a> from # anchor_allowed_pos on. curr_pos = start_idx + len(result_head) anchor_allowed_pos = start_idx + len(result) text = text[:start_idx] + result + text[match.end():] else: # Anchor not allowed here. curr_pos = start_idx + 1 else: # This id isn't defined, leave the markup alone. curr_pos = match.end() continue # Otherwise, it isn't markup. curr_pos = start_idx + 1 return text _setext_h_re = re.compile(r'^(.+)[ \t]*\n(=+|-+)[ \t]*\n+', re.M) def _setext_h_sub(self, match): n = {"=": 1, "-": 2}[match.group(2)[0]] demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) return "<h%d>%s</h%d>\n\n" \ % (n, self._run_span_gamut(match.group(1)), n) _atx_h_re = re.compile(r''' ^(\#{1,6}) # \1 = string of #'s [ \t]* (.+?) # \2 = Header text [ \t]* (?<!\\) # ensure not an escaped trailing '#' \#* # optional closing #'s (not counted) \n+ ''', re.X | re.M) def _atx_h_sub(self, match): n = len(match.group(1)) demote_headers = self.extras.get("demote-headers") if demote_headers: n = min(n + demote_headers, 6) return "<h%d>%s</h%d>\n\n" \ % (n, self._run_span_gamut(match.group(2)), n) def _do_headers(self, text): # Setext-style headers: # Header 1 # ======== # # Header 2 # -------- text = self._setext_h_re.sub(self._setext_h_sub, text) # atx-style headers: # # Header 1 # ## Header 2 # ## Header 2 with closing hashes ## # ... # ###### Header 6 text = self._atx_h_re.sub(self._atx_h_sub, text) return text _marker_ul_chars = '*+-' _marker_any = r'(?:[%s]|\d+\.)' % _marker_ul_chars _marker_ul = '(?:[%s])' % _marker_ul_chars _marker_ol = r'(?:\d+\.)' def _list_sub(self, match): lst = match.group(1) lst_type = match.group(3) in self._marker_ul_chars and "ul" or "ol" result = self._process_list_items(lst) if self.list_level: return "<%s>\n%s</%s>\n" % (lst_type, result, lst_type) else: return "<%s>\n%s</%s>\n\n" % (lst_type, result, lst_type) def _do_lists(self, text): # Form HTML ordered (numbered) and unordered (bulleted) lists. for marker_pat in (self._marker_ul, self._marker_ol): # Re-usable pattern to match any entire ul or ol list: less_than_tab = self.tab_width - 1 whole_list = r''' ( # \1 = whole list ( # \2 [ ]{0,%d} (%s) # \3 = first list item marker [ \t]+ ) (?:.+?) ( # \4 \Z | \n{2,} (?=\S) (?! # Negative lookahead for another list item marker [ \t]* %s[ \t]+ ) ) ) ''' % (less_than_tab, marker_pat, marker_pat) # We use a different prefix before nested lists than top-level lists. # See extended comment in _process_list_items(). # # Note: There's a bit of duplication here. My original implementation # created a scalar regex pattern as the conditional result of the test on # $g_list_level, and then only ran the $text =~ s{...}{...}egmx # substitution once, using the scalar as the pattern. This worked, # everywhere except when running under MT on my hosting account at Pair # Networks. There, this caused all rebuilds to be killed by the reaper (or # perhaps they crashed, but that seems incredibly unlikely given that the # same script on the same server ran fine *except* under MT. I've spent # more time trying to figure out why this is happening than I'd like to # admit. My only guess, backed up by the fact that this workaround works, # is that Perl optimizes the substition when it can figure out that the # pattern will never change, and when this optimization isn't on, we run # afoul of the reaper. Thus, the slightly redundant code to that uses two # static s/// patterns rather than one conditional pattern. if self.list_level: sub_list_re = re.compile("^"+whole_list, re.X | re.M | re.S) text = sub_list_re.sub(self._list_sub, text) else: list_re = re.compile(r"(?:(?<=\n\n)|\A\n?)"+whole_list, re.X | re.M | re.S) text = list_re.sub(self._list_sub, text) return text _list_item_re = re.compile(r''' (\n)? # leading line = \1 (^[ \t]*) # leading whitespace = \2 (%s) [ \t]+ # list marker = \3 ((?:.+?) # list item text = \4 (\n{1,2})) # eols = \5 (?= \n* (\Z | \2 (%s) [ \t]+)) ''' % (_marker_any, _marker_any), re.M | re.X | re.S) _last_li_endswith_two_eols = False def _list_item_sub(self, match): item = match.group(4) leading_line = match.group(1) leading_space = match.group(2) if leading_line or "\n\n" in item or self._last_li_endswith_two_eols: item = self._run_block_gamut(self._outdent(item)) else: # Recursion for sub-lists: item = self._do_lists(self._outdent(item)) if item.endswith('\n'): item = item[:-1] item = self._run_span_gamut(item) self._last_li_endswith_two_eols = (len(match.group(5)) == 2) return "<li>%s</li>\n" % item def _process_list_items(self, list_str): # Process the contents of a single ordered or unordered list, # splitting it into individual list items. # The $g_list_level global keeps track of when we're inside a list. # Each time we enter a list, we increment it; when we leave a list, # we decrement. If it's zero, we're not in a list anymore. # # We do this because when we're not inside a list, we want to treat # something like this: # # I recommend upgrading to version # 8. Oops, now this line is treated # as a sub-list. # # As a single paragraph, despite the fact that the second line starts # with a digit-period-space sequence. # # Whereas when we're inside a list (or sub-list), that line will be # treated as the start of a sub-list. What a kludge, huh? This is # an aspect of Markdown's syntax that's hard to parse perfectly # without resorting to mind-reading. Perhaps the solution is to # change the syntax rules such that sub-lists must start with a # starting cardinal number; e.g. "1." or "a.". self.list_level += 1 self._last_li_endswith_two_eols = False list_str = list_str.rstrip('\n') + '\n' list_str = self._list_item_re.sub(self._list_item_sub, list_str) self.list_level -= 1 return list_str def _get_pygments_lexer(self, lexer_name): try: from pygments import lexers, util except ImportError: return None try: return lexers.get_lexer_by_name(lexer_name) except util.ClassNotFound: return None def _color_with_pygments(self, codeblock, lexer, **formatter_opts): import pygments import pygments.formatters class HtmlCodeFormatter(pygments.formatters.HtmlFormatter): def _wrap_code(self, inner): """A function for use in a Pygments Formatter which wraps in <code> tags. """ yield 0, "<code>" for tup in inner: yield tup yield 0, "</code>" def wrap(self, source, outfile): """Return the source with a code, pre, and div.""" return self._wrap_div(self._wrap_pre(self._wrap_code(source))) formatter = HtmlCodeFormatter(cssclass="codehilite", **formatter_opts) return pygments.highlight(codeblock, lexer, formatter) def _code_block_sub(self, match): codeblock = match.group(1) codeblock = self._outdent(codeblock) codeblock = self._detab(codeblock) codeblock = codeblock.lstrip('\n') # trim leading newlines codeblock = codeblock.rstrip() # trim trailing whitespace if "code-color" in self.extras and codeblock.startswith(":::"): lexer_name, rest = codeblock.split('\n', 1) lexer_name = lexer_name[3:].strip() lexer = self._get_pygments_lexer(lexer_name) codeblock = rest.lstrip("\n") # Remove lexer declaration line. if lexer: formatter_opts = self.extras['code-color'] or {} colored = self._color_with_pygments(codeblock, lexer, **formatter_opts) return "\n\n%s\n\n" % colored codeblock = self._encode_code(codeblock) return "\n\n<pre><code>%s\n</code></pre>\n\n" % codeblock def _do_code_blocks(self, text): """Process Markdown `<pre><code>` blocks.""" code_block_re = re.compile(r''' (?:\n\n|\A) ( # $1 = the code block -- one or more lines, starting with a space/tab (?: (?:[ ]{%d} | \t) # Lines must start with a tab or a tab-width of spaces .*\n+ )+ ) ((?=^[ ]{0,%d}\S)|\Z) # Lookahead for non-space at line-start, or end of doc ''' % (self.tab_width, self.tab_width), re.M | re.X) return code_block_re.sub(self._code_block_sub, text) # Rules for a code span: # - backslash escapes are not interpreted in a code span # - to include one or or a run of more backticks the delimiters must # be a longer run of backticks # - cannot start or end a code span with a backtick; pad with a # space and that space will be removed in the emitted HTML # See `test/tm-cases/escapes.text` for a number of edge-case # examples. _code_span_re = re.compile(r''' (?<!\\) (`+) # \1 = Opening run of ` (?!`) # See Note A test/tm-cases/escapes.text (.+?) # \2 = The code block (?<!`) \1 # Matching closer (?!`) ''', re.X | re.S) def _code_span_sub(self, match): c = match.group(2).strip(" \t") c = self._encode_code(c) return "<code>%s</code>" % c def _do_code_spans(self, text): # * Backtick quotes are used for <code></code> spans. # # * You can use multiple backticks as the delimiters if you want to # include literal backticks in the code span. So, this input: # # Just type ``foo `bar` baz`` at the prompt. # # Will translate to: # # <p>Just type <code>foo `bar` baz</code> at the prompt.</p> # # There's no arbitrary limit to the number of backticks you # can use as delimters. If you need three consecutive backticks # in your code, use four for delimiters, etc. # # * You can use spaces to get literal backticks at the edges: # # ... type `` `bar` `` ... # # Turns to: # # ... type <code>`bar`</code> ... return self._code_span_re.sub(self._code_span_sub, text) def _encode_code(self, text): """Encode/escape certain characters inside Markdown code runs. The point is that in code, these characters are literals, and lose their special Markdown meanings. """ replacements = [ # Encode all ampersands; HTML entities are not # entities within a Markdown code span. ('&', '&amp;'), # Do the angle bracket song and dance: ('<', '&lt;'), ('>', '&gt;'), # Now, escape characters that are magic in Markdown: ('*', g_escape_table['*']), ('_', g_escape_table['_']), ('{', g_escape_table['{']), ('}', g_escape_table['}']), ('[', g_escape_table['[']), (']', g_escape_table[']']), ('\\', g_escape_table['\\']), ] for before, after in replacements: text = text.replace(before, after) return text _strong_re = re.compile(r"(?<!\w)(\*\*|__)(?=\S)(.+?[*_]*)(?<=\S)\1(?!\w)", re.S) _em_re = re.compile(r"(?<!\w)(\*|_)(?=\S)(.+?)(?<=\S)\1(?!\w)", re.S) _code_friendly_strong_re = re.compile(r"\*\*(?=\S)(.+?[*_]*)(?<=\S)\*\*", re.S) _code_friendly_em_re = re.compile(r"\*(?=\S)(.+?)(?<=\S)\*", re.S) def _do_italics_and_bold(self, text): # <strong> must go first: if "code-friendly" in self.extras: text = self._code_friendly_strong_re.sub(r"<strong>\1</strong>", text) text = self._code_friendly_em_re.sub(r"<em>\1</em>", text) else: text = self._strong_re.sub(r"<strong>\2</strong>", text) text = self._em_re.sub(r"<em>\2</em>", text) return text _block_quote_re = re.compile(r''' ( # Wrap whole match in \1 ( ^[ \t]*>[ \t]? # '>' at the start of a line .+\n # rest of the first line (.+\n)* # subsequent consecutive lines \n* # blanks )+ ) ''', re.M | re.X) _bq_one_level_re = re.compile('^[ \t]*>[ \t]?', re.M); _html_pre_block_re = re.compile(r'(\s*<pre>.+?</pre>)', re.S) def _dedent_two_spaces_sub(self, match): return re.sub(r'(?m)^ ', '', match.group(1)) def _block_quote_sub(self, match): bq = match.group(1) bq = self._bq_one_level_re.sub('', bq) # trim one level of quoting bq = self._ws_only_line_re.sub('', bq) # trim whitespace-only lines bq = self._run_block_gamut(bq) # recurse bq = re.sub('(?m)^', ' ', bq) # These leading spaces screw with <pre> content, so we need to fix that: bq = self._html_pre_block_re.sub(self._dedent_two_spaces_sub, bq) return "<blockquote>\n%s\n</blockquote>\n\n" % bq def _do_block_quotes(self, text): if '>' not in text: return text return self._block_quote_re.sub(self._block_quote_sub, text) def _form_paragraphs(self, text): # Strip leading and trailing lines: text = text.strip('\n') # Wrap <p> tags. grafs = re.split(r"\n{2,}", text) for i, graf in enumerate(grafs): if graf in self.html_blocks: # Unhashify HTML blocks grafs[i] = self.html_blocks[graf] else: # Wrap <p> tags. graf = self._run_span_gamut(graf) grafs[i] = "<p>" + graf.lstrip(" \t") + "</p>" return "\n\n".join(grafs) def _add_footnotes(self, text): if self.footnotes: footer = [ '<div class="footnotes">', '<hr' + self.empty_element_suffix, '<ol>', ] for i, id in enumerate(self.footnote_ids): if i != 0: footer.append('') footer.append('<li id="fn-%s">' % id) footer.append(self._run_block_gamut(self.footnotes[id])) backlink = ('<a href="#fnref-%s" ' 'class="footnoteBackLink" ' 'title="Jump back to footnote %d in the text.">' '&#8617;</a>' % (id, i+1)) if footer[-1].endswith("</p>"): footer[-1] = footer[-1][:-len("</p>")] \ + '&nbsp;' + backlink + "</p>" else: footer.append("\n<p>%s</p>" % backlink) footer.append('</li>') footer.append('</ol>') footer.append('</div>') return text + '\n\n' + '\n'.join(footer) else: return text # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin: # http://bumppo.net/projects/amputator/ _ampersand_re = re.compile(r'&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)') _naked_lt_re = re.compile(r'<(?![a-z/?\$!])', re.I) _naked_gt_re = re.compile(r'''(?<![a-z?!/'"-])>''', re.I) def _encode_amps_and_angles(self, text): # Smart processing for ampersands and angle brackets that need # to be encoded. text = self._ampersand_re.sub('&amp;', text) # Encode naked <'s text = self._naked_lt_re.sub('&lt;', text) # Encode naked >'s # Note: Other markdown implementations (e.g. Markdown.pl, PHP # Markdown) don't do this. text = self._naked_gt_re.sub('&gt;', text) return text def _encode_backslash_escapes(self, text): for ch, escape in g_escape_table.items(): text = text.replace("\\"+ch, escape) return text _auto_link_re = re.compile(r'<((https?|ftp):[^\'">\s]+)>', re.I) def _auto_link_sub(self, match): g1 = match.group(1) return '<a href="%s">%s</a>' % (g1, g1) _auto_email_link_re = re.compile(r""" < (?:mailto:)? ( [-.\w]+ \@ [-\w]+(\.[-\w]+)*\.[a-z]+ ) > """, re.I | re.X | re.U) def _auto_email_link_sub(self, match): return self._encode_email_address( self._unescape_special_chars(match.group(1))) def _do_auto_links(self, text): text = self._auto_link_re.sub(self._auto_link_sub, text) text = self._auto_email_link_re.sub(self._auto_email_link_sub, text) return text def _encode_email_address(self, addr): # Input: an email address, e.g. "foo@example.com" # # Output: the email address as a mailto link, with each character # of the address encoded as either a decimal or hex entity, in # the hopes of foiling most address harvesting spam bots. E.g.: # # <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101; # x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111; # &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a> # # Based on a filter by Matthew Wickline, posted to the BBEdit-Talk # mailing list: <http://tinyurl.com/yu7ue> chars = [_xml_encode_email_char_at_random(ch) for ch in "mailto:" + addr] # Strip the mailto: from the visible part. addr = '<a href="%s">%s</a>' \ % (''.join(chars), ''.join(chars[7:])) return addr def _do_link_patterns(self, text): """Caveat emptor: there isn't much guarding against link patterns being formed inside other standard Markdown links, e.g. inside a [link def][like this]. Dev Notes: *Could* consider prefixing regexes with a negative lookbehind assertion to attempt to guard against this. """ link_from_hash = {} for regex, repl in self.link_patterns: replacements = [] for match in regex.finditer(text): if hasattr(repl, "__call__"): href = repl(match) else: href = match.expand(repl) replacements.append((match.span(), href)) for (start, end), href in reversed(replacements): escaped_href = ( href.replace('"', '&quot;') # b/c of attr quote # To avoid markdown <em> and <strong>: .replace('*', g_escape_table['*']) .replace('_', g_escape_table['_'])) link = '<a href="%s">%s</a>' % (escaped_href, text[start:end]) hash = _hash_text(link) link_from_hash[hash] = link text = text[:start] + hash + text[end:] for hash, link in link_from_hash.items(): text = text.replace(hash, link) return text def _unescape_special_chars(self, text): # Swap back in all the special characters we've hidden. for ch, hash in g_escape_table.items(): text = text.replace(hash, ch) return text def _outdent(self, text): # Remove one level of line-leading tabs or spaces return self._outdent_re.sub('', text) class MarkdownWithExtras(Markdown): """A markdowner class that enables most extras: - footnotes - code-color (only has effect if 'pygments' Python module on path) These are not included: - pyshell (specific to Python-related documenting) - code-friendly (because it *disables* part of the syntax) - link-patterns (because you need to specify some actual link-patterns anyway) """ extras = ["footnotes", "code-color"] #---- internal support functions # From http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549 def _curry(*args, **kwargs): function, args = args[0], args[1:] def result(*rest, **kwrest): combined = kwargs.copy() combined.update(kwrest) return function(*args + rest, **combined) return result # Recipe: regex_from_encoded_pattern (1.0) def _regex_from_encoded_pattern(s): """'foo' -> re.compile(re.escape('foo')) '/foo/' -> re.compile('foo') '/foo/i' -> re.compile('foo', re.I) """ if s.startswith('/') and s.rfind('/') != 0: # Parse it: /PATTERN/FLAGS idx = s.rfind('/') pattern, flags_str = s[1:idx], s[idx+1:] flag_from_char = { "i": re.IGNORECASE, "l": re.LOCALE, "s": re.DOTALL, "m": re.MULTILINE, "u": re.UNICODE, } flags = 0 for char in flags_str: try: flags |= flag_from_char[char] except KeyError: raise ValueError("unsupported regex flag: '%s' in '%s' " "(must be one of '%s')" % (char, s, ''.join(flag_from_char.keys()))) return re.compile(s[1:idx], flags) else: # not an encoded regex return re.compile(re.escape(s)) # Recipe: dedent (0.1.2) def _dedentlines(lines, tabsize=8, skip_first_line=False): """_dedentlines(lines, tabsize=8, skip_first_line=False) -> dedented lines "lines" is a list of lines to dedent. "tabsize" is the tab width to use for indent width calculations. "skip_first_line" is a boolean indicating if the first line should be skipped for calculating the indent width and for dedenting. This is sometimes useful for docstrings and similar. Same as dedent() except operates on a sequence of lines. Note: the lines list is modified **in-place**. """ DEBUG = False if DEBUG: print "dedent: dedent(..., tabsize=%d, skip_first_line=%r)"\ % (tabsize, skip_first_line) indents = [] margin = None for i, line in enumerate(lines): if i == 0 and skip_first_line: continue indent = 0 for ch in line: if ch == ' ': indent += 1 elif ch == '\t': indent += tabsize - (indent % tabsize) elif ch in '\r\n': continue # skip all-whitespace lines else: break else: continue # skip all-whitespace lines if DEBUG: print "dedent: indent=%d: %r" % (indent, line) if margin is None: margin = indent else: margin = min(margin, indent) if DEBUG: print "dedent: margin=%r" % margin if margin is not None and margin > 0: for i, line in enumerate(lines): if i == 0 and skip_first_line: continue removed = 0 for j, ch in enumerate(line): if ch == ' ': removed += 1 elif ch == '\t': removed += tabsize - (removed % tabsize) elif ch in '\r\n': if DEBUG: print "dedent: %r: EOL -> strip up to EOL" % line lines[i] = lines[i][j:] break else: raise ValueError("unexpected non-whitespace char %r in " "line %r while removing %d-space margin" % (ch, line, margin)) if DEBUG: print "dedent: %r: %r -> removed %d/%d"\ % (line, ch, removed, margin) if removed == margin: lines[i] = lines[i][j+1:] break elif removed > margin: lines[i] = ' '*(removed-margin) + lines[i][j+1:] break else: if removed: lines[i] = lines[i][removed:] return lines def _dedent(text, tabsize=8, skip_first_line=False): """_dedent(text, tabsize=8, skip_first_line=False) -> dedented text "text" is the text to dedent. "tabsize" is the tab width to use for indent width calculations. "skip_first_line" is a boolean indicating if the first line should be skipped for calculating the indent width and for dedenting. This is sometimes useful for docstrings and similar. textwrap.dedent(s), but don't expand tabs to spaces """ lines = text.splitlines(1) _dedentlines(lines, tabsize=tabsize, skip_first_line=skip_first_line) return ''.join(lines) class _memoized(object): """Decorator that caches a function's return value each time it is called. If called later with the same arguments, the cached value is returned, and not re-evaluated. http://wiki.python.org/moin/PythonDecoratorLibrary """ def __init__(self, func): self.func = func self.cache = {} def __call__(self, *args): try: return self.cache[args] except KeyError: self.cache[args] = value = self.func(*args) return value except TypeError: # uncachable -- for instance, passing a list as an argument. # Better to not cache than to blow up entirely. return self.func(*args) def __repr__(self): """Return the function's docstring.""" return self.func.__doc__ def _xml_oneliner_re_from_tab_width(tab_width): """Standalone XML processing instruction regex.""" return re.compile(r""" (?: (?<=\n\n) # Starting after a blank line | # or \A\n? # the beginning of the doc ) ( # save in $1 [ ]{0,%d} (?: <\?\w+\b\s+.*?\?> # XML processing instruction | <\w+:\w+\b\s+.*?/> # namespaced single tag ) [ \t]* (?=\n{2,}|\Z) # followed by a blank line or end of document ) """ % (tab_width - 1), re.X) _xml_oneliner_re_from_tab_width = _memoized(_xml_oneliner_re_from_tab_width) def _hr_tag_re_from_tab_width(tab_width): return re.compile(r""" (?: (?<=\n\n) # Starting after a blank line | # or \A\n? # the beginning of the doc ) ( # save in \1 [ ]{0,%d} <(hr) # start tag = \2 \b # word break ([^<>])*? # /?> # the matching end tag [ \t]* (?=\n{2,}|\Z) # followed by a blank line or end of document ) """ % (tab_width - 1), re.X) _hr_tag_re_from_tab_width = _memoized(_hr_tag_re_from_tab_width) def _xml_encode_email_char_at_random(ch): r = random() # Roughly 10% raw, 45% hex, 45% dec. # '@' *must* be encoded. I [John Gruber] insist. # Issue 26: '_' must be encoded. if r > 0.9 and ch not in "@_": return ch elif r < 0.45: # The [1:] is to drop leading '0': 0x63 -> x63 return '&#%s;' % hex(ord(ch))[1:] else: return '&#%s;' % ord(ch) #---- mainline class _NoReflowFormatter(optparse.IndentedHelpFormatter): """An optparse formatter that does NOT reflow the description.""" def format_description(self, description): return description or "" def _test(): import doctest doctest.testmod() def main(argv=None): if argv is None: argv = sys.argv if not logging.root.handlers: logging.basicConfig() usage = "usage: %prog [PATHS...]" version = "%prog "+__version__ parser = optparse.OptionParser(prog="markdown2", usage=usage, version=version, description=cmdln_desc, formatter=_NoReflowFormatter()) parser.add_option("-v", "--verbose", dest="log_level", action="store_const", const=logging.DEBUG, help="more verbose output") parser.add_option("--encoding", help="specify encoding of text content") parser.add_option("--html4tags", action="store_true", default=False, help="use HTML 4 style for empty element tags") parser.add_option("-s", "--safe", metavar="MODE", dest="safe_mode", help="sanitize literal HTML: 'escape' escapes " "HTML meta chars, 'replace' replaces with an " "[HTML_REMOVED] note") parser.add_option("-x", "--extras", action="append", help="Turn on specific extra features (not part of " "the core Markdown spec). Supported values: " "'code-friendly' disables _/__ for emphasis; " "'code-color' adds code-block syntax coloring; " "'link-patterns' adds auto-linking based on patterns; " "'footnotes' adds the footnotes syntax;" "'xml' passes one-liner processing instructions and namespaced XML tags;" "'pyshell' to put unindented Python interactive shell sessions in a <code> block.") parser.add_option("--use-file-vars", help="Look for and use Emacs-style 'markdown-extras' " "file var to turn on extras. See " "<http://code.google.com/p/python-markdown2/wiki/Extras>.") parser.add_option("--link-patterns-file", help="path to a link pattern file") parser.add_option("--self-test", action="store_true", help="run internal self-tests (some doctests)") parser.add_option("--compare", action="store_true", help="run against Markdown.pl as well (for testing)") parser.set_defaults(log_level=logging.INFO, compare=False, encoding="utf-8", safe_mode=None, use_file_vars=False) opts, paths = parser.parse_args() log.setLevel(opts.log_level) if opts.self_test: return _test() if opts.extras: extras = {} for s in opts.extras: splitter = re.compile("[,;: ]+") for e in splitter.split(s): if '=' in e: ename, earg = e.split('=', 1) try: earg = int(earg) except ValueError: pass else: ename, earg = e, None extras[ename] = earg else: extras = None if opts.link_patterns_file: link_patterns = [] f = open(opts.link_patterns_file) try: for i, line in enumerate(f.readlines()): if not line.strip(): continue if line.lstrip().startswith("#"): continue try: pat, href = line.rstrip().rsplit(None, 1) except ValueError: raise MarkdownError("%s:%d: invalid link pattern line: %r" % (opts.link_patterns_file, i+1, line)) link_patterns.append( (_regex_from_encoded_pattern(pat), href)) finally: f.close() else: link_patterns = None from os.path import join, dirname, abspath, exists markdown_pl = join(dirname(dirname(abspath(__file__))), "test", "Markdown.pl") for path in paths: if opts.compare: print "==== Markdown.pl ====" perl_cmd = 'perl %s "%s"' % (markdown_pl, path) o = os.popen(perl_cmd) perl_html = o.read() o.close() sys.stdout.write(perl_html) print "==== markdown2.py ====" html = markdown_path(path, encoding=opts.encoding, html4tags=opts.html4tags, safe_mode=opts.safe_mode, extras=extras, link_patterns=link_patterns, use_file_vars=opts.use_file_vars) sys.stdout.write( html.encode(sys.stdout.encoding or "utf-8", 'xmlcharrefreplace')) if opts.compare: test_dir = join(dirname(dirname(abspath(__file__))), "test") if exists(join(test_dir, "test_markdown2.py")): sys.path.insert(0, test_dir) from test_markdown2 import norm_html_from_html norm_html = norm_html_from_html(html) norm_perl_html = norm_html_from_html(perl_html) else: norm_html = html norm_perl_html = perl_html print "==== match? %r ====" % (norm_perl_html == norm_html) if __name__ == "__main__": sys.exit( main(sys.argv) )
Python
from markdown2 import * from gluon.html import XML def WIKI(text, encoding="utf8", safe_mode='escape', html4tags=False, **attributes): if not text: test = '' if attributes.has_key('extras'): extras = attributes['extras'] del attributes['extras'] else: extras=None text = text.decode(encoding,'replace') return XML(markdown(text,extras=extras, safe_mode=safe_mode, html4tags=html4tags)\ .encode(encoding,'xmlcharrefreplace'),**attributes)
Python
""" Developed by Massimo Di Pierro, optional component of web2py, GPL2 license. """ import re import pickle import copy def quote(text): return str(text).replace('\\', '\\\\').replace("'", "\\'") class Node: """ Example:: # controller from gluon.contrib.spreadsheet import Sheet def callback(): return cache.ram('sheet1', lambda: None, None).process(request) def index(): sheet = cache.ram('sheet1', lambda: Sheet(10, 10, URL(r=request, f='callback')), 0) #sheet.cell('r0c3', value='=r0c0+r0c1+r0c2', readonly=True) return dict(sheet=sheet) # view {{extend 'layout.html'}} {{=sheet}} or insert invidivual cells via {{=sheet.nodes['r0c0']}} """ def __init__(self, name, value, url='.', readonly=False, active=True, onchange=None): self.url = url self.name = name self.value = str(value) self.computed_value = '' self.incoming = {} self.outcoming = {} self.readonly = readonly self.active = active self.onchange = onchange self.size = 4 self.locked = False def xml(self): return """<input name="%s" id="%s" value="%s" size="%s" onkeyup="ajax('%s/keyup',['%s'], ':eval');" onfocus="ajax('%s/focus',['%s'], ':eval');" onblur="ajax('%s/blur',['%s'], ':eval');" %s/> """ % (self.name, self.name, self.computed_value, self.size, self.url, self.name, self.url, self.name, self.url, self.name, (self.readonly and 'readonly ') or '') def __repr__(self): return '%s:%s' % (self.name, self.computed_value) class Sheet: regex=re.compile('(?<!\w)[a-zA-Z_]\w*') re_strings = re.compile(r'(?P<name>' + r"[uU]?[rR]?'''([^']+|'{1,2}(?!'))*'''|" + r"'([^'\\]|\\.)*'|" + r'"""([^"]|"{1,2}(?!"))*"""|' + r'"([^"\\]|\\.)*")', re.DOTALL) def dumps(self): dump = pickle.dumps(self) return dump @staticmethod def loads(data): sheet = pickle.loads(data) return sheet def process(self, request): """ call this in action that creates table, it will handle ajax callbacks """ cell = request.vars.keys()[0] if request.args(0) == 'focus': return "jQuery('#%s').val('%s');" % (cell, quote(self[cell].value)) value = request.vars[cell] self[cell] = value if request.args(0) == 'blur': return "jQuery('#%s').val('%s');" \ % (cell, quote(self[cell].computed_value)) elif request.args(0) == 'keyup': jquery = '' for other_key in self.modified: if other_key != cell: jquery += "jQuery('#%s').val('%s');" % \ (other_key, quote(self[other_key].computed_value)) return jquery def __init__(self, rows, cols, url='.', readonly=False, active=True, onchange=None): self.rows = rows self.cols = cols self.url = url self.nodes = {} self.error = 'ERROR: %(error)s' self.allowed_keywords = ['for', 'in', 'if', 'else', 'and', 'or', 'not', 'i', 'j', 'k', 'x', 'y', 'z', 'sum'] self.environment = {} [self.cell('r%sc%s'%(k/cols, k%cols), '0.0', readonly, active, onchange) for k in xrange(rows*cols)] exec('from math import *', {}, self.environment) def delete_from(self, other_list): indices = [k for (k, node) in enumerate(other_list) if k == node] if indices: del other_list[indices[0]] def changed(self, node, changed_nodes=[]): for other_node in node.outcoming: if not other_node in changed_nodes: changed_nodes.append(other_node) self.changed(other_node, changed_nodes) return changed_nodes def define(self, name, obj): self.environment[name] = obj def cell(self, key, value, readonly=False, active=True, onchange=None): """ key is the name of the cell value is the initial value of the cell. It can be a formula "=1+3" a cell is active if it evaluates formuls """ key = str(key) if not self.regex.match(key): raise SyntaxError, "Invalid cell name: %s" % key node = Node(key, value, self.url, readonly, active, onchange) self.nodes[key] = node self[key] = value def __setitem__(self, key, value): key = str(key) value = str(value) node = self.nodes[key] node.value = value if value[:1] == '=' and node.active: # clear all edges involving current node for other_node in node.incoming: del other_node.outcoming[node] node.incoming.clear() # build new edges command = self.re_strings.sub("''", value[1:]) node.locked = False for match in self.regex.finditer(command): other_key = match.group() if other_key == key: self.computed_value = self.error % dict(error='cycle') self.modified={} break if other_key in self.nodes: other_node = self.nodes[other_key] other_node.outcoming[node] = True node.incoming[other_node] = True elif not other_key in self.allowed_keywords and \ not other_key in self.environment: node.locked = True node.computed_value = \ self.error % dict(error='invalid keyword: ' + other_key) self.modified = {} break self.compute(node) else: try: node.computed_value = int(node.value) except: try: node.computed_value = float(node.value) except: node.computed_value = node.value self.environment[key] = node.computed_value if node.onchange: node.onchange(node) self.modified = self.iterate(node) def compute(self, node): if node.value[:1] == '=' and not node.locked: try: exec('__value__=' + node.value[1:], {}, self.environment) node.computed_value = self.environment['__value__'] del self.environment['__value__'] except Exception, e: node.computed_value = self.error % dict(error=str(e)) self.environment[node.name] = node.computed_value if node.onchange: node.onchange(node) def iterate(self, node): output = {node.name: node.computed_value} changed_nodes = self.changed(node) while changed_nodes: ok=False set_changed_nodes = set(changed_nodes) for (k, other_node) in enumerate(changed_nodes): #print other_node, changed_nodes if not set(other_node.incoming.keys()).\ intersection(set_changed_nodes): #print 'ok' self.compute(other_node) output[other_node.name] = other_node.computed_value #print other_node del changed_nodes[k] ok = True break if not ok: return {} return output def __getitem__(self, key): return self.nodes[str(key)] def get_computed_values(self): d={} for key in self.nodes: node = self.nodes[key] if node.value[:1] != '=' or not node.active: d[key] = node.computed_value return d def set_computed_values(self, d): for key in d: if not key in self.nodes: continue node = self.nodes[key] if node.value[:1] != '=' or not node.active: node.value = d[key] def xml(self): import gluon.html (DIV, TABLE, TR, TD, TH, BR) = \ (gluon.html.DIV, gluon.html.TABLE, gluon.html.TR, gluon.html.TD, gluon.html.TH, gluon.html.BR) regex = re.compile('r\d+c\d+') return DIV(TABLE(TR(TH(), *[TH('c%s' % c) for c in range(self.cols)]), *[TR(TH('r%s' % r), *[TD(self.nodes['r%sc%s'%(r, c)]) \ for c in range(self.cols)]) \ for r in range(self.rows)]), BR(), TABLE(*[TR(TH(key), TD(self.nodes[key])) \ for key in self.nodes if not regex.match(key)])).xml() if __name__ == '__main__': s = Sheet(0, 0) s.cell('a', value="2") s.cell('b', value="=sin(a)") s.cell('c', value="=cos(a)**2+b*b") print s['c'].computed_value
Python
#!/usr/bin/python """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) Attention: Requires Chrome or Safari. For IE of Firefox you need https://github.com/gimite/web-socket-js 1) install tornado easy_install tornado 2) start this app: python gluon/contrib/comet_messaging.py -k mykey -p 8888 3) from any web2py app you can post messages with from gluon.contrib.comet_messaging import comet_send comet_send('http://127.0.0.1:8888','Hello World','mykey','mygroup') 4) from any template you can receive them with <script> $(document).ready(function(){ if(!web2py_comet('ws://127.0.0.1:8888/realtime/mygroup',function(e){alert(e.data)})) alert("html5 websocket not supported by your browser, try Google Chrome"); }); </script> When the server posts a message, all clients connected to the page will popup an alert message Or if you want to send json messages and store evaluated json in a var called data: <script> $(document).ready(function(){ var data; web2py_comet('ws://127.0.0.1:8888/realtime/mygroup',function(e){data=eval('('+e.data+')')}); }); </script> - All communications between web2py and comet_messaging will be digitally signed with hmac. - All validation is handled on the web2py side and there is no need to modify comet_messaging.py - Multiple web2py instances can talk with one or more comet_messaging servers. - "ws://127.0.0.1:8888/realtime/" must be contain the IP of the comet_messaging server. - Via group='mygroup' name you can support multiple groups of clients (think of many chat-rooms) Here is a complete sample web2py action: def index(): form=LOAD('default','ajax_form',ajax=True) script=SCRIPT(''' jQuery(document).ready(function(){ var callback=function(e){alert(e.data)}; if(!web2py_comet('ws://127.0.0.1:8888/realtime/mygroup',callback)) alert("html5 websocket not supported by your browser, try Google Chrome"); }); ''') return dict(form=form, script=script) def ajax_form(): form=SQLFORM.factory(Field('message')) if form.accepts(request,session): from gluon.contrib.comet_messaging import comet_send comet_send('http://127.0.0.1:8888',form.vars.message,'mykey','mygroup') return form Acknowledgements: Tornado code inspired by http://thomas.pelletier.im/2010/08/websocket-tornado-redis/ """ import tornado.httpserver import tornado.websocket import tornado.ioloop import tornado.web import hmac import sys import optparse import urllib import time listeners = {} names = {} tokens = {} def comet_send(url,message,hmac_key=None,group='default'): sig = hmac_key and hmac.new(hmac_key,message).hexdigest() or '' params = urllib.urlencode({'message': message, 'signature': sig, 'group':group}) f = urllib.urlopen(url, params) data= f.read() f.close() return data class PostHandler(tornado.web.RequestHandler): """ only authorized parties can post messages """ def post(self): if hmac_key and not 'signature' in self.request.arguments: return 'false' if 'message' in self.request.arguments: message = self.request.arguments['message'][0] group = self.request.arguments.get('group',['default'])[0] print '%s:MESSAGE to %s:%s' % (time.time(), group, message) if hmac_key: signature = self.request.arguments['signature'][0] if not hmac.new(hmac_key,message).hexdigest()==signature: return 'false' for client in listeners.get(group,[]): client.write_message(message) return 'true' return 'false' class TokenHandler(tornado.web.RequestHandler): """ if running with -t post a token to allow a client to join using the token the message here is the token (any uuid) allows only authorized parties to joins, for example, a chat """ def post(self): if hmac_key and not 'message' in self.request.arguments: return 'false' if 'message' in self.request.arguments: message = self.request.arguments['message'][0] if hmac_key: signature = self.request.arguments['signature'][0] if not hmac.new(hmac_key,message).hexdigest()==signature: return 'false' tokens[message] = None return 'true' return 'false' class DistributeHandler(tornado.websocket.WebSocketHandler): def open(self,params): group,token,name = params.split('/')+[None,None] self.group = group or 'default' self.token = token or 'none' self.name = name or 'anonymous' # only authorized parties can join if DistributeHandler.tokens: if not self.token in tokens or not token[self.token]==None: self.close() else: tokens[self.token] = self if not self.group in listeners: listeners[self.group]=[] # notify clients that a member has joined the groups for client in listeners.get(self.group,[]): client.write_message('+'+self.name) listeners[self.group].append(self) names[self] = self.name print '%s:CONNECT to %s' % (time.time(), self.group) def on_message(self, message): pass def on_close(self): if self.group in listeners: listeners[self.group].remove(self) del names[self] # notify clients that a member has left the groups for client in listeners.get(self.group,[]): client.write_message('-'+self.name) print '%s:DISCONNECT from %s' % (time.time(), self.group) if __name__ == "__main__": usage = __doc__ version= "" parser = optparse.OptionParser(usage, None, optparse.Option, version) parser.add_option('-p', '--port', default='8888', dest='port', help='socket') parser.add_option('-l', '--listen', default='0.0.0.0', dest='address', help='listener address') parser.add_option('-k', '--hmac_key', default='', dest='hmac_key', help='hmac_key') parser.add_option('-t', '--tokens', action='store_true', default=False, dest='tokens', help='require tockens to join') (options, args) = parser.parse_args() hmac_key = options.hmac_key DistributeHandler.tokens = options.tokens urls=[ (r'/', PostHandler), (r'/token', TokenHandler), (r'/realtime/(.*)', DistributeHandler)] application = tornado.web.Application(urls, auto_reload=True) http_server = tornado.httpserver.HTTPServer(application) http_server.listen(int(options.port), address=options.address) tornado.ioloop.IOLoop.instance().start()
Python
# fix response import re import os import cPickle import gluon.serializers from gluon import current from gluon.html import markmin_serializer, TAG, HTML, BODY, UL, XML from gluon.contenttype import contenttype from gluon.contrib.pyfpdf import FPDF, HTMLMixin from gluon.sanitizer import sanitize from gluon.contrib.markmin.markmin2latex import markmin2latex from gluon.contrib.markmin.markmin2pdf import markmin2pdf def wrapper(f): def g(data): try: output = f(data) except (TypeError, ValueError): raise HTTP(405, '%s serialization error' % extension.upper()) except ImportError: raise HTTP(405, '%s not available' % extension.upper()) except: raise HTTP(405, '%s error' % extension.upper()) return XML(ouput) return g def latex_from_html(html): markmin=TAG(html).element('body').flatten(markmin_serializer) return XML(markmin2latex(markmin)) def pdflatex_from_html(html): if os.system('which pdflatex > /dev/null')==0: markmin=TAG(html).element('body').flatten(markmin_serializer) out,warning,errors=markmin2pdf(markmin) if errors: current.response.headers['Content-Type']='text/html' raise HTTP(405,HTML(BODY(H1('errors'), LU(*errors), H1('warnings'), LU(*warnings))).xml()) else: return XML(out) def pyfpdf_from_html(html): request = current.request def image_map(path): if path.startswith('/%s/static/' % request.application): return os.path.join(request.folder,path.split('/',2)[2]) return 'http%s://%s%s' % (request.is_https and 's' or '',request.env.http_host, path) class MyFPDF(FPDF, HTMLMixin): pass pdf=MyFPDF() pdf.add_page() html = sanitize(html, escape=False) #### should have better list of allowed tags pdf.write_html(html,image_map=image_map) return XML(pdf.output(dest='S')) def pdf_from_html(html): # try use latex and pdflatex if os.system('which pdflatex > /dev/null')==0: return pdflatex_from_html(html) else: return pyfpdf_from_html(html)
Python
import re, cPickle, random, datetime IUP = {'shoebill':{'a':1,'187':1},'trout-like':{'parr':1},'fig.':{'19':1},'mcintosh.':{'the':1,'illustration':1},'chiasmodon':{'niger':2},'yellow':{'and':4,'giant':1,'green':2,'red':1,'spots':1},'four':{'brightly':1,'hundred':1,'haunts':1,'feet':1,'solutions':2,'hours.':1,'things':1,'long':1,'.':2,'legs':1,'inches':4,'thousand':1,'million':1,'pairs':2,'hours':1,'satellites':1,'tufts':1,'great':1,'main':1,'of':1,'months':1,'days':1,'times':4,'volumes':1,'inches.':1,'frilled':2,'or':3},'snapping-blades':{'the':1},'aegir':{'on':4},'hanging':{'down':1,'on':2},'bird--evidences':{'of':1},'canes':{'venatici':1},'inheritance.':{'looking':1},'electricity':{'and':5,'belong':1,'is':4,'rotating':2,'held':1,'as':1,'sec':1,'in':1,'yet':1,'predominates':1,'from':1,'there':1,'.':9,'to':1,'which':4,';':4,'has':1,'we':1,'that':1,'here':1,'i.e':1,'like':1,'repel':1,'the':2,'or':1,'attracting':1},'similarity':{'of':3,'between':1},'sunlit':{'side':1},'superficially':{'indistinguishable':1,'like':1},'out-breeding':{'among':1,'when':1,'exogamy':1},'lord':{'popular':1,'kelvin':5,'avebury':1},'non-intelligent':{'experiments':1},'flicking':{'out':1},'meadows':{'and':2,'an':1},'sinking':{'down':2,'according':1,'in':1},'digit':{'of':1,'well':1},'co-operation':{'of':2},'oceans':{'lie':1,'of':1,'there':1,'are':1,'goes':1,'must':1},'pigment':{'and':1,'is':2,'.':1,'as':1,'which':1,';':1},'figs':{'.':1},'fingers.':{'but':1},'experimentally':{'on':1},'bringing':{'of':1,'about':1,'the':2},'elevations':{'and':1,'of':1},'meadow.':{'in':1},'internally':{'hot':1},'whitman':{'says':1,'took':1},'colour--the':{'result':2},'stars.':{'yet':1},'persisted':{'as':1,'until':1},'chameleons':{'the':1,'.':1},'intensification':{'of':1},'succession':{'giving':1,'of':5,'the':1,'has':1,'.':1},'tube--the':{'walls':1},'ultra-violet':{'and':1,'light':1,'waves--which':1,'or':1,'waves':1},'straight':{'ahead':1,'drop':1,'lines':1,'down':1,'through':1,'in':1,'path':2,'line':1,'legs':1,'along':1},'spiders':{'about':1,'were':1,'it':1,'.':1,'scorpions':1,'are':1,'have':1,'in':1},'specially':{'protected':1,'adapted':1},'symmetry.':{'illustration':1},'stiffens':{'.':1},'270':{'a':1,'silk':1,'reproduced':1},'271':{'electrical':1,'from':1},'second':{'and':5,'layer':1,'when':1,'year':1,'extinction':1,'yet':1,'any':1,'group':1,'would':3,'there':1,'question':2,'.':10,'to':1,'millennium':1,'which':1,';':1,'then':1,'we':1,'advantage':1,'that':1,'class':1,'screen.':1,'interglacial':1,'every':1,'longest':1,'not':1,'cousin':1,'copy':1,'opportunity':1,'by':1,'a':1,'great':1,'these':1,'of':1,'or':1,'preparation':1,'printing':1,'error':1,'position':1,'the':2,'chapter':1,'photograph':2},'attended':{'the':1,'by':2},'274':{'photo':1},'275':{'from':1},'278':{'hours':1,'photo':1},'279':{'rotating':1,'the':2},'inanimate':{'world':1},'dormancy':{'.':1},'errors':{'a':1,'in':1},'semicircular':{'canals':1},'phalangers':{'and':1,'flying':1},'thunder':{'and':1,'means':1},'nature.':{'the':1,'typical':1,'what':1,'illustration':1,'one':1},'contributed':{'every':1},'fingers':{'and':6,'to':1,';':1,'2':1,'knocking':1},'lowliness':{'.':1},'fossil':{'horses':1,'remains':2,'series':1,'forms':2,'scorpions':1,'of':2,'species':1},'increasing':{'control--a':1,'temperature':1,'facility':1,'intelligence':1,'complexity':2,'fullness':1,'the':1,'with':1,'day':1},'inducement':{'many':1},'surface--the':{'photosphere--is':1},'chins':{'and':1},'error':{'a':1,'we':1,'is':1,'here':1,'method':2,'to':1,';':1,'or':1,'must':1},'here':{'and':5,'says':1,'is':5,'within':1,'some':1,'it':1,'anticipating':1,'go':1,'seen':1,'again':4,'for':1,'also':1,'rather':1,'concerned':1,'since':1,'.':1,'to':3,'only':2,'cockchafers':1,'you':1,'was':2,'refer':1,'we':2,'let':1,'with':1,'nor':1,'a':1,'of':1,'spontaneously':1,'the':2,'stimulating':1,'are':1},'atoms':{'and':10,'being':1,'is':1,'an':1,'270':1,'whilst':1,'exist':1,'are':4,'have':1,'in':3,'seem':1,'seek':1,'containing':1,'indivisible':1,'from':1,'appear':1,'would':1,'with':1,'had':1,'.':5,'which':2,'got':1,';':2,'has':1,'was':1,'into':1,'do':2,'form':1,'were':4,'but':1,'atoms':2,'break':1,'most':1,'they':1,'put':1,'come':1,'themselves':1,'he':1,'for':1,'of':33,'enter':1,'the':2,'first':1,'at':1},'reported':{'to':1,'in':1,'that':1},'china':{'and':1},'evolutionist':{'s':1,'ideas':1,'suggestion':1},'fire.':{'chief':1,'saturn':1},'substance':{'in':1,'both':1,'from':2,'would':1,'is':1,'after':1,'glowing':1,'reaches':1,'.':3,'will':1,'to':1,'as':2,'but':1,'which':2,'were':1,'known':1,'has':1,'by':1},'contribute.':{'another':1},'k':{'.':1},'second--more':{'than':1},'reports':{'performances':1},'controversy':{'as':1},'forbes':{'observed':1,'tells':1,'history':1},'symmetrical':{'fishes.':1},'heidelbergensis':{'discovered':1},'appropriately':{'giants':1},'divide':{'a':1,'in':1},'owed':{'to':1},'explained':{'on':1,'because':1,'presently':1,'that':1,'later':1,'in':4,'by':1},'lengthen':{'the':1},'replace':{'the':4,'it':1},'brought':{'about':3,'to':3,'into':2,'up':1,'us':1,'their':1,'outside':1,'near':2,'through':1,'together':1,'in':1,'the':1,'its':1},'larger.':{'6':1},'female.':{'the':1},'obligation':{'works':1},'unit':{'body':1,'of':1,'for':1,'areas':1},'disproved--e.g':{'.':1},'spoke':{'of':3},'temperature.':{'if':1},'1892':{'.':1},'occupying':{'a':1},'vol':{'.':4},'untie':{'knots':1},'therefore':{'there':1,'is':2,'it':1,'one':2,'as':1,'are':2,'have':1,'even':1,'little':1,'since':1,'to':1,'survey':1,'means':1,'more':1,'form':1,'that':7,'imagine':1,'not':1,'conspicuous':1,'must':1,'a':2,'always':1,'so':1,'contain':1,'the':1,'called':1},'strike':{'a':1,'to':1,'the':2},'fossiliferous':{'beds':1},'until':{'comparatively':1,'some':1,'it':7,'one':1,'discovered':1,'at':3,'in':1,'its':2,'there':1,'when':1,'finally':1,'we':1,'recently':1,'that':1,'they':5,'such':1,'inconceivable':1,'a':3,'both':1,'i':1,'near':1,'the':3,'once':1},'skill.':{'illustration':1},'females':{'go':1,'the':1,'who':1,'use':1},'9.':{'instinctive':1},'successful':{'hunting':1,'accomplishment':2,'.':1,'notably':1,'race':1,'animal':1,'in':1,'performance':1,';':2,'class':1},'brings':{'about':1,'his':1,'this':1,'them':1,'us':1,'obvious':1,'the':1},'whirling':{'nebulae.':1,'gaseous':1,'streams':1,'motions':1,'electrons':1,'ring':1,'round':1},'glass':{'and':1,'on':1,'by':1,'blown':1,'wall':1,'of':1,'tube':1,'jar':1,'prism':3,'vulcanite':1,'.':2,'walls':1,'vibrate':1,'prism--a':1,'the':2,'tubes':1,'model':2},'inwards':{'each':1},'91':{'photo':1,'after':1,'pictorial':1},'90':{'photo':1,'from':1,'days':2,'per':1},'midst':{'of':1},'92':{'830':2,'as':1,'fossil':1},'95':{'photo':1,'from':1},'immature':{'sperm':1,'egg':1,'larval':1},'circumstances':{'and':1,'of':1,'it':1,'however':1,'indicate':1,'as':1},'locked':{'up':3},'mimickers':{'do':1,'live':1,'though':1,'survive--although':1},'pursue':{'further':1,'the':1},'accomplishment':{'of':2,'would':1},'plunged':{'in':1},'tell-tale':{'evidence':2},'temperatures':{'and':2,'as':1,'enormously':1,'but':1,';':1},'concepts':{'differ':1,'or':1},'plunges':{'into':1},'example':{'a':2,'passes':1,'of':5,'is':1,'three':1,'.':1,'the':1,'out':1},'type.':{'there':1,'steps':1,'it':1,'illustration':1},'encouragement.':{'evidences':1},'nitrates':{'which':1},'organized':{'under':1},'shore.':{'the':1},'dragons':{'and':1,'a':1,'for':1,'stalking':1,'which':1,'the':1,'or':1},'glued':{'to':1,'together':2},'caution':{'is':2,':':1,'in':2},'kingdoms':{'to':1},'want':{'to':1,'that':1},'oil-sheet':{'by':1},'absolute':{'cold':1,'calm':1,'zero':2},'disappearing.':{'thus':1},'travel':{'from':2,'for':1,'that':2,'fifteen':1,'is':1,'it':1,'.':2,'through':1,'at':3,'in':3,'rapidly':1,'with':1,'by':1,'round':1},'drying':{'up':1},'feature':{'of':2,'is':1,'in':2,'that':1},'machine':{'and':1,'readable':1,'which':1,'in':1},'how':{'beautiful':1,'this':2,'all':2,'useful':1,'striking':1,'vertebrates':1,'abundantly':1,'it':6,'long':4,'in':1,'curious':1,'your':1,'their':2,'thoroughly':1,'sunlight':1,'.':1,'to':9,'much':1,'--all':1,'he':1,'admirable':1,'is':1,'whipped':1,'noble':1,'we':4,'express':1,'do':4,'men':1,'but':1,'soon':1,'magnetism':1,'important':1,'infinite':1,'man':1,'a':1,'like':2,'these':2,'many':4,'could':2,'well':1,'swiftly':1,'did':1,'electrons':1,'can':1,'the':14,'professor':1,'are':2},'krait':{':':2,'should':1},'hop':{'.':1},'significance':{'of':3,'is':1,'.':1,'was':1,'that':1},'mueller':{'where':1},'uselessness':{'of':1},'utilise':{'their':1,'the':7,'atomic':1,'directly':1},'ptarmigan':{'very':1,'moults':1},'diagram':{'a':1,'and':1,'illustrating':3,'illustrates':2,'of':10,'showing':3,'.':4,'fig':2,'shows':2,'is':3,'constructed':1},'dinosaurs':{'and':1,'it':1,'which':1,'in':1},'wrong':{'and':1,'side':1,'though':1},'lattice-work':{'than':1,'but':1},'destined':{'to':3,'within':1},'twined':{'round':1},'pearl-bearing':{'river-mussels':1},'factor.':{'we':1},'types':{'and':2,'we':1,'like':2,'especially':1,'that':2,'of':10,'it':1,'.':2,'are':3,'which':3,'suited':1,'the':1,'has':1,'nearly':1},'calves':{'young':1},'effective':{'and':1,'substitutes':1,'ways':1,'camouflaging':1,'flying':1,'.':1,'action':1,';':1,'response':1},'endeavoured':{'instead':1},'attracts':{'every':1},'headquarters':{'of':1},'specks':{'faintly':1},'keeps':{'the':1,'as':1,'an':1},'back--till':{'we':1},'wing':{'and':1,'remains':1,'of':4,'is':3,'.':3,'while':1,'action':1,'has':1,'was':2},'wind':{'and':3,'tugs':1,'from':1,'around':1,'that':1,'pay':1,'.':1,'falls':1},'wine':{'decanter':1},'ovule':{'so':1},'restriction':{'attendant':1},'school.':{'as':1},'effect.':{'the':1,'illustration':1},'vary':{'a':1,'enormously':1,'.':1},'halfpennies':{'.':1},'microbe':{'or':1},'fore-limbs':{'and':3,'a':1,'emerging':1,'of':1},'elevated':{'into':1},'rewarded':{'the':2},'throne.':{'illustration':1},'wrought':{'on':1,'out':2,'in':1},'admirably':{'suited':1},'matures':{'or':1},'fit':{'and':2,'effected':1,'variations':1,'will':1,'to':2,'beautiful':1,'lasts':1,'the':1},'bodies--evolution':{'of':2},'heretofore':{'unimagined':1},'fix':{'dates':1,'after':1,'the':1},'occupations':{'and':1,'whether':1},'survivors':{'in':1},'woolly-haired':{'africans':1,'african':1},'anticipations':{'at':1},'fig':{'4':1,'.':36},'nobler':{'more':1},'hidden':{'disc':1,'from':1,'secrets.':1,'or':1},'alpine':{'heights':1},'admirable':{'indeed':1,'is':1,'adjustment':1,'in':1},'easier':{'to':4,'for':1},'bristle':{'.':1},'bolton.':{'the':3,'orang-utan':1,'chimpanzee':1,'cassowary':1},'f.r.s':{'.':1},'effects':{'and':1,'on':1,'from':1,'of':2,'due':1,'.':1,'are':1},'stars;':{'their':1},'coal-fields':{'is':1,'can':1},'devices.':{'vii':1,'illustration':1},'prize':{'is':1},'represents':{'a':2,'the':4,'an':1},'educable.':{'illustration':1},'humming-birds':{'we':1},'arrow':{'round':1,'shows':1},'obdurate':{'solid':1},'burial':{'customs':1},'financial':{'support':1},'telescope':{'and':1,'because':1,'show':1,'developed':1,'is':4,'it':1,'depends':1,'at':1,'in':1,'takes':1,'49':1,'remains':1,'.':3,':':1,'was':1,'brings':1,'construction':2,'with':1,'of':1,'mount':2,'weigh':1,'the':2},'garment':{'of':5,'by':1,'.':1},'spider':{'called':1,'203':1,'has':1,'that':1,'may':2,'dr':1,'ascends':1,'after':1,'reaches':1,'sunning':2,'jerks':1,'to':4,'s':1,'which':1,'--brushes':1,'with':1,'is':1,'ornithoscatoides':1},'parasites':{'a':1,'have':1,'may':1,'casual':1,'as':1,'are':2,'which':1,'or':1,'often':1},'armour--the':{'sea-urchin':1},'contracting':{'striped':1,'muscles':1,'mass':1,'the':1,'its':1},'depositing':{'eggs':1},'laboratory':{'cambridge':1,'would':1,'had':1,'but':1,'.':1,'at':1,'in':1,';':1,'or':1},'nerve-cell':{'s.c.':1,'m.c.':1,'a.c.':1},'message':{'travels':3,'is':2,'reaches':1},'borne':{'on':1,'just':1,'away':1,'in':1,'usually':1,'by':2,'out':1},'speed.':{'in':1},'excepting':{'the':1},'ice-sheets':{'retreated':1},'unrelated':{'types':1},'adapt':{'itself':1},'centauri':{'4.29':1,'estimated':1},'foundation':{'and':3,'web':1,'makes':1,'is':2,'as':1,'.':3,'project':1,'how':1,'s':3,'at':1,'in':1,'the':5,'was':1,'or':1,'are':1,'anyone':1},'stamping':{'a':1},'assured':{'that':1},'waddle':{'130':1},'strata':{'of':3,'is':1,'when':1,'contained':1,'have':1,';':1,'with':1},'solution':{'containing':1,'that':1,'may':1,'of':4,'within':1,'when':1,'has':1,'was':1},'sensory':{'nerve-fibre':2,'nerve-cell':1,'equipment':1,'nerve-cells':1,'stimulus':1,'fibres':1,'alertness':1},'born.':{'but':1},'crowned':{'with':1},'estimate':{'and':1,'obtained':1,'being':1,'how':1,'this':1,'of':2,'its':1,'these':1,'by':1},'universally':{'true':1},'enormous':{'distances':2,'energy':1,'number':1,'disc-like':1,'pressure--2-1':1,'size':1,'infantile':2,'vibration':1,'speed':1,'depths.':1,'amount':2,'increase':1,'pressures':1,'role':1,'store':1,'dilatable':1,'pressure':1,'jets':1,'velocities':1,'length':1,'activity':1,'velocity':1,'the':1},'bates':{'tells':1,'but':1},'exposing':{'it':1},'merychippus':{';':1,'miocene':1},'shelves':{'of':1},'hind-limbs':{'of':2},'perhaps.':{'moreover':1},'elements--we':{'have':1},'disturbed':{'development':1,'and':1,'.':2},'tempting':{'but':1,'one':1},'ineffectively':{'or':1},'speeds':{'to':1},'appreciable':{'atmosphere':1},'gas-bubbles':{'and':1,'in':1},'wasp':{'or':1,'beetle':2},'subtlety':{'in':1,'that':1},'maladies':{'to':1},'channels':{'or':1},'spinning':{'slowly':1,'threads':1,'round':1},'179':{'a':1,'photograph':1,'reproduced':1},'178':{'photo':1,'after':1},'likes.':{'illustration':1},'175':{'after':1},'174':{'after':1},'flagella':{'.':1},'172':{'000':1,'piltdown':1},'171':{'reproduced':1},'170':{'after':1,'from':1},'bitten':{'by':1},'service':{'to':1,'in':2,'abroad':1,'.':1},'similarly':{'for':1,'suggest':1,'when':1,'our':1,'the':3,'adapted':1,'out':1},'cooling':{'and':1,'white-hot':1,'of':3,'metal':1,'but':1,'down':3,'earth':1,'the':1},'needed':{'.':1,'for':1,'in':1},'master':{'of':1,'the':2,'different':1},'blossoms':{'.':1},'gilbert':{'white':1},'legs':{'and':4,'on':1,'free':1,'.':3,'to':1,'indents':1,'so':1,'are':1,'out':1},'genesis':{'of':1,'.':1},'treasure-house':{'of':1},'listen':{'it':1},'rewards':{'to':1},'fibrous':{'husk':1},'wisdom':{'of':1,'in':1},'egg-producer':{'.':1},'motionless':{'on':1,'at':1,'that':1},'predictable':{'and':1},'collaterals':{'hundreds':1,'.':1},'scarborough':{'and':2},'positively':{'say':2,'that':1,'into':1,'charged':1},'insect-visitors':{';':1},'surer':{'by':1},'showed':{'a':1,'on':1,'great':1,'for':1,'that':9,'is':1,'how':2,'simian':1,'the':1},'miniatures':{'of':1},'tree':{'and':2,'217':1,'notice':1,'of':5,'into':1,'struggles':1,'but':1,'.':2,'to':3,'near':1,'i.e':1,'with':1,'is':2,'before':1},'likely':{'to':5,'that':1,'unless':1,'it':1,'however':1},'idly':{'on':1,'why':1},'project':{'gutenberg-tm':56,'gutenberg':29,'gutenberg:':1,'gutenberg-tm.':1,'from':1},'fly-trap':{'77':1,'when':1,'one':1},'feeling':{'and':2,'of':1,'is':1,'.':1,'their':2,'things':1,'or':1},'acquisition':{'almost':1,'of':1,'made':1,'associated':1,'by':1},'life--the':{'first':2},'groaning':{'and':3},'objects':{'and':1,'do':1,'for':1,'very':1,'but':1,'.':2,'271':1,'take':1,'in':2},'similitude':{'of':2},'oxygen-capture':{';':1},'spectrum':{'and':2,'rays':1,'provides':1,'of':4,'is':2,'emitted':1,'analysis':2,'.':3,'will':1,'as':1,'are':1,'have':1,'the':2},'controversy.':{'in':1},'antagonistic':{'substances':1},'well.':{'illustration':1},'constricted':{'off':1},'oxygen-combustion':{'the':1},'dozen':{'eggs':1,'classes':1,'by':1,'years':1},'affairs':{'on':1,';':1,'would':1},'wholesome':{'superstitions':1},'yolk-forming':{'and':1},'person':{'often':1,'you':1,'or':3,'can':1},'eagerly':{'following':1},'metallic':{'vapours':1},'toothed':{'whales':1,'bird':2,'birds':1},'australia--all':{'sometimes':1},'absorbed':{'but':1,'so':1,'in':1,';':1,'with':1,'by':2},'doors':{'and':1,'of':1,'.':1,'depositing':1,'which':1,'were':1},'season':{'209':1,'it':1,'illustration':1},'concedes':{'the':1},'rhodesia':{'very':1,'178':1},'shall':{'be':2,'we':1,'deal':1,'give':1,'predict':1,'explain':2,'never':1,'content':1,'see':11,'have':1,'not':1,'see.':2,'find':2,'refer':1},'screwing':{'the':1,'it':1},'object':{'and':1,'we':1,'of':2,'.':1,'to':1,'too':1,'in':2,'drawn':1},'diminishing':{'in':1},'victoria':{'b':1,'british':2},'gill-cavity':{'and':1},'mouth':{'and':5,'of':1,'is':1,'there':2,'.':6,'allied':1,'are':1,'in':1,'the':1,'where':1,'into':1,'came':1},'long.':{'in':1},'letter':{'is':1,'there':1,'o':2},'drought':{'and':2,'is':1,'frost':1,'by':1,'extremes':1},'hide-and-seek':{'game':1},'difficulties.':{'illustration':1},'expound':{'their':1},'redistribution':{'is':1},'episode':{'in':1},'available.':{'many':1},'professor':{'holmes':2,'and':1,'thomas':2,'j':3,'tacchini':1,'rayleigh':1,'michael':1,'frederick':1,'chamberlin':1,'yerkes':3,'hickson':1,'starling':1,'lull':3,'church':2,'soddy':3,'eddington':4,'sir':8,'le':1,'royal':1,'young':1,'pickering':1,'soddy.':1,'john':1,'gamble':2,'soddy--as':1,'oscar':1,'perrin':1,'william':1,'flinders':1,'buller':1,'wood':1,'thorndike':3,'e':2,'whitman':1,'h':2,'later':1,'poulton':1,'l':2,'curie':1,'s':1,'r':6,'bayliss':1,'w':3,'of':3,'schuchert':2,'percival':2,'left':1,'schwalbe':1,'lloyd':2},'nineteenth':{'century.':2,'century':6},'mating':{'.':1},'incomplete':{'inaccurate':1,'.':1},'marvel':{'that':1},'hobhouse':{'has':1,'had':1},'insects':{'and':5,'belonging':1,'related':1,'extinct':1,'spring-tails':1,'pterodactyls':1,'whose':1,'by':2,'appear':1,'perhaps':1,'divided':1,'.':3,'to':1,'only':1,'which':1,'birds':1,'we':1,'that':2,'rest':1,'such':1,'with':1,'than':1,'on':1,'made':1,'like':1,'could':1,'carries':1,'can':1,'the':2,'where':1,'spend':1},'sea-snakes':{'such':1},'feather-stars':{'on':1},'apace':{'there':1},'touches':{'the':1,'some':1,'one':1},'flagellates--the':{'originators':1},'methods--one':{'using':1},'shuffling':{'a':1,'the':1},'quaint':{'insects':1,'lop-eared':1,'ways':1,'explorer':1,'creatures':2},'unrest.':{'many':1},'character':{'of':1,'set':1,'except':1},'bush':{'in':1},'touched':{'it.':1,'on':1,'by':1},'rich':{'repertory':1,'inheritance':1,'area':1,'seaweed':1,'in':4},'rice':{';':1},'plate':{'and':2,'reveals':1,'may':1,'of':3,'is':1,'there':1,'however':1,'.':4,'underneath':1,'to':1,'goes':1,';':1,'has':1,'holder':1},'well-advanced':{'stage':1},'wide':{'of':1,'range':2,'spread':1,'departures':1,'apart':1},'foremost':{'living':1},'pocket':{'and':1,'of':1,'is':1},'insect.':{'masking':1},'altogether':{'and':1,'we':1,'from':1,'obscure.':1,'there':1,'.':1,'lies':1,'inattentive.':1,'extinct':1,'the':1,'apart':1},'tips':{'of':1,'form':1},'transmissible.':{'given':1},'societies':{'.':1},'greens':{'and':1},'dipnoi':{'which':1},'patch':{'of':2,'which':1},'men.':{'we':1,'the':1},'fitly':{'use':1},'release':{'date':1,'harness':1},'them.':{'1':1,'we':1,'clodd':1},'hasten':{'matters':1,'however':1},'lesson.':{'we':1},'circling':{'eddies':1,'round':1},'protists':{'the':1,'which':1},'evolutionism':{'with':1},'traverse':{'matter':1,'we':1},'fair':{'to':1},'radium':{'and':6,'discharges':1,'270':1,'as':1,'sec':1,'in':1,'salts':1,'passes':2,'rays':8,'began':1,'that':1,'when':1,'.':2,'to':1,'rays.':1,'john':2,'was':2,'generates':1,'captivated':1,'may':1,'now':1,'a':1,'implied':1,'the':2,'or':2},'niche':{'of':2,'among':1},'radius':{'and':1},'result':{'we':1,'of':10,'is':1,'when':1,'.':1,'will':4,'as':1,'strange':1,'which':1,'in':1,'not':1,'was':2},'fail':{'to':4},'nocturnal':{'birds':1,'animal':1},'skulls':{'high':1,'of':1,'.':1},'best':{'methods':1,'for':1,'of':2,'explanation':1,'.':1,'to':1,'while':1,'suited':1,'thermometer':1,'illustrations':1,'i.e':1,'has':1,'dress':1,'conductors.':1},'oceanic':{'islands':1},'rings':{'and':1,'from':1,'of':1,'mighty':1,'are':1,'in':1,'the':1,'round':1},'frond-like':{'tassels':1,'tags':1},'stealthy':{';':1,'stalking':1},'pressures':{'the':1,'that':1},'score':{'of':1,'but':1,'which':1},'conceptual':{'as':1,'inference':1,'inference--or':1},'propagated':{';':1},'circulating':{'at':1,'the':1,'round':1,'as':1,'in':1},'glasgow':{'and':1},'magnesium':{';':1},'preserve':{'free':1},'claws':{'on':3,'especially':1,'.':1},'men':{'and':2,'indicated':1,'it':1,'as':1,'at':1,'have':1,'oftener':1,'still':1,'ancient':1,'.':5,'to':1,'that--':1,'who':4,'proving':1,'but':2,'arose':1,'with':1,'like':2,'of':19,'s':1,'so':1,'were':1,'the':1,'powers':1,'or':1},'extend':{'far':1,'our':1,'the':1,'towards':1,'outwards':1},'nature':{'and':3,'because':1,'less':1,'is':1,'some':1,'depends':1,'acts':1,'draws':1,'would':1,'there':1,'had':1,'.':5,'which':1,'messrs':2,'drawn':1,';':1,'has':2,'was':3,'more':1,'never':1,'but':1,'includes':1,'november':1,'the':1,'a':1,'about':1,'of':28,'s':8,'ninety-two':1,'messrs.':2,'or':1,'involves':2},'blood-containing':{'tufts':1},'twinkling':{'of':1},'cards':{'and':1,'with':1,'but':1,'.':1,'are':1,'come':1},'extent':{'and':1,'on':2,'what':1,'gauged':1,'of':1,'able':1,'intelligently':1,'by':1,'to':1,';':1,'permitted':1},'carbon':{'immersed':1,'compounds':4,'hydrogen':1,'until':1,'dioxide':1},'debt':{'repaid':1},'well-lighted':{'surface':1},'tyranny':{'of':3},'outcome':{'of':12,'is':2},'sacrificing':{'accuracy':1},'refinement':{'and':1},'country':{'then':1,'of':1,'to':1,'outside':1,'in':2,'nothing':1,'the':1},'conclusions':{'are':1,'which':1},'heating':{'process':1},'tree-toads':{'tree-snakes':1},'dents':{'or':1},'argue':{'fire':1},'adapted':{'for':14,'many':1,'.':1,'to':12,'itself':1,'so':1,'in':1},'asked':{'perhaps':1,'to':1,'what':1,'for':3},'exogamy':{'tending':1},'vain':{'and':1},'canyon':{'60':1,'many':1},'259':{'professor':1},'irresponsibly':{'they':1},'252':{'reproduced':1},'250':{'what':1,'000':2,'miles':1,'fathoms':2,'the':1,'inconceivable':1},'251':{'a':1},'grazing':{'mammals':1,'the':1,'herds':1,'bison':2,'in':1},'254':{'photo':1,'from':1,'reproduced':1},'255':{'reproduced':1},'101':{'after':1},'berenices':{'is':1,'.':1},'union':{'of':3,'with':1},'fro':{'about':1,'more':1},'.':{'secondly':1,'all':12,'three-toed':2,'sci':2,'skeleton':1,'chain':1,'holman':1,'mcintosh.':2,'four':1,'zinc':1,'foundations':1,'contributions':1,'magnifying':1,'certainly':1,'fahr.':1,'father':1,'young':2,'miall':1,'to':27,'finally':2,'romanes':1,'lord':1,'non-intelligent':1,'protective':1,'7':4,'very':5,'every':12,'dando':1,'radio-active':1,'well-finished':1,'f.r.s':1,'louis':1,'laying':1,'t.':1,'p':9,'hickson':1,'small':2,'indemnity':1,'round':1,'upper':1,'feathers':1,'yerkes':1,'electricians':1,'further':1,'langmuir':1,'blue':1,'what':24,'17.--a':1,'pariasaurus':1,'paintings':1,'section':1,'above':3,'dr.':1,'new':3,'movement':1,'cheetahs':1,'sci.':1,'men':1,'here':10,'hundreds':1,'anthropology':2,'let':7,'others':3,'along':3,'f.r.s.':1,'neville':1,'daughter':1,'dividing':1,'chalmers':1,'k':1,'compliance':1,'forbes':3,'usually':1,'adopting':1,'holmes':1,'saunders':3,'24.--the':1,'berridge':8,'newby':1,'cuttlefishes':1,'everybody':1,'from':21,'russell':3,'would':1,'remains':1,'positive':1,'two':5,'anatomical':1,'examination':1,'therefore':2,'6':6,'taken':2,'until':2,'on':19,'flying':3,'inclined':1,'berridge.':10,'chimpanzee':1,'lodge':1,'everywhere':1,'hilger':2,'baby':2,'bates':2,'ward':21,'huxley':3,'dando.':3,'none':2,'animals':2,'f':5,'this':102,'science':5,'when':39,'piltdown':1,'3--the':1,'making':1,'male':1,'history':3,'frogs':1,'high':1,'something':1,'story':1,'presently':1,'sir':2,'end':1,'starch':1,'astronomers':3,'how':7,'orang-utan':1,'occasionally':1,'s.':1,'intelligent':1,'side-view':2,'millikan':2,'information':3,'slipher':1,'perrin':1,'after':15,'deep-sea':1,'waves':1,'such':10,'man':4,'a':95,'forestier':3,'light':6,'clavius':1,'osborn':3,'so':24,'kippax':1,'iii.':1,'sc':1,'evolutionary':1,'barnard':2,'pelican':1,'indeed':4,'21.--typical':1,'murray':2,'thomson':7,'helena':1,'experiments':2,'still':2,'its':14,'soddy':1,'before':1,'25':1,'27':1,'21':1,'22':1,'28':1,'wilkinson.':2,'lowell':5,'23.--star':1,'fabre.':2,'26.--a':1,'estuaries':1,'they':99,'compound':1,'not':6,'olcott':1,'now':23,'nor':2,'nos':1,'6.--solar':1,'f.e.s.':1,'james':1,'radiant':1,'reid.':2,'scharff':1,'associative':1,'weighs':1,'everyone':2,'directly':1,'needless':2,'series':2,'fish':1,'journ':2,'macmillan':3,'12.--jupiter':1,'owing':1,'our':5,'hart':1,'special':2,'out':2,'living':4,'9.--the':1,'furthermore':1,'since':2,'may':1,'america.':3,'safety':1,'rational':1,'10.--solar':1,'sluggish':1,'red':1,'7.--the':1,'quite':1,'fourteen':1,'extraordinary':1,'experimenting':1,'besides':6,'put':3,'detecting':2,'keith':1,'ll.d':2,'organic':1,'g':1,'where':2,'hence':5,'first':3,'18.--a':1,'copper':1,'already':1,'plainly':1,'thereafter':1,'one':16,'another':9,'mercury':1,'given':2,'ancient':2,'limited':2,'similarly':4,'anyone':2,'their':13,'2':23,'caterpillars':1,'white':1,'speaking':2,'x-rays':2,'that':23,'19.--comet':1,'part':2,'somewhat':1,'gilbert':1,'11':1,'10':2,'13':2,'b':7,'15':1,'14':2,'17':1,'16':2,'second':2,'project':3,'matter':2,'r':3,'algol':1,'other':4,'are':1,'and':41,'clerk-maxwell':3,'ltd.':2,'pliocene':1,'ages':4,'lull':4,'sentences':1,'1':26,'apparently':1,'any':1,'viewed':1,'eels':1,'u.s':1,'mic':1,'gravity':1,'note':5,'also':1,'without':4,'take':1,'sirius':1,'even':16,'play':2,'unless':4,'wilson.':2,'though':1,'price':1,'who':2,'hincks':1,'most':6,'combustion':1,'nothing':1,'america':1,'nutritive':1,'constitution':1,'firelight':1,'22.--a':1,'dragon-flies':1,'professor':12,'later':2,'heat':2,'looked':1,'25--giant':1,'electrons':7,'prout':1,'normally':1,'laws':1,'stones':1,'hobhouse':1,'aquatic':1,'charles':2,'14.--the':1,'lloyd':1,'uranus':1,'earth':1,'hinkins':2,'copyright':1,'duncan':1,'only':4,'going':2,'molecules':2,'humdrum':1,'thompson':1,'8':5,'4.--the':1,'darwin':4,'thousands':1,'combe':1,'do':3,'his':1,'fossil':1,'meanwhile':2,'15.--mars':1,'there':106,'watch':1,'watson':1,'12':2,'nearly':2,'distinctly':1,'during':3,'silk':2,'dr':1,'crabs':1,'evolution':3,'h':27,'girdled':1,'twice':2,'discs':1,'20.--comet':1,'she':8,'gibson':1,'1922':1,'intelligence':1,'radium':2,'notice':3,'j.':2,'sec':1,'mud-nests':1,'mcgregor.':12,'5.--diagram':1,'tropisms':1,'federal':1,'artificial':1,'birds':1,'3':19,'between':5,'probably':2,'email':1,'crookes':2,'we':115,'tylor':1,'fox-bat':1,'however':5,'8.--the':1,'atoms':2,'both':7,'c':18,'wallace':1,'many':17,'taking':1,'according':6,'s':21,'1.--diagrams':1,'johnstone':1,'otherwise':1,'among':4,'goodrich':1,'simple':4,'had':1,'jeans':1,'whatever':3,'pycraft':1,'church':1,'moreover':9,'newbigin':1,'broadening':1,'marett':1,'geddes':1,'much':5,'sponges':1,'bragg':2,'life':3,'modern':1,'partly':1,'c.':1,'four-toed':1,'luther':1,'13.--saturn':1,'shepstone.':6,'races':1,'despite':1,'an':14,'161':1,'those':4,'sound':1,'adaptations':1,'unlike':1,'these':36,'lightner':1,'16.--the':1,'n':2,'while':2,'suppose':1,'viii':1,'2.--the':1,'fore-limb':2,'then':4,'vol':1,'vi':1,'is':4,'thus':48,'it':317,'iv':2,'ii':2,'middle':2,'in':152,'mcgregor':2,'if':76,'jenner':1,'headley':1,'perhaps':13,'things':1,'make':1,'sollas':1,'babies':1,'9':2,'several':1,'yucca':1,'higher':1,'ball':1,'see':4,'kelvin':1,'v.':1,'kinnaman':1,'moving':2,'lower':2,'i':3,'no':11,'mccabe':1,'contact':1,'furneaux':1,'comparisons':1,'the':569,'redistribution':1,'just':2,'being':1,'generally':1,'rest':1,'ideas':1,'disguise':1,'ritchie':2,'years':1,'paul':1,'yet':11,'like':1,'smith':1,'except':2,'potential':1,'4':15,'5':8,'putnam':2,'possibly':1,'boxes':1,'royalty':2,'five':1,'6.':1,'apart':4,'tail':1,'d':1,'lightning':1,'enregistered':1,'arthur':7,'donations':1,'t':1,'interbreeding':1,'webb':1,'old':1,'flattely':1,'triceratops':1,'some':37,'jupiter':2,'easygoing':1,'gradually':1,'for':44,'shall':1,'skeletons':1,'everything':2,'does':1,'subtlest':1,'newcomb':2,'11.--mars':1,'each':13,'illustration':2,'subconscious':1,'great':1,'although':4,'affording':1,'by':18,'macpherson.':1,'actual':1,'extending':1,'of':25,'o':1,'sea-horse':1,'whence':3,'larmor':1,'gregory':1,'consequently':1,'or':6,'naturalists':1,'serviss':1,'kapp':1,'reactions':1,'within':3,'chemists':1,'mic.':1,'mills.':2,'haddon':2,'protozoa':1,'swimmers':1,'nowadays':1,'theoretically':1,'technically':1,'doubtless':1,'linnaeus':1,'additional':1,'her':1,'placing':1,'brute':1,'long':1,'why':2,'moseley':3,'daniell':1,'stars':1,'duffus.':2,'energy':3,'naturally':1,'lowest':1,'gluten':1,'mammals':1,'but':138,'cloth':1,'curiously':1,'white.':1,'with':8,'he':39,'october':1,'whether':5,'j':40,'up':1,'idiosyncrasies':1,'stages':1,'similar':2,'sometimes':6,'taste':1,'certain':1,'metals':1,'general':2,'as':35,'ether':1,'at':22,'adams':2,'again':1,'compared':2,'curie':1,'9.':1,'c.:':1,'pickering':1,'electrical':1,'you':12,'picture':1,'energetic':1,'carpenter':1,'marshes':1,'fishes':2,'ramsay':1,'building':1,'e':5,'glass':1,'persistent':1,'together':1,'brocklehurst.':4,'mckready':1,'functionless':1,'keane':1,'once':1},'much':{'indebted':1,'harm':1,'smaller':2,'less':4,'wall':1,'intelligence':1,'subtlety':1,'alive':1,'parasites':1,'as':5,'disarranged':1,'right':1,'in':5,'sought':1,'beyond':1,'exhausted':1,'if':1,'nearer':2,'use':1,'cut':1,'from':1,'for':4,'.':2,'better':1,'to':10,'changed':1,'change':1,'progress':1,';':1,'has':1,'dreaded':1,'energy':2,'more':24,'scepticism':1,'used':2,'paperwork':1,'greater':5,'trace':1,'that':1,'importance':2,'gliding':1,'is':1,'controversy':1,'damaged':1,'denser':1,'speculation':1,'bigger':1,'simpler':1,'a':1,'on':1,'surer':1,'faster':1,'of':5,'larger':2,'stronger':1,'greater--a':1,'easier':1,'so':1,'truth':1,'light':1,'the':3,'movement':1},'pedigree--man':{'s':1},'104':{'after':1},'sponges':{'stinging':1,'zoophytes':1,'jellyfishes':1,'spongillidae':1,'are':1,'corals':1,'jellyfish':1},'smolts':{'and':1,'which':1},'fry':{'become':1,'about':2,'rises':1,'ltd.':2},'105':{'an':1},'exactness':{'with':1},'life':{'and':15,'among':1,'because':1,'although':1,'exists':1,'is':6,'it':1,'lies':1,'namely':1,'through':4,'are':3,'in':13,'palaeozoic':1,'best':1,'if':1,'depend':1,'for':1,'to':4,'remains':1,'began':1,'there':2,'had':1,'1914':1,'1':1,'.':17,'of':19,'whole':1,'which':3,';':4,'before':1,'was':2,'as':4,'than':1,'that':1,'after':1,'possible':1,'illustration':1,'but':4,'utterly':1,'during':1,'166':1,'continued':1,'by':1,'a':1,'on':18,'depends.':1,'has':4,'animals':1,'1921':2,'many':1,'depends':2,'will':1,'s':1,'can':1,'though':1,'each':1,'at':1,'taxed':1,'the':3,'history':1,'where':1,'or':1,'72':1},'latro':{'that':2},'retrospect':{'looking':1},'in-breeding':{'endogamy':1,'tended':1},'conifers':{'and':1,'ginkgos':1,'shall':1},'luther':{'the':1,'burbank':1},'shepstone.':{'light':1,'the':2,'modern':1,'100-inch':1,'lightning':1},'connaissance':{'du':1},'tree-mice':{'tree-porcupines':1},'child':{'of':4,'s':4,'does':1,'.':1,'that':1},'chili':{'where':1},'spin':{'round':1},'breast-pocket':{';':1},'control--a':{'promise':1},'adaptations':{'and':1,'of':1,'or':1,'to':5,'which':1,'such':1,'by':1},'heidelberg':{'man':5,':':2,'was':1,'sand-pit':1,'in':2},'contemp':{'.':1},'viii':{'foundations':1,'.':2},'flooding':{'space':1},'elaborate':{'burial':1},'picturing':{'a':1},'remembering':{'the':1,'that':1},'played':{'an':1},'equator':{'and':1,'of':1,'.':1,'seems':1,'i.e':1},'photographer.':{'as':1},'obeying':{'the':2},'player':{'is':1},'australia':{'perhaps':2,'is':1,'190':1,'it':1,'to':1,'neoceratodus':1,'which':1,'the':1,'95':1},'anticipating':{'the':1,'we':1},'south.':{'illustration':1},'plants.':{'sec':1,'illustration':1},'said.':{'illustration':1},'open-water':{'period':1,'turtles':1},'damaged':{'disk':1,'by':1},'feebler':{'and':1,'until':1},'things':{'and':6,'endowed':1,'is':1,'effectively':1,'as':1,'are':1,'in':2,'dr':1,'.':6,'to':1,'which':2,'wildly':1,';':1,'was':1,'horses':1,'do':1,'we':3,'that':5,'with':1,'you':1,'he':1,'on':1,'like':1,'e.g':1,'without':1,'mixed':1,'or':1},'format':{'other':1,'with':1,'used':1,'must':1},'killdeer':{'plover':1},'dissimilars':{'tends':1},'clucking':{'of':1},'gateways':{'to':1,'of':3},'double-breathers':{'dipnoi':1},'elliott':{'fry.':2,'fry':1},'emphatic':{'notice':1,'rejection':1},'european':{'fauna':1,'lynx':1},'increased.':{'electrons':1,'illustration':1},'fairly':{'what':1,'complicated':1,'mastered':1},'typhoid':{'fever':1},'georgics':{'to':1},'middle-aged':{'and':1},'effectively':{'to':1,'e.g':1,'conquered.':1,'.':1},'pioneers':{'men':1},'race-history':{'.':1},'tune':{'to':1},'registering':{'steps':1},'stupendous':{'energy':1,'collection':1,'.':1},'matters':{'little':1,'greatly':1},'erectus':{'found':1},'-mammal':{'and':1},'raindrops':{'and':1},'opinions':{'with':1},'boyhood':{'the':1},'sea-skimmers':{'halobatidae':1},'sleeps':{'upright':1},'golden':{'draperies':1,'plover':1,'age':5,'eagles.':1,';':1},'expensively':{'for':1},'distribute':{'a':1,'this':1,'copies':1,'it':1,'the':1,'or':2},'rotated':{'that':1},'beset':{'with':1},'disguise':{'and':1,'besides':1,'is':1,'.':3,'sec':1,'which':1,'differs':1,'the':1,'with':1,'or':1},'neanderthalers':{'and':1},'falcon':{'s':2},'glue-like':{'threads':1},'hen-pigeon':{'may':1},'rushing':{'torrent':1},'succeeding':{'ages':2},'lasso':{'minute':1},'99712':{'.':1},'spectacles':{'in':1},'seal':{'right':1},'old-fashioned':{'type':1,'way':1},'had':{'gone':2,'remained':1,'appeared':2,'dived':1,'some':1,'few':1,'increased':1,'brought':1,'wit':1,'at':1,'human':1,'seen':1,'swallowed':1,'enjoyed':1,'to':8,'really':1,'established':1,'given':1,'surmised':1,'proceeded':1,'rushed':1,'there':2,'been':18,'anatomical':1,'their':5,'only':1,'definitely':1,'emerged':1,'probably':1,'learned':2,'mainly':1,'claws':2,'his':1,'tried':1,'feathers':1,'gathered':1,'never':1,'extended':1,'anticipated':1,'its':4,'haunted':1,'no':4,'survived':1,'become':2,'not':6,'suspected':1,'disappeared':1,'undoubtedly':1,'a':10,'discovered':1,'great':2,'these':1,'many':1,'actually':1,'fish-like':1,'large':1,'passed':2,'teeth':2,'found':1,'the':1,'pulled':1,'waited':1,'something':1},'salmon--forming':{'new':1},'thickening':{'or':1},'saturn--the':{'moon--the':1},'collections':{'of':1},'easy':{'business':1,'for':1,'haunt':1,'.':4,'to':6,'times--glacial':1},'irresponsive':{'.':1},'botanists':{'that':1},'east':{'has':1,'when':1,'are':1,'which':1},'eocene':{'and':1,'n':1,'era':1,'n.':1,'period':1},'good-humoured':{'talkativeness':1},'up--a':{'clever':1},'elevation':{'and':1,'of':2},'survival':{'of':1,'with':1,'.':2},'semi-fluid':{'carbon':1},'possible':{'origin':1,'and':1,'instruments':1,'it':1,'according':1,'are':1,'in':1,'moreover':1,'yet':1,'enemies':1,'again':1,'evolution.':1,'for':4,'basis':1,'favouring':1,'.':1,'colours':1,'to':13,'that':6,'however':1,'but':1,'a':1,'kind':1,'outline':1,'when':1,'haunts':1,'seeds':1,'steps':1,'victory':1,'error':1,'or':1},'knife-blade-like':{'to':2,'larva':2},'firmer':{'though':1},'possibly':{'run':1,'show':1,'there':1,'outside':1,'attain':1,'have':1,'in':1},'indicative':{'not':1,'of':1},'birth':{'and':2,'of':2,'gestation':1,'.':3,'to':1,'the':1,'with':1},'shadow':{'and':1,'cast':2,'across':1,'on':1},'unique':{'and':1,'solution':1,'in':1,'property':1,'ensemble':1,'discovery':1},'12:30':{'p.m':1},'occurring':{'in':2},'desire':{'to':3,'that':1},'skull-walls':{'sir':1},'collection.':{'a':1,'lord':2,'charles':1,'sir':1,'j':1},'process--a':{'process':1,'building':1},'enregistered':{'reactions':1,'rhythms':1,'hereditarily':1,'it':1,'instinctive':2,'reactions.':1},'steps':{'followed':1,'of':1,'per':1,'which':1,'in':9,'by':1},'beneficial':{'partnerships':1,'partnership':1,'external':1,'.':1},'right':{'and':1,'into':1,'we':1,'as':1,'at':1,'in':1,'out':1,'indicate':1,'away':1,'to':2,'answer':1,'has':1,'146':1,'resting':1,'direction':1,'hand':1,'angles':4,'path':1,'with':1,'this':1,'of':4,'or':2},'old':{'quarters':1,'philosophical':1,'before':1,'terrestrial':1,'lady':1,'young':2,'.':1,'to':1,'going':1,'which':1,'entomologist':1,'editions':1,';':1,'red':2,'showing':1,'middle-aged':1,'they':1,'world':2,'with':2,'stone':4,'land':1,'word':1,'could':1,'haunts':1,'race':1,'so':1,'margin':1,'view':1},'creek':{'.':1},'crowd':{'of':1},'people':{'then':1,'would':1,'213':1,'just':1,'their':1,'arguing':1,'who':1,'.':1,'start':1,'s':1,'know':1,'have':3,'in':1,'fail':1,'wrongly':1},'predominance':{'of':1},'crown':{'of':3,'corona':1,'but':1},'deflection':{'of':3},'crows':{'but':1},'dragons--the':{'first':1},'animate':{'nature':5},'creep':{'slowly':1,'up':2},'enemies':{'a':1,'and':1,'for':1,'who':1,'except':1,'but':1,'.':5,'as':1,'which':1},'for':{'all':6,'aquatic':2,'untold':1,'unseen':1,'accurate':1,'seizing':4,'years':3,'egg-laying':1,'not':1,'existence.':2,'converting':1,'its':11,'negligence':1,'current':1,'rapid':1,'knowledge':1,'instance':25,'body-making.':1,'reasons':1,'believing':1,'capturing':1,'pursuing':1,'grasping':1,'weeks':1,'thousands':3,'over':3,'them':1,'good':1,'worse':1,'food':7,'gauging':1,'balancing':2,'existence--which':1,'every':3,'nearly':2,'they':8,'half':2,'mixing':4,'highly':1,'several':2,'identifying':3,'humming-birds':1,'this':8,'miles':1,'common':1,'activity':2,'speculation':1,'bone':2,'dexterity':1,'another':2,'intelligence':1,'radium':1,'some':4,'catching':4,'jupiter':1,'vocal':1,'existence':13,'our':4,'sport':2,'special':1,'blood-vessel':1,'crunching':1,'what':2,'three':1,'giving':1,'drifting':1,'brief':1,'increase':1,'new':3,'allowing':1,'receiving':1,'ever':4,'safety.':1,'measuring':1,'we':4,'reproduction':1,'parental':1,'example.':1,'terse':1,'of':1,'here':2,'water':2,'feeding':1,'nowhere':1,'although':3,'sedentary':1,'science':2,'dry':1,'comparison':1,'enormous':1,'actual':1,'respiration':1,'branch-gripping':1,'many':12,'violence':1,'adventures':1,'generations':1,'swimming':2,'nerve':1,'striking':1,'keenness':1,'obtaining':1,'seven':1,'one':1,'learning':1,'accepting':1,'.':1,'millions':14,'life--the':2,'man--the':1,'additional':1,'her':2,'their':2,'race-history':1,'there':8,'copies':2,'long':2,'by':1,'whom':1,'much':1,'motility':1,'themselves':1,'analysing':3,'fourteen':1,'hearing.':1,'more':6,'free':1,'exploring':1,'excavating':2,'himself':1,'north':1,'that':4,'ages':3,'releasing':1,'instance.':1,'about':1,'it':29,'carrying':1,'observations':1,'chasing':1,'coal--dissipation':1,'considerable':1,'it--radium.':1,'plants':1,'keeping':1,'animals':1,'thirty':1,'these':4,'us.':1,'access':1,'generating':1,'sifting':2,'life--water':1,'project':1,'while':1,'future':1,'midday':1,'thirty-five':1,'aesthetic':1,'life.':1,'example':6,'are':1,'and':1,'bearing':1,'amenity':1,'almost':1,'alongside':1,'mind':1,'life':6,'avoiding':1,'an':6,'as':2,'his':1,'evening':1,'something':2,'in':5,'counting':2,'any':5,'if':2,'utility':2,'us':3,'climate':1,'granted':1,'when':1,'offspring':1,'how':1,'damages':1,'holding':2,'so':1,'profiting':1,'higher':2,'supersaturated':1,'unpalatability':1,'centuries':1,'food.':1,'most':1,'moving':1,'two':1,'supposing':3,'such':1,'foothold':1,'sally':1,'man':8,'a':49,'muscle':1,'natural':1,'observation':1,'professor':2,'itself':2,'coal':2,'shore':1,'engulfing':1,'five':1,'fresh':1,'the':104,'crayfish':1,'playing':1},'bottom':{'may':1,'of':1,'and':1,'than':1,'.':2},'fox':{'all':2,'plays':1,'the':1,'or':1},'individuals':{'die':1,'who':1,'are':1,'each':1},'exposition':{'to':1},'landscape':{'effects':1},'invasions':{'of':1,'there':1},'surging':{'fire.':1},'man--body':{'and':1},'monkey-ape-man':{'.':1},'palatable':{'and':3,'butterflies':1,'flesh':1},'substitutes':{'for':2},'energy':{'and':7,'all':1,'force':1,'is':16,'it':2,'an':1,'produced':2,'as':4,'are':3,'in':6,'go':1,'if':1,'by':2,'or':1,'from':2,'would':2,'come':1,'since':1,'had':3,'expressed':1,'.':18,'to':3,'is.':1,'which':10,'tends':1,'streams':1,';':2,'has':1,'energy':1,'287':1,'greater.':1,'we':2,'that':4,'may':4,'sufficient':1,'derived':1,'but':1,'cannot':2,'let':1,'such':1,'originated':1,'than':1,'nor':1,'must':1,'a':1,'brought':1,':':1,'locked':2,'like':2,'this':1,'of':40,'into':1,'later':1,'equal':1,'across':1,'will':1,'so':1,'can':1,'ineffectively':1,'the':1,'disappears':1,'could':1,'came':1,'for':1},'dental':{'troubles.':1},'unfrozen':{'at':1},'life-or-death':{'quality':1},'substituted':{'for':1},'shifting':{'of':1},'losing':{'a':1,'the':1,'its':1},'memorable':{'because':1},'joule':{'who':1},'tide-producing':{'power':1},'emits':{'when':1,'rays--the':1},'shaken':{'.':1},'restlessness':{';':1,'an':1},'predisposition':{'to':1},'opossums':{'feigning':2,'are':2},'o':{'.':3,'as':1,'there':1,'in':1},'oneness':{'of':1},'wave-length':{'of':2,'is':1,'corresponds':1},'herring-gull':{'is':1},'slightly':{'from':1,'changed':1,'developed.':1,'simplified.':1},'lamprey':{'.':1},'raised':{'to':1,'higher':1,'from':1,'in':2,'many':1},'cloud-screen.':{'illustration':1},'statements':{'concerning':1,'that':1,'might':1,'.':1},'facility':{'of':2,'in':1},'non-protrusive':{'face':1},'son':{'of':1},'beings':{'on':1,'whose':1,'in':1},'raises':{'the':1},'sow':{'broadcast':1,'and':1,'again.':1},'spores':{'and':1,'of':1},'pairs':{'of':3},'shoots':{'and':1,'from':1},'polaris':{'76':1},'fields.':{'virgil':1},'fabric':{'of':1},'wonder-horse':{'with':1},'support':{'and':3,'a':1,'life':1,'of':1,'its':1,'to':1,'the':1,'has':1,';':1},'constantly':{'driven':1,'pouring':2,'rising':1,'splitting':1,'for':1},'width':{'.':1},'grasping':{'of':1,'the':1,'lifting':1},'physicists':{'and':3,'did':1,'of':4,'who':1,'but':1,'to':1},'greatness':{'and':1},'resulted':{'from':1,'in':2},'music':{'of':1,'had':1},'telegraph':{'and':1,'cables':1},'offer':{'serious':1,'rewards':1,'was':1,'no':1},'fascination':{'about':1},'forming':{'associations':2,'what':1,'good':1,'useful':1,'these':1,'of':1,'an':1,'part':1,'in':1,'vegetable':1,'new':1,'the':2,'ordinary':1},'shoot':{'out':3},'hemisphere':{'learned':1,'throughout':1},'thickness.':{'a':1},'survive':{'douching':1,'for':1,'being':1,'when':1,'prolonged':2,'but':1,'.':1,'high':1,'without':1,'the':2},'beech':{'a':1},'statement.':{'illustration':1},'otter':{'a':1,'is':1,'one':1,'239':1,'which':1,'or':1},'week':{'four':1,'or':2,'in':1},'death--procession':{'of':1},'inside':{'and':2,'a':2,'is':1,'are':1,'have':1,'the':3},'arrow-worms':{'in':1},'devices':{'it':1,'adaptations':1,'which':1,'.':1},'lays':{'stress':1,'her':2,'many':1,'an':1,'the':2,'its':1},'masterfulness':{'of':1},'soldering':{'of':1},'palm':{'and':2,'of':1},'procyon':{'10.5':1},'cormorants':{'and':1},'150':{'to':1,'000':5},'153':{'anatomical':1},'later':{'chapter':1,'on':2,'differ':1,'on.':1,'sir':1,'section':1,'there':1,'ages':1,'.':3,'discovered':1,'to':1,'stage':3,'which':1,'in':3,'the':2,'still':1,'than':1,'christened':1,'section.':1},'proved':{'what':1,'that':2,'very':1,'of':1,'equal':1,'but':1,'.':1,'to':2,'as':1,'too':1},'157':{'side-view':1,'photo':1,'the':1,'after':1},'156':{'photo':2},'158':{'darwin':1},'as-is':{'with':1},'palm;':{'and':1},'proves':{'fatal.':1},'exist':{'on':2,'all':1,'there':1,'would':1,'since':1,'.':2,'in':4,'between':1,'apart':1},'melan':{'dr':1},'sprouts':{'kale':1},'redolent':{'of':1},'stolidity':{'gives':1},'floor':{'of':7,'.':2},'glacier':{'that':1},'negatively-electrified':{'body':1,'ones':1},'uttered':{'until':1},'flood':{'of':4,'in':1},'nestling':{'bittern':1},'beginning--whatever':{'we':1},'deep-seated':{'connection':1,'difference':1},'entomologist':{'mr':1},'irresistible':{'.':1},'superfluous':{'length':1,'twig':1},'roll':{'themselves':1,'over':1},'friar-birds':{'of':1},'thoroughgoing':{'internal':1},'palms':{'and':1},'non-moulting':{'winged':1},'teats':{'injects':1},'mariner':{'s':1},'transported':{'in':1},'irs.':{'the':1},'scale':{'on':1,'we':1,'far':1,'of':4,'is':1,'in':2,'but':1,'to':1,'each':1,'the':4},'intent':{'efforts':1},'foot-print':{'of':1},'variable':{'monitor':2,'hare':2,'as':1,'stars':3,'in':1,'new':1,'before':1,'stock':1},'cleaver':{'of':1},'commensalism':{'with':1,'eating':1,'i.e.':1,'where':1},'fastened':{'to':1,'by':1,'up':1,'on':1},'microbes':{'such':1,'invading':1,'to':1},'packets':{'one':1},'coastlines':{'.':1},'ottawa':{'by':1},'time':{'and':11,'is':3,'it':2,'as':6,'in':5,'immemorial.':1,'thought':1,'rapidly':1,'for':1,'their':1,'with':3,'since':1,'when':5,'.':7,'to':5,'onwards':1,'swift':1,';':1,'until':1,'ahead.':1,'we':2,'energy':1,'that':5,'very':1,'than':1,'however':2,'much':1,'great':1,'a':1,'they':1,'during':1,'come':1,'by':1,'nor':1,'ago':1,'wide':1,'immemorial':1,'last':1,'like':2,'showed':1,'of':11,'required':1,'reminding':1,'appearing':1,'so':1,'she':1,'were':1,'about':1,'the':12,'or':1},'adult':{'and':1,'eel':1,'life':1,'by':1,'.':2},'peacock':{'and':1,'for':1},'irrigation':{'of':1},'chain':{'of':2,'instincts':1,'.':1},'perch':{'when':1},'colour-change':{'bony':1,'is':2,'sometimes':1,'expresses':1,':':2,'occurs':1},'lawlessly':{'they':1},'activated':{'by':1},'crocodile':{'pipes':1,'is':2,'would':1},'avalanche':{'.':1},'skate':{'and':1,'places':1},'93':{'000':2},'witmer.':{'peter':1},'ebooks.':{'':1},'hold':{'a':1,'all':1,'that':1,'of':2,'it':1,'their':2,'in':1,'the':1},'rottenness':{'eaters':1},'methodically':{'onwards':1},'94':{'photo':1,'from':1},'efficiencies':{'supply':1},'209':{'a':1,'homing':1},'chequered':{'by':1,'but':1},'walking-fish':{'or':2},'separated.':{'perhaps':1},'downloading':{'copying':1},'gisbert':{'electricity':1},'navigable':{'kingdom':1},'choice':{'of':1},'92.9':{'1.00':1},'gloomy':{'prognostications':1,'gorilla.':1},'bustle':{'of':1},'fullest':{'ears':1},'right-handed':{'and':1},'exact':{'and':1,'intensity':1,'it':1,'limits':1},'minute':{'and':2,'signs':1,'tag--but':1,'unicellular':1,'planets':1,'in':1,'diamond-like':1,'surfaces':1,'living':1,'rays':1,'organisms':2,'measurements':1,'.':1,'particles':1,'molecules':1,'6':1,'fragments':1,'that':1,'crustaceans':3,'after':1,'but':1,'hand':1,'waves':1,'satellites':1,'atoms':1,'transparent':2,'animals':2,'atom':1,'traces':1,'or':1},'tear':{'into':1,'asunder':1,'them':1,'are':1},'leave':{'me':1,'them':1,'this':1,'well':1,'atoms':1,'their':1,'the':4,'open':1,'him':1,'creatures':1},'solved':{'four':2,'there':1,'it':1},'settle':{'these':1,'on':1,'down':3},'team':{'at':2},'depository':{'of':2,'the':1,';':1,'he':1},'speculation':{'and':1,'about':1,'.':3,'is':2,'that':1},'unpaying':{'boarders':1},'prevent':{'you':1},'thinkers':{'the':1,'since':1,'have':2},'occurrence':{'of':5,'.':1},'chimpanzee--and':{'it':1},'insignificant':{'compared':1,'one':1},'trails':{'a':1},'milligram':{'of':1},'gnawed':{'the':1},'roof':{'of':3},'depressions':{'of':1},'mind--even':{'in':1},'parachuting':{'animals':1,'.':1},'educate':{'the':1},'leaf-butterfly':{'kallima':1},'axes':{'follow':1,'of':1},'melt':{'in':1},'current':{'rang':1,'is':6,'intellectual':1,'through':1,'275':1,'in':2,'279':1,'seems':1,'exhibits':1,'.':4,'to':1,'is.':1,'which':1,'instead':1,'was':2,'therefore':1,'donation':1,'not':1,'with':1,'the':2,'of':3,'passing':1,'where':1},'remembered':{'that':4},'looking':{'is':1,'backwards':6,'at':3,'extraordinarily':1},'period--its':{'length':1},'falling':{'and':1,'on':1,'stone':2,'into':1,'body':1,'water':2,'weights':1,'between':1,'particles':1},'ground':{'a':1,'on':2,'what':1,'his':1,'again.':1,'would':1,'though':1,'is':1,'or':2,'when':1,'by':1,'pushed':1,'as':1,'flapping':1,'in':1,'has':1,'the':2,'.':5,'was':1,'generate':1,'he':1},'coccyx':{'at':1},'climbs':{'on':2,'the':2,'up':1},'honour':{'of':1},'mauer.':{'d-e.':1},'understanding':{'and':1,'of':1},'exceptions':{'the':1,'as':1,'that':2},'magnetism':{'and':1,'we':1,'gravitation':1,'is':3,'supposes':1,'.':1,'differs':1,'he':1},'nemesis':{'of':2},'yards':{'and':1,'a':1,'off':1},'address':{'specified':1},'alone':{'is':2,'.':4,'swamp':1,'the':1,'has':1,'by':2},'along':{'a':3,'copper':1,'many':1,'lines':1,'two':1,'an':1,'its':1,'at':1,'which':3,'certain':2,'the':15,'with':9,'by':2},'dwindling':{'counterpart':1,'relic':1,'of':1,'structure--the':1,'race':1,'relics':1,'structures':1,'resources':1,'must':1},'anchoring':{'structures':1},'momentous':{'event':1,'step':1,'.':1,'except':1,'that':1},'testings':{'.':1},'neville':{'extinct':1},'brilliant':{'workers':1,'young':1,'or':1,'early':1,'experiment':1,'photosphere':1,'failures':1,'conquest':1,'coloration':1,'redness':1},'studied':{'a':1,'the':1,'was':1,'by':1},'wherever':{'the':2,'there':1},'commonly':{'found':1,'accepted':1},'brazilian':{'forest':1},'accomplished':{'in':1,'if':1},'ineffective':{'way':1,'movements':1},'vitiated':{'air':1},'studies':{'of':1},'unification.':{'we':1},'tasks':{'of':2},'love':{'as':1,'.':1,'hunger':1},'prefer':{'to':1},'relations.':{'when':1},'betraying':{'its':1},'deep-water':{'marine':1},'sky':{'means--light':1,'means':1,'no':1,'.':2,'will':1,'to':1,'overhead':2,'at':1,'in':1,'probably':1,'where':1},'engrain':{'capacities':1},'working':{'from':1,'of':2,'into':1,'methodically':1,'against':1,'powerfully':1,'which':1,'or':1,'out':1},'mankind--steps':{'in':1},'formulated':{'the':2},'positive':{'and':7,'knowledge':2,'electricity':6,'particles':1,'charge':1,'in':1,'the':1,';':1},'-fish':{'embryo':1},'anatomical':{'distinctions':1,'proof':2,'genius.':1,'structure':1,'evidence':1},'vigour':{'and':1,'of':1,'.':1},'down-breaking':{'disruptive':1},'opposed':{'to':1},'films':{'of':2},'scope':{'to':1},'theoretical':{'basis':1},'ten-miles-wide':{'moons':1},'perishes':{'for':1},'periophthalmus':{'of':1,'common':2},'chapters--the':{'feeding':1},'afford':{'food':1,'a':1,'to':2},'apparent':{'strokes':1,'suddenness':1,'.':1,'motion':1,'to':1,'stroke':1,'motions':1,'exceptions':1,'creeping':1},'assimilation':{'exceeding':1},'validity':{'there':1},'minnows':{'and':2,'learned':1,'were':1},'appendix':{'alone':1,'at':1,'which':1},'everywhere':{'forming':1,'there':1,'like':1,'in':1},'virtue':{'of':5,'as':1},'blood.':{'as':1},'disparagement':{'tentative':1},'easiest':{'of':1},'petrel':{'the':1,'or':2,'is':1},'logos':{'which':1,'.':1},'modernised':{'types':1},'originally':{'a':2,'derived':2,'intelligent':1,'supposed':1},'rutherford':{'and':2,'sir':1,'246':1,'one':2,'christened':1},'imagination.':{'the':1,'organic':1},'moulted':{'which':1,'in':1},'life--water':{'that':1},'believes':{'that':1},'printing':{'august':1,'april':4,'may':1,'june':4,'september':1,'sept':1},'values':{'most--control':1},'slowness':{'.':1},'stature':{'and':1,'than':1,'human':1},'believed':{'not':1,'to':1,'by':2,'that':2},'admired':{'the':1},'short-limbed':{'but':1},'frogs':{'and':3,'a':1,'show':1,'may':1,'sometimes':1,'herald':1,'jumping':1,'have':1,'meet':1,'along':1},'bulkiest':{'structure':1},'parachute':{'of':1,';':1,'wing':1,'before':1},'locks':{'.':1},'one--the':{'old':1},'238':{'photo':2,'whereas':1},'239':{'photo':1},'unveiled':{'in':1,'.':1},'allowed':{'to':1,'aliens':1,'for':1,'her':1,'of':1},'evidently':{'light':1,'puzzled':1},'232':{'photo':2},'233':{'photo':4},'winter':{'and':4,'by':2,'in':1,'of':1,'within':1,'freeze':1,'scene':2,'whiteness':1,'plumage':2,'.':1,'are':1,'sets':1,'nor':1,'the':1,'has':1,'dress':1,';':1,'retreat':1},'venation':{'of':1},'chromatophores':{'and':1,'in':1},'foul':{'waterholes':1,'with':1},'protozoon':{'and':1,'has':1,'or':1,'.':1},'s.':{'fairbanks':1,'illustration':1},'elephant':{'and':2,'rhinoceros':1,'a':1,'.':1,'helping':1,'at':1,'they':1,'was':1},'northwards':{'for':1},'divides':{'and':1,'into':2,'is':1},'edinburgh':{'the':1},'snaps':{'secure':1},'explores':{'a':1},'explorer':{'which':1},'motive-force':{'in':1},'spot':{'and':1,'on':2,'23':1,'though':1,'at':1,'where':1},'convincingly':{'the':1},'muellerian':{'after':1},'date':{'living':1,'from':1,'for':1,'on':1,'of':2,'contact':1,'at':1,':':1},'such':{'ingenious':1,'and':1,'remarkable':1,'publications':1,'constituents':1,'is':5,'metals':1,'well-known':2,'contrasts':1,'as':72,'diverse':1,'are':1,'planets':1,'in':1,'speed':1,'birds':1,'enemies':1,'dense':1,'things':1,'phrases':1,'unity':1,'wonderfully':1,'way':1,'instruments':2,'if':1,'conditions':1,'important':1,'movement':1,'that':3,'rock':1,'apparent':1,'furnaces':1,'depths':1,'wave-motions':1,'races':1,'fishes':1,'cases':2,'intelligent':1,'active':1,'stage':1,'a':19,'dangers':1,'changes':1,'occasions':1,'damage.':1,'betelgeux':1,'cells':1,'motion':1,'thing':4,'states':1,'hard-and-fast':1,'temperatures':2,'time':1,'similar':1,'order':1},'behaviour--experimenting':{'learning':1},'truly':{'wonderful':3},'data':{'transcription':1,'for':1},'codes':{'that':1},'lids':{'to':1,';':1},'waggons':{'at':1},'sy':{'1':1,'2':1},'forestier':{'of':3},'varieties':{'of':1,'which':1,'altogether':1},'conscious':{'guile':1,'agent':1,'imitation':1},'naturae':{'meaning':1,'the':1},'st':{'.':2},'inhabiting':{'this':1,'the':2},'castings':{'and':1},'remoter':{'part':1},'so':{'chicks':1,'they':2,'among':1,'fond':1,'subtle':1,'still':1,'generous':1,'slow':1,'young':1,'late':1,'to':3,'differently':1,'rich':1,'he':1,'clouded':1,'do':2,'good':1,'far':14,'safe':1,'apt':1,'closely':1,'vast':2,'easily':1,'like':2,'keenly':1,'shaped':1,'forth':3,'large':1,'stupid':1,'she':1,'small':2,'where':1,'simple.':1,'often':1,'attenuated':1,'are':1,'helpless':1,'pronounced':1,'for':1,'restricted':1,'below':1,'does':1,';':1,'numerous':1,'common':2,'we':6,'recently':1,'inextricably':1,'completely':1,'rapid':1,'strong':1,'by':1,'momentous':1,'gained':1,'on':16,'great':3,'many':7,'sensitive':1,'rudely':1,'striking':1,'powerful':1,'marked':2,'one':1,'long':3,'quickly':1,'readily':1,'fast':1,'from':1,'there':4,'sunlight':1,'.':3,'much':15,'clever':3,'that':43,'forming':1,'minute':1,'motionless':1,'mounted':1,'inconspicuous':1,'wide':1,'arranged':1,'this':1,'up':1,'will':1,'while':1,'obvious':1,'of':1,'similar':1,'bright--the':1,'is':3,'it':8,'an':1,'effectively':1,'as':6,'in':4,'clearly':1,'relatively':1,'proceeds':1,'very':3,'hot':1,'absorbed':1,'instead':1,'firmly':1,'watery':1,'may':1,'important':1,'conspicuous':1,'a':2,'short':1,'crowded':1,'clear':1,'well':1,'near':2,'deeply':1,'species':1,'fresh':1,'the':8},'sc':{'the':1},'mud-flats':{';':1},'pulled':{'.':1,'down':1,'twice':1,'at':1,'the':3,'by':4},'outflowing':{'network':2},'unsolicited':{'donations':1},'lighter':{'and':1,'materials':2,'in':1,'atomic':2,'.':1},'differences':{'separating':1,'of':3,'in':3,'between':2},'below.':{'1.f.':1,'illustration':2,'1.c':1},'copious':{'supply':1},'course':{'and':1,'associated':1,'is':1,'it':2,'an':1,'are':1,'in':1,'confirms':1,'her':1,'unknown':1,'there':2,'been':1,'to':2,'only':1,'5':1,'easy':1,'has':1,'be':2,'we':3,'cannot':1,'not':1,'with':1,'by':1,'he':2,'a':2,'for':3,'of':24,'the':2},'experiments':{'suggested':1,'towards':1,'proved':1,'chiefly':1,'showed':1,'that':1,'of':5,'in':4,'enabled':1,'.':4,'indicate':1,'without':1,'have':1,'which':1,'usually':1,'checked':1,'with':2},'frequents':{'two':1},'insurgence':{'and':2,'of':2},'tendency':{'to':11,'that':1,'among':1,'by':1,'of':2},'solitary':{'bit':1,'or':1},'limbs':{'is':1,'to':2,'at':1,';':1,'with':1,'or':1},'derive':{'their':1,'from':1},'yawning':{'in':2},'thumb':{'and':5,'th':1},'did.':{'looking':1},'hot':{'and':2,'gaseous':1,'for':1,'gas':1,'when':1,'but':1,'.':2,'as':1,'weather':1,'earth':1,'cinder':1,'or':1,'bodies':1},'decreases':{'.':1},'attraction':{'produces':1,'of':1,'is':1,'.':1,'can':1,'between':2},'creations':{'of':1,'.':1},'dwarfs':{'.':1},'constitutes':{'matter':2,'one':2},'instantly':{'fly':1},'conveying':{'it':1},'thereby':{'buoyed':1,'escapes':1},'earth--the':{'earth-knot':1},'youth.':{'sec':1},'experiment.':{'we':1},'indigenous':{'wild':2},'records':{'of':2,'the':1,'or':1,'.':1},'year.':{'in':1},'overpowering':{'and':1,'its':1},'water-shrew.':{'freshwater':1},'sorted':{'out':2},'twilight':{'by':1,'no':1},'runners':{'that':1},'one-seventh':{'and':1},'find.':{'fresh':1},'creation.':{'the':1},'establishing':{'itself':1,'or':1,'associations.':1},'veins':{'on':1,'of':1},'instability':{'and':1},'eighty-seven--and':{'that':1},'quarter':{'of':4,'days':2},'habitat-zones':{'and':1},'limb.':{'it':1},'turtle':{'found':1,'the':1,'that':1,'which':1,'of':1},'square':{'of':1,'.':1,'miles':2,'inch':2,'our':1,'the':1},'retrieve':{'its':1,'her':1},'receipt':{'of':1,'that':1},'parachutists--':{'flying':1},'prisms':{'the':1,'are':1},'woodcraft':{'the':1},'owing':{'to':4,'in':1},'entering':{'a':1,'the':4,'into':1},'beetle':{'running':1,'which':4},'instinct--the':{'mind':1},'neighbourhood':{'of':1},'crowding':{'there':1},'river-tortoises':{'which':1},'abide':{'by':1},'collisions':{'.':1},'contained':{'good':1,'meat':1,'in':4},'protections':{'against':1},'washington.':{'illustration':1},'suggesting':{'that':2},'granites':{'while':1},'ascendant':{'and':1},'soap-bubble':{'.':2},'siege':{'are':1},'million':{'millions':1,'square':1,'million':2,'stars.':1,'volts':1,'is':1,'trillion':1,'atoms':1,'meteorites':1,'miles':3,'electrons':1,'stars':1,'in':1,'horsepower':1,'250':1,'years':9,'.':1,'times':6},'envelop':{'the':1},'possibility':{'of':12,'is':1,'that':2,'in':1},'quite':{'uninterested':1,'certain':5,'direct':1,'comfortable':1,'as':1,'clever':1,'at':1,'impossible':1,'extinct':1,'indifferent':1,'readily':1,'different':5,'emancipated':1,'artificial':1,'difficult':1,'separated':1,'independent':1,'sure':2,'possible':2,'lively.':1,'invisible':1,'apart':3,'a':2,'easily':1,'novel':1,'clear':1,'so':3,'fundamental':1,'obscure':1,'away':1},'disintegrates':{'generates':1},'complicated':{'and':2,'elements':1,'than':1,'convolutions.':1,'atoms':1,'to':1,'atom':1,'cases':1,'wave':1,'by':1},'besides':{'even':1,'all':1,'his':1,'her':1,'turtles':1,'that':1,'this':1,'monkeys--in':1,'violent':1,'sunlight':1,'.':2,'these':1,'acting':1,'pulling':1,'struggle':1,'which':1,'instinctive':1,'the':4,'perceptual':1,'those':1},'remainder':{'of':1},'seventy':{'or':1},'vivum':{'e':1},'shores':{'and':1,'going':1,'which':1,'.':1},'training':{'given':1,'they':1,'nor':1,'.':1},'possum':{'lying':1},'tree-sloths':{'for':1,'tree-shrews':1},'undisguised':{'shore-animals':1},'ostrich':{'and':1,'with':1},'wanderers':{'.':1},'disguises':{'which':1},'massive':{'bulk':1,'jaws':1,'lower':1,'face':1},'routes':{'became':1,'round':1},'learning.':{'vi':1,'vii':1,'illustration':1,'animal':1},'puny':{'infant':1},'toads--it':{'serves':1},'emotion':{'as':1,'is':1},'saving':{'the':2,'clauses.':1},'symmetry':{'of':1,'is':1,'.':1,'well':1,'must':1},'serpent':{';':1},'spoken':{'of':1,'language':1},'one':{'over':1,'atom':3,'not':1,'mile':3,'whose':1,'cut':1,'group':1,'championed':1,'except':1,'should':3,'to':2,'primordial':2,'main':1,'might':2,'resting-place':1,'digit':1,'animal':1,'big':1,'colour--the':2,'answer':1,'year.':1,'cannot':1,'half':1,'foot':1,'rotation':2,'day':4,'three-hundredth':1,'reality--the':1,'name':1,'magnet':1,'fitness':1,'served':1,'side':5,'kernel':1,'revolution':1,'telescope':1,'second':1,'martian':1,'year':1,'close':1,'thinks':2,'living':1,'for':1,'disease':1,'time.':1,'discovers':1,'above':1,'example':1,'consisting':1,'body':6,'we':1,'state':1,'million':2,'here':1,'objects':1,'illustration':1,'key':1,'put':1,'sadly':1,'by':1,'momentous':1,'extreme':1,'on':4,'substance':1,'asks':1,'of':101,'local':1,'thing':3,'s':2,'place':3,'or':1,'comes':1,'family':1,'embodiment':2,'another':16,'comprises':1,'pulls':1,'cloud':1,'from':3,'would':3,'hundred-thousandth':1,'.':7,'water-shed':1,'crab':1,'half-hour':1,'was':2,'toe':1,'direction':1,'knows':2,'form':1,'that':3,'successful':1,'thousand':2,'but':1,'another.':1,'manifestation':1,'hopes':1,'line':1,'with':3,'must':1,'kind':3,'has':1,'type':1,'as':1,'will':1,'near':1,'obvious':1,'can':6,'country':1,'piece':1,'remembers':1,'and':8,'pound':3,'stream':2,'is':8,'hardly':1,'say':1,'way':2,'at':2,'in':3,'helium':1,'globe.':1,'end':6,'parish':1,'food-plant':1,'other':1,'which':3,'inch':1,'physical':1,'week':1,'snail':1,'may':1,'after':1,'molecule':1,'hand':2,'plane':3,'such':1,'class':2,'man':2,'planet':1,'owns':1,'colour':3,'electron':1,'element':1,'more':1,'time':5,'the':1,'lined':1,'egg':1,'order':1},'spanish':{'don.':1},'open':{'pipe':1,'sea':25,'jaws':1,'waters':2,'there':1,'up':1,'one':1,'water':1,'atlantic':1,'sea.':1,'doors':1,'sea--the':1,'the':1,'gateways':1},'city':{'ut':1,'like':1},'bite':{'of':1,'at':1},'indicate':{'a':2,'the':4,'that':1,'first':1,'an':1},'2':{'and':4,'among':1,'show':1,'gradual':1,'in':1,'it':1,'chromosomes.':3,'feet':1,'tons':1,'jupiter':2,'escape':1,'paternal':1,'egg':1,'nebulae':1,'factors':1,'physiological':1,'.':11,'0':1,'3':1,'holding':1,'newly':1,'500':3,'we':2,'maternal':1,'inches':2,'respectively':1,'instinctive':1,'canals':1,'with':1,'by':1,'a':1,'represents':1,'of':3,'the':13,'changes':1},'vapoury':{'tail':1},'stuffed':{'their':1},'bits':{'.':1},'lingering':{'influence':1,'here':1},'vapours':{'and':1,'that':1,'of':1,'whirling':1,'imaginable':1,'.':1,'above':1},'on.':{'we':1,'there':1,'illustration':1,'sec':1,'in':1,'the':3,'recent':1},'viviparous':{'the':1},'gently.':{'these':1},'proving':{'everything':1,'trying':1,'itself':1},'s.c.':{'on':1},'herds':{'extended':1},'absorbs':{'most':1,'the':2,'all':1},'photographic':{'emulsions':1,'plate':11,'negative':1},'structure.':{'differences':1,'in':1},'vapour.':{'millions':1},'meteors':{'and':2,'what':1,'showing':2,':':1,'approach':1,'or':2},'third':{'and':2,'case':1,'layer':1,'eyelid':2,'form':1,'of':3,'night':2,'rings':1,'digit':1,'haunt':1,'trial':1,'printing':1,'great':1,'have':1,'atom':1,'answer':1,'interglacial':3},'depressed':{'into':1},'himself.':{'when':1},'weapons--the':{'sea-anemone':1},'siding':{'we':1},'future':{'and':1,'for':1,'reproductive':1,'of':1,'holds':1,'.':6,'access':1,'cannot':1,'let':1,'need':1,'research':1,'generations.':1},'17-1':{'2':1},'trekking':{'to':1},'college':{'of':2,'observatory.':4},'wandering':{'about':1,'amoeboid':2,'.':1},'johnstone':{'j':1},'prospect':{'for':3,'.':1},'thousandths':{'of':1},'royalties':{'.':1,'under':1},'sac':{'beneath':1},'turned':{'towards':1,'from':1,'into':5,'round':1,'to':1,'sharply':1,'rapidly':2,'the':1,'its':1},'argument':{'supposes':1,'implies':1},'alley':{'at':1},'auroral':{'displays':1},'say':{'just':1,'is':1,'some':1,'it':2,'an':1,'brain':1,'as':1,'at':2,'in':1,'our':1,'its':1,'what':2,'for':1,'sodium':1,'much':2,'began':1,'there':3,'ignorabimus.':1,'.':2,'other':1,'therefore':1,':':1,'reflex':1,'more':4,'presently.':1,'we':2,'full':1,'that':26,'mammals':1,'here':1,'unification':1,'they':3,'half':1,'by':1,'a':1,'about':1,'like':1,'of':5,'enthusiastic':1,'according':1,'without':1,'ignoramus':1,'the':9},'buried':{'and':1,'eggs':1,'his':1,'egg':1,'alive':1},'horsepower':{'.':1},'1':{'and':3,'testing':1,'it':2,'an':1,'100th':1,'drawings':1,'in':1,'before':2,'67':2,'25':1,'giant':1,'for':1,'no':1,'sun':1,'except':1,'.':10,'1':1,'to':1,'340':1,'mars':1,'progress':1,'we':1,'300':1,'dam':1,'67000':1,'but':1,'000':2,'125':2,'367':1,'drought':1,'20417':1,'with':1,'by':1,'evolution':1,'1800':1,'of':4,'35':1,'1845':1,'the':12,'two':1},'sap':{'reminding':1,'and':1,'which':1},'saw':{'and':1,'a':1,'all':1,'that':1,'may':1,'is':1,'earlier':1,'about':2,'heard':1,'combine':1,'in':2,'the':1,'has':1,'was':1},'1903.':{'illustration':1},'law.':{'if':1},'unsuitable':{'and':1,'pools':1},'downwards':{'on':1,'along':1,'at':1},'aside':{'to':1,'conventional':1,'only':1},'zoo':{'with':1,'were':1},'note':{'that':1,'of':2,'is':2,'its':1,'how':2,'the':9,'still':1,'by':1},'take':{'frogs':1,'it':1,'an':3,'as':1,'in':1,'our':2,'its':1,'what':1,'from':1,'rather':1,'long':1,'1':1,'to':2,'much':1,'400':1,'place.':1,'photographs':1,'centuries':1,'advantage':1,'between':2,'about':1,'leaps':1,'one':1,'a':6,'great':2,'light':1,'up':1,'us':1,'place':1,'five':1,'the':10,'root':2,'50':1},'fruit-fly':{'drosophila':1},'wanting':{'of':1},'powers--man':{'still':2},'butterfly':{'kallima':2,'showed':1,'which':1,'an':1},'scents.':{'the':1},'hunt':{'insects':1,'from':1},'wilson.':{'peripatus':1,'rock':1},'opposite':{'pans':1,'direction':2,'electric':1,'ways':1,'of':1,'ends':1,'side':2,'picture.':1,'directions':3,'page':1},'knew':{'to':1,'what':1,'.':1,'but':1,'less':1},'molecule':{'of':4,'is':2,'contains':1,'as':1,'every':1,'therefore':1,':':1,'with':1},'talk':{'of':1},'detect':{'and':2,'a':2,'them':1,'less':1,'this':1,'as':2,'such':1,'the':2},'printed':{'cards':1,'on':2,';':1,'and':1,'editions':1},'remarks':{'of':1},'inserted':{'nuts':1},'pages':{'for':1},'adaptability':{'of':1},'average':{'distance':1,'would':1,'level':1,'of':1,'men':1,'molecule':1,'height':1,'depth':1,'5':1,'human':1,'estimate':1,'organism':1},'drive':{'electric':1},'crowd--we':{'cannot':1},'unabated':{'to':1},'messier':{'31':2},'atlantic':{'and':1,'cod-banks':1,'some':1,'.':1,'crowds':1,'overcome':1},'salt':{'and':1,'did':1,'of':1,'lake':2,'.':1,'water':2,'projects':1},'laws':{'and':1,'of':5,'alone':1,'regulating':1,'in':1},'walking':{'and':2,'on':1,'wood':1,'powers':2,'movements':1},'pencilled':{'above.':1},'definite':{'direction':2,'constant':1,'periodic':1,'positions':1,'function--we':1,'answers':1,'possibilities':1,'entities':1,'step':1,'race':1,'figures':1,'nervous':1,'learning':2,'mammals':2,'routes':1,'position':2,'concentric':1,'type':1,'order':1,'bronze':1},'imagines':{'when':1},'friction':{'and':1,'on':1,'.':1,'when':1,'of':1},'far-reaching':{'importance':1,'influences.':1,'with':1,'discoveries':1,'consequences':2},'bright':{'star':1,'globe':1,'lines':5,'central':1,'white':1,'cloudlets':1,'image':1},'fiord':{'estuary':1},'scarce':{'as':1,'multiplying':1},'imagined':{'the':1,'entity':1},'beetles':{'and':1},'slot':{'and':1,'of':1},'colony-making':{'protozoon':1},'slow':{'and':1,'like':1,'boiling':1,'one':1,'down':2,'to':3,'as':1,'vibrations':1,'although':1,'changes':1},'representation':{'of':6,'to-day':1},'gravers':{'and':1},'fox-terrier':{'turned':1},'liberation':{'and':1},'going':{'on':17,'appearing':1,'that':1,'back':5,'one':2,'to':4,'through':1,'farther':1,'on.':8,'beyond':1,'outward':1,'concern':1},'uppermost':{'portion':1,'layer':1},'helmholtz':{'lord':1},'dispute':{'as':1,'the':1},'evolution--but':{'even':1},'hindmost':{'pair':1},'guarded':{'against':1},'tail.':{'now':1,'it':1,'but':1,'man':1},'infallibly':{'between':1},'genera':{'and':1},'eel-fare':{'includes':1},'freezing':{'.':1,'point':1},'theory--had':{'a':1},'also--protection':{'for':1},'clearest':{'realities':1},'shallow-water':{'species':1},'keenly':{'aware':1},'parasitic':{'sporozoa':1,'death':1},'toads':{'newts':1,'and':2,'jump':1,'sometimes':1},'absurdly':{'small':1},'liable':{'to':3,'such':1},'where':{'and':1,'copper':1,'words':1,'it':10,'deep':1,'an':1,'sea':1,'any':1,'dense':1,'no':1,'there':5,'its':1,'their':1,'does':3,'routine':1,'you':1,'alertness':1,'we':3,'very':1,'they':2,'alone':1,'instinctive':1,'a':3,'this':2,'these':1,'each':1,'the':24},'sake--imitation--the':{'mind':1},'vision':{'and':1,'is':3,'holds':1,'than':1,'in':1},'press.':{'comparative':1},'proof--man':{'s':1},'attenuated':{'that':1},'electrons--and':{'the':1},'reign.':{'they':1},'silurian':{'and':1,'the':1,'when':1,'period':2,'rocks':1},'up':{'and':8,'individually':1,'intelligence':2,'into':14,'it':1,'general':1,'light-waves':1,'at':1,'questions':1,'in':10,'impressions':1,'rivulets':1,'the':26,'any':1,'living':1,'what':1,'from':2,'for':2,'how':1,'.':5,'to':8,'between':1,'estuaries':1,'new':1,'energy':1,'his':1,'an':1,'substances':1,'our':2,'nonproprietary':1,'trees':1,'but':1,'such':1,'one':1,'with':6,'by':10,'a':9,'on':5,'organic':1,'these':1,'light':1,'leaves':1,'carbon':3,'so':2,'of':9,'again':2,'everything':1,'photosynthesis':1,'or':4},'distended.':{'eventually':1},'impressions':{'go':1,'of':1,'.':1},'hastened':{'the':1},'830':{'000':2},'inequalities':{'of':1,'in':1},'compounds':{'to':1,'from':1,'activated':1,'like':1,'out':1},'representatives':{'of':3,'sometimes':1,'had':1,'except':1,'.':1},'under-skin':{'or':1,'.':1},'secondaries':{'are':1},'dormitory':{'instead':1},'--which':{'have':1},'moons':{'we':1,'of':4,'four':1,'to':1,'which':2,'certain':1,'round':1},'affecting':{'it':1,'nerve-cells':1},'man.':{'a':1,'on':1,'animals':1,'pariasaurus':1,'4':1,'triceratops':1,'it':1,'deperet':1,'according':1,'1':1,'illustration':1,'such':1,'eocene':1,'man':1},'volvox':{'a':1,'69':1,'the':1,'is':1,'.':1},'fir':{'cones':1},'spectroscopy':{'is':1},'vertical':{'line':1,'bars':1},'screen':{'and':1,'we':1,'for':1,'means':1,'where':1,'is':1,'.':4,'through':1,'which':1,'producing':1,'make':1,'glowed':1},'dome':{'like':1,'.':1},'ancestors--a':{'wolf':1},'big-brain':{'type':4},'proterozoic':{'ages':1,'eras':1,'era':1},'jets':{'of':2,'or':1},'engravings.':{'factors':1},'spark':{'on':1,'this':1,'.':1,'271':1,'274':1,'consists':1,'an':1,'or':1},'well-protected':{'pupa':1},'concentrated':{'upon':2},'circumference':{'so':1,'.':1},'many':{'insects':1,'instincts':1,'years':1,'bivalves':1,'experiments':2,'facts':1,'contributions':1,'birds':4,'young':2,'forms':4,'parts':2,'anticipations':1,'reptiles':2,'inventions':1,'thousands':2,'which':1,'tenses':1,'very':1,'crustaceans':1,'portions':1,'more.':1,'far-reaching':1,'minute':1,'fossils':1,'nerve-endings':1,'countries':1,'corners':1,'miles':2,'brownish':1,'small':4,'freshwater':1,'generations':1,'people':1,'animals':9,'fish':1,'parasites':1,'individual':1,'universes':2,'hundredfold':1,'creatures':2,'oceanic':1,'for':1,'ways':1,'migrations':1,'new':1,'open-sea':1,'levels--the':1,'we':1,'were':2,'hours':1,'broken':1,'directions.':1,'yards':1,'directions':3,'about':1,'brilliant':1,'of':23,'months':2,'haunts':1,'times':3,'shore-animals':2,'tree-loving':1,'already':1,'useful':1,'annelids':1,'another':1,'fees':1,'protozoa':2,'establish':1,'millions':5,'ancient':1,'would':1,'.':1,'tropical':1,'stars':2,'dangers':1,'more':1,'acquisitions':2,'that':2,'mammals':3,'regard':1,'sciences.':1,'amphibians':1,'cases':9,'an':1,'plants':1,'prehistoric':1,'unsegmented':1,'places':1,'apples':1,'planes':1,'drops':1,'similar':2,'and':2,'likewise':1,'days':3,'have':1,'domesticated':1,'occur':1,'different':5,'things':1,'shore':1,'astronomers':4,'other':9,'doors':1,'units':1,'mysteries':1,'kinds':1,'thoroughgoing':1,'eggs':1,'swiftly':1,'problems':1,'important':1,'waves':1,'fishes':1,'types':2,'a':3,'land':1,'minutes':1,'sometimes':1,'peculiarities':1,'electrons':1,'nuclei':1},'moon.':{'illustration':1},'estimates.':{'the':1},'thickly':{'peopled':2},'s':{'chicks':1,'atmosphere':3,'skeleton':1,'sentence':1,'stinging-cells':1,'instincts':1,'sheltering':1,'brain':3,'snapping-blades':1,'hairs--an':1,'skin':2,'chicken':2,'visceral':1,'principal':1,'web':3,'anvil':1,'interesting':1,'instruction':1,'monkeys':1,'hidden':1,'real':1,'beginnings.':1,'return':1,'orbit':1,'arboreal':3,'big':1,'theory--had':1,'famous':2,'shell--there':1,'sons':2,'moods':1,'saying':1,'hands':1,'press':7,'world':1,'rotation':4,'continued':1,'day':4,'runs':1,'establishment':1,'cry':1,'solution':1,'experiments':1,'activity':1,'sake--imitation--the':1,'ceaseless':1,'mental':2,'energy':2,'mongoose':1,'notice':1,'past':1,'affiliation':1,'books':1,'mighty':1,'year':1,'laboratory':1,'indirect':1,'ascent':2,'arm':1,'shining':1,'pedigree':2,'apparatus':2,'nebula':6,'crust':4,'finger':1,'rational':1,';':2,'eggs':1,'discovery':1,'body':8,'prerogative.':1,'theory':2,'leg':1,'beak-like':1,'men':4,'behaviour':1,'magnetism':2,'compass':1,'dwindling':1,'tide-producing':1,'intense':1,'advance':2,'great':2,'derivation':1,'side':1,'croaking-sacs':1,'patagium':1,'action':1,'history':2,'frequent':1,'skill':1,'point':4,'feelings':1,'inquisitive':1,'long':2,'beak':2,'theory.':1,'story':1,'sake':1,'initial':1,'frog':1,'.':26,'dropping':1,'pedigree--man':1,'structure':1,'danger-note':1,'white':1,'store':1,'mundane':1,'eyes':2,'hard':1,'flight':1,'relationship':4,'cluck':1,'training':1,'shard':1,'bulk':1,'heat':2,'surface':19,'ear':1,'food-canal':1,'essays':1,'he':1,'pull':2,'wise':1,'skull':3,'solid':2,'gravitational':1,'bill':12,'fly-trap':1,'light':4,'propeller':1,'head.':1,'earth.':1,'ein':1,'and':1,'words:':1,'discovery.':1,'ingenuity':1,'horns':1,'escape':1,'mind':3,'head':3,'apartness':1,'dog':1,'shell':1,'at':1,'cathedral':1,'wonderful':1,'clothing':1,'laws.':1,'movements':2,'cage':1,'rays':5,'maxim:':1,'diurnal':1,'inheritance':1,'heat.':1,'forceps':1,'blood-relationship':1,'food':1,'strange':1,'animal':1,'hedgehog-like':1,'predestined':1,'civilisation':1,'composition':1,'conclusion':1,'vestigial':1,'nest':1,'philosophy':1,'reach':1,'hand':1,'ancestors':4,'mouth':1,'device':1,'does;':1,'sand-grouse':1,'descent':3,'mysteries':2,'remote':1,'expert':1,'foot':1,'undeniable':1,'age':2,'handiness.':1,'coastlines':1,'star-book':1,'mass':1,'gill-plates.':1,'the':2,'wing':4,'goals':1},'mane':{'reaching':1},'expended':{'their':1},'flipper':{'of':3},'expression':{'of':6,'is':1,'as':1,'are':1,'familiar':1,'instinctive':1,'has':1},'moon;':{'it':1},'riddle':{'that':1},'stoats':{'hares':1},'ants':{'and':5,'beneath':1,'bees':3,'are':1,'hive':1},'air-breathing':{'insects':1,'arthropods':3,'amphibians':1,'invertebrates':1},'boar':{'and':1,'below':1,'coloured':1,'were':1},'extinct':{'and':2,'reptile':2,'apes':1,'animals':2,'volcanoes':1,'fish':1,'flying':3,'leaving':1,'monsters':1,'neanderthal':1,'reptiles':1,'types--':1,'race':1,'in':1,'not':1,'vegetarian':2,'type':1,'or':1,'pterodactyls':1,'flightless':2},'twig':{'and':1,'breaks':1,'for':1},'want.':{'illustration':1},'fitful':{'gleams':2},'collides':{'with':1},'cetaceans':{'some':1},'stretch':{'of':1,'vast':1},'mounting':{'of':1},'lettering':{'to':1},'diurnal':{'tint.':1,'variation':1},'collided':{'with':1},'combined':{'to':1,'operation':1},'finger-tip':{'they':1},'reflective':{'one':1},'covering':{'and':1,'many':1,'is':1,'of':2},'recaptures':{'it':1},'day--a':{'long':1},'enable':{'their':1,'the':1,'us':4},'gist':{'of':2},'lakelets':{'of':1},'thousand':{'and':1,'or':2,'trillion':2,'of':1,'cells':2,'million':2,'together':1,'years':10,'millions':1,'miles':3,'.':1,'steep':1,'thousand':1,'generations':1,'times':6},'formed':{'a':1,'then':1,'has':1,'from':3,'float':1,'young':1,'it':1,'solids':1,'at':1,'sandstones':1,'in':2,'the':4,'.':2,'by':2},'haunt':{'forever':1,'for':1,'of':8,'some':1,'stops':1,'includes':1,'so':1,'which':1,'has':1},'photos':{':':5},'indents':{'the':1},'observe':{'these':1,'and':1,'in':1},'infusorians':{'to':1,'like':1},'diffuse':{'and':1,'gas':1},'co-ordination':{'of':1},'prominence':{'to':1,'by':1,'would':1},'intimately':{'associated':1,'bound':1},'dints':{'impressed':1,'have':1},'confidently':{'say':1},'situation':{'.':5,'for':1,'in':1},'region':{'smaller':1,'of':5,'is':1,'when':1,'to':1,'at':1,'known':1,'the':4,'called':1,'south':2},'girth':{'.':1},'concatenation':{'of':1},'birth.':{'enough':1},'regularity':{'of':1},'rock-cod':{'requires':1},'ascii':{'start':1,'or':2},'adopted.':{'the':1},'binary':{'compressed':1},'beginning.':{'in':1},'shuts':{'on':1},'preparatory':{'to':1},'perpetually':{'giving':1},'coconuts':{'is':1},'emulsions':{'can':1},'way.':{'this':1,'bearing':1},'wires':{'as':1,'are':1,'in':1},'sickness':{'.':5},'edges':{'and':1,'of':4},'advertisement':{'impressing':2},'six':{'meant':1,'feet':1,'great':1,'main':1,'inches':1,'very':1,'thousand':1,'months':1,'quite':1,'colours':1,'to':2,'miles':1,'greatly':1,'years':1,'weeks':1,'stages':2},'volcanoes':{'.':1},'tentacle':{'touches':1},'know':{'and':2,'almost':1,'indeed':1,'is':1,'it':4,'not':1,'as':2,'are':1,'in':1,'if':1,'fire':1,'what':1,'from':1,'their':1,'when':3,'gases':1,'.':3,'to':2,'outside':1,';':1,'be':1,'that':17,'very':1,'but':1,'nothing':1,'now':2,'with':1,'a':1,'also':1,'about':1,'to-day':2,'whether':3,'of':4,'no':1,'definitely':2,'far':1,'life.':1,'the':5,'nothing.':1,'something':1},'peculiarities':{'and':1,'of':5,'.':1,'say':1,'in':2,'such':1},'costs':{'and':2},'engulfing':{'and':1,'large':1,'in':1},'unimagined':{'.':1},'persistently':{'used':1,'resorted':1},'216':{'photo':2},'summer':{'and':2,'full':1,'darkness':1,'of':1,'green-flies':1,'months':1,'scene':2,'day':1,'plumage':1,'s':1,'does':1,'at':1,'weather.':1,'than':1},'followed.':{'illustration':1},'manifold':{'significance.':1,'influence':1},'213':{'photo':2},'being':{'already':1,'closely':1,'swept':2,'blown':1,'unpalatable':1,'able':1,'moved':1,'investigated.':1,'an':3,'held':1,'as':1,'set':2,'dried':2,'human':1,'nonplussed':1,'swallowed':2,'any':1,'given':1,'built':1,'to':1,'washed':2,'due':1,'continually':1,'liberated':1,'outside':1,'incessantly':1,'deposited':1,'surveyed':1,'endowed':1,'polygamous':1,'more':2,'a':1,'affected':1,'evolved':1,'that':3,'very':1,'mammals':1,'formed':1,'what':1,'driven':1,'imperfectly':1,'nourished':1,'dissipated':1,'on':1,'than':1,'regrown':1,'thrown':1,'begins':2,'devoured':1,'indivisible':1,'embryos':1,'frozen':2,'consumed':1,'utilised':1,'replaced':1,'greatly':1,'hurled':1,'each':1,'quick':1,'the':3,'left':1,'reinforced':1},'drone-fly':{'is':1},'slime':{'from':1},'rest':{'and':1,'repair':1,'assured':1,'of':5,'is':1,'belong':1,'.':3,'till':1,'through':1,'in':1},'steamer':{'and':1},'crust.':{'on':1},'potentiality':{'of':1},'aspect.':{'illustration':1},'water-basins':{'or':1},'ligula':{'or':1},'weekly':{'nature':1},'occasional':{'light':1,'flash':1,'traces':1},'tactility':{'.':2},'geological':{'clock':1,'time-table':1,'estimates.':1,'tree':1,'middle':1,'periods':1,'time':1,'past.':1},'silver':{'on':1,'mirror':1},'instrument':{'and':1,'again':1,'used':2,'for':3,'that':1,'of':3,'however':1,'to':1,'which':2,'in':1,'the':2,'has':1,'ever':1,'gets':1},'formative':{'times':1},'continuation':{'of':2},'prominently':{'whenever':1,'displaying':1},'form-resemblance.':{'illustration':1},'skies':{'.':1},'aspects':{'of':3,'matter':1,'folk':1,'.':1},'around':{'sun':1,'the':8,'its':1,'us':1,'an':2},'decomposed':{'into':1},'dart':{'to':1},'dark':{'sprawling':1,'and':1,'absorbing':1,'spots--they':1,'in':1,'silent':1,'nebula':1,'moorland':1,'spots':1,'forms':1,'to':1,'only':1,'parts':1,'stars':1,';':1,'body':1,'bands':2,'water':1,'heat':1,'lines.':1,'markings':1,'areas':1,'varieties':1,'corners':1,'region':1,'fringe':1,'lines':3,'matter':1,'of':1},'bandage':{'which':1},'vacuum':{'tube--the':1,'tube':7,'tubes':1,'.':2},'world':{'and':2,'would':1,'new.':1,'throwing':1,'is':4,'within':1,'an':1,'as':1,'are':2,'in':2,'provokes':1,'if':1,'wondered':1,'internat':1,'when':1,'.':13,'without':1,'too':1,'which':2,';':2,'was':1,'over':1,'then':1,'knows':1,'means':1,'becomes':1,'who':1,'but':2,'than':2,'like':1,'a':1,'about':1,'for':2,'of':7,'professor':1,'monkeys':3,'will':1,'s':1,'became':1,'can':2,'always':1,'biological':1,'the':2,'entered':1,'settled':1,'came':1,'once':1},'breakage':{'plane':1},'vague':{'idea':1},'dare':{'not':1,'say':1,'one':1},'sensational':{'stories':1,'estimates':1,'discoveries':1},'60':{'spotted':1,'000':2,'reproduced':1,'days':1},'fossils':{'we':1,'e.g':1,'of':1,'when':1,'but':1,'coloured':1,'.':1,'in':1,'binding':1,'many':1,'by':1},'pole':{'to':2,';':1,'of':5,'was':1,'in':1},'claw':{'it':1},'stationary':{'.':1},'clap':{'of':1},'65':{'photo':1,'reproduced':1},'satisfactory':{'and':1,'fossils':1,'or':1,'way':1},'fives':{'or':1},'wattle':{'or':1},'law--senses':{'of':1},'lobster':{'swimming':1},'all-pervading':{'similitude':2},'diving':{'in':1,'flying':1,'capacity':1,'but':1,'suit':1},'racial':{'evolution':2,'profit.':1,'ventures':1,'strains':1,'vigour':1,'change':2,'qualities':1,'process':1,'qualities--notably':1},'armoured':{'fishes':1},'thinks':{'of':1,'the':1,'that':3,'less':1},'wrongly':{'call':1,'shows':1},'dissociated':{'and':1},'dimensions':{'11':1,'this':1,'.':2,'cannot':1,'in':1,'than':1},'cavity':{'the':2},'memories':{'and':1,'of':3},'noon':{'of':1},'tree-snake':{'is':1},'nook':{'of':1},'favourite':{'answer':1},'semotilus':{'atromaculatus':2},'918':{'miles':1},'happened':{'to':2,'over':1,'later':1,'in':2,'one':1},'levels--the':{'tendency':1},'transmutation':{'of':1,'brighten':1,'would':2},'refer':{'to':3,'throughout':1},'scientific':{'glories':1,'methods':1,'habit':2,'mind':2,'imagination':1,'caution':1,'weekly':1,'instruments.':1,'ideas':6,'way':1,'description':1,'description.':1,'american.':1,'men':2,'problems':1,'hypothesis':1,'statement.':1,'spirit':1,'man':1,'acquisitions':1,'definition':1,'study':1,'american':1,'way.':1,'spectator':1,'position':1},'power':{'used':1,'from':1,'stations':1,'of':37,'stations.':1,'that':1,'to':1,'enough':1,'in':1,'or':1,'is':2},'intimate':{'physiological':1,'part':1,'partnership':3,'physiology':1},'sprung':{'from':1},'precious.':{'illustration':1},'endogamy':{'tending':1},'five.':{'if':1},'lens':{'and':2,'weighs':1,'of':1,'is':1,'two':1,'.':3,'four':1,'near':1,'however':1,'at':2,'resolved':1,';':1,'called':1},'stone':{'implements':3,'and':1,'neolithic':1,'curlews':1,'generates':1,'hunting':1,'resting':1,'of':1,'age':3,'implements--knives':1,'until':1,'to':1,'running':1,'.':1,'into':1,'living':1,'the':2,'trying':1,'its':1,'or':1,'age.':3},'origins':{'are':1},'swarms':{'of':1},'industry':{'and':1},'slender':{'stream':1},'side':{'and':5,'for':1,'tells':1,'of':19,'actions':1,'.':8,'to':9,'below':1,'so':2,'are':1,'veins':1,';':1,'must':1,'was':2,'by':1,'view':1},'practicable':{'to':1},'act':{'though':1,'of':2,'was':1,'against':1,'as':2,'together':1,'experimentally':1,'instinctively':1,'with':1},'composed--':{'one':1},'johnston':{'in':1},'--brushes':{'off':1},'puzzle-box':{'at':1},'diversely':{'adapted':1},'fundraising':{'.':1},'burning':{'and':1,'coal':1,'wood':1,'of':1},'image':{'and':1,'of':2,'.':1},'electricity.':{'what':1,'4':1},'surinam':{'toad':4},'carey':{'s':2},'mic.':{'sci.':1},'sneering':{'curl':1},'wave-movements':{'on':1},'lively':{'cheerful':1,'and':1,'commotion':1,'.':1},'wade':{'cautiously':1},'excrementitious':{'material':1},'snakes':{'are':3,'.':1},'tropical':{'shores':1,'africa':2},'repertory.':{'from':1,'according':1},'her':{'and':1,'silken':1,'family':2,'supply':1,'almost':1,'advantage.':1,'hand.':1,'mind':1,'hindmost':1,'young':1,'chin':1,'in':1,'arm':1,'web':1,'ancestors':1,'two':1,'stealthy':1,'short':1,'to':2,'tail':1,'eggs':6,'body':2,'life':1,'maternal':1,'offer':1,'nest':1,'attention':1,'back':2,'behaviour':1,'nimble':1,'mouth-parts':1,'intent':1,'beak':1,'instinctive':1,'teacher':2,'clumps':1,'a':1,'perceptions':1,'cocoon':1,'limits':1,'performances':1,'except':1,'range':1,'race':1,'teeth':1,'mouth':1,'relation':1},'bristles':{'.':1},'reflectors':{'and':1,'.':1},'symbiosis':{'.':1},'secretion':{'such':1,'of':1},'hen':{'leave':1,'there':1,'which':1},'bubble':{'would':1,'of':3,'ascends':1,'coloured':1,'as':1,'are':1,'were':1,'the':1,'is':2},'survives':{'in':1},'journ':{'.':2},'continents':{'and':4,'are':1,'.':1},'secreted':{'strange':1,'from':2,'by':1},'semnopithecus':{'entellus':1},'mammals':{'and':9,'among':1,'there':2,'besides':1,'show':2,'enjoy':1,'it':1,'as':2,'including':1,'are':3,'have':2,'in':1,'ourselves':1,'whose':1,'by':2,'from':1,'hoofed':1,'did.':1,'burrowers':1,'.':13,'to':2,'master':1,'emerged':1,';':2,'save':1,'is':1,'we':2,'repeat':1,'which':1,'may':1,'but':1,'like':9,'arose':1,'they':2,'such':4,'flowering':1,'now':1,'adaptive':1,'possess':1,'off':1,'especially':1,'e.g':1,'these':1,'always':1,'will':1,'very':1,'the':2,'furnish':1},'nitrogenous':{'waste':2,'material':1},'foreheads':{'well-marked':1},'another.':{'investigation':1,'sec':1,'besides':1,'illustration':1},'survived':{'and':1},'elimination':{'of':3},'mice':{'learn':1},'with':{'all':8,'pointing':1,'less':1,'frontispiece.':1,'over':1,'particular':1,'worms':2,'yellow':1,'far-reaching':1,'hind-legs':1,'experiments':1,'human':1,'signs':1,'alternative':1,'its':12,'colour-associations':1,'one':4,'cave-bear':1,'remarkable':1,'decomposing':1,'much':5,'young':2,'reason--lays':1,'better':1,'insects':1,'neighbours':1,'internal':1,'microscopic':1,'4':3,'disgust':1,'gravel':1,'instincts':1,'awareness':2,'alternating':2,'them':3,'his':11,'increased':1,'permission':1,'arboreal':1,'capacities':1,'longish':1,'balancing':1,'negative':1,'words':2,'instinctive':1,'silk':1,'motor':1,'progressive':1,'sense-organs':1,'ageing':1,'large':4,'this':11,'coco-nut':1,'each':1,'perceptual':1,'traces':1,'engravings':1,'mental':1,'intelligence':2,'energy':2,'hard':1,'some':6,'plumage':1,'us':1,'our':3,'instinct--the':1,'rough':1,'folk':1,'planetesimal':1,'what':3,'definite':1,'fingers':2,'worship':1,'difficulties':1,'rational':1,'numerous':2,'public':1,'scientific':1,'zest':1,'cellulose':1,'seaweeds':1,'out-flowing':1,'extraordinary':1,'compressed':1,'tartan':1,'by':1,'universals.':1,'both':1,'great':7,'freshwater':2,'distinctness':1,'many':3,'parts':1,'motion':1,'benevolence':2,'grain':1,'greatly':1,'atoms.':1,'warning':1,'or':2,'embryo':1,'copper':1,'equally':1,'there':1,'peculiar':1,'sweet':1,'powerful':1,'marked':1,'hearing':1,'sympathy':2,'unicellular':1,'another':4,'such':3,'faraday':1,'.':1,'open':1,'your':1,'fossil-bearing':1,'startling':1,'little':1,'her':3,'shells':1,'positive':1,'flying':1,'two':1,'particulars':1,'anyone':1,'their':9,'2':2,'which':17,'reptiles':1,'vapours':1,'life':1,'only':1,'that':1,'becoming':1,'apparent':1,'flinty':1,'stone':1,'amphibians':1,'it':7,'offers':1,'determination':1,'external':1,'excellent':1,'prodigious':2,'an':11,'active':2,'considerable':2,'those':2,'animals':1,'adaptations':1,'glory':1,'these':4,'instinct':2,'sea-anemones':1,'project':2,'matter':2,'paragraph':2,'temperatures':1,'wicketed':1,'concepts':1,'wild':1,'about':1,'more':6,'beliefs':1,'something':2,'and':1,'associated':1,'protrusive':1,'almost':2,'certain':3,'universal':1,'suggestions':2,'few':1,'general':4,'as':1,'breathing':1,'numbers':1,'aristotle':1,'in':6,'partner':2,'mediocre':1,'agility':1,'any':2,'currents':1,'masterly':1,'astonishing':1,'different':2,'awkward':1,'no':2,'unsuitable':1,'ideas':1,'immense':1,'pectoral':1,'food':1,'other':3,'coconuts':1,'animal':1,'ordinary':1,'enormous':1,'calendar-keeping':1,'rude':1,'opposite':1,'mentality':1,'unsurpassed':1,'most':1,'mankind':1,'moss':1,'mendel':1,'astronomy':1,'buttonholes':1,'man':2,'a':72,'short':1,'branches':1,'traps':1,'conscious':1,'others.':1,'professor':1,'incredible':1,'eddies':1,'peculiarities':1,'points':1,'electrons':2,'very':1,'the':149,'mating':1,'reserve':1},'pull':{'of':3,'acting':1,'which':1,'each':1,'the':3,'than':2},'rush':{'violently':1,'through':1,'of':2},'october':{'10':1,'3':2,'5':2},'stoneless':{'plum':1},'world-cloud':{'of':1},'universe--astronomical':{'instruments.':1},'nearest':{'planet':1,'to':5,'star':2,'stars':2,'of':1},'agree':{'rather':1,'to':7,'.':1,'with':1,'that':2},'darker':{'in':1},'gone':{'furthest':1,'far':1,'back.':1,'to':1,'through':1,'in':1,'wild':2,'further':1,'beyond':1,'by':1},'haunts--such':{'as':1},'certain':{'comets':1,'individuality':1,'abilities':1,'hormones--itself':1,'facial':1,'repertory':1,'is':2,'pre-arrangements':1,'number':1,'actions':1,'sounds':1,'internal':1,'depth':1,'from':1,'degree':2,'microbes':1,'that':15,'peculiarities':1,'parts':1,'black':1,'units':1,'ancestor':1,'lichens':1,'long-headed':1,'backgrounds':1,'we':1,'clever':1,'kinds':1,'desires':1,'substances':1,'ductless':1,'however':1,'effective':1,'atoms':1,'sensory':1,'dinosaurs':1,'chemicals':1,'words':1,'cases':3,'minerals':1,'types':2,'areas':1,'plants':1,'dark':2,'kind':1,'difficulties':1,'predisposition':1,'commands':1,'lines':2,'strange':1,'amount':7,'implied':1,'limit':1,'of':1,'fixed':1},'ak':{'99712':1},'cuttles':{'or':1},'am':{'of':1},'an':{'ovule':1,'impression':4,'atmosphere':1,'evolutionary':1,'earthworm':5,'astronomical':1,'egg-cell':1,'infant':3,'aquatic':1,'atomic':2,'intricate':2,'earth':1,'abundant':2,'imagined':1,'outer':1,'anvil':1,'interesting':13,'apple--out':1,'endeavour':1,'instrument':4,'advanced':1,'easy':2,'orange':1,'electrical':2,'adequate':1,'unprecedented':1,'equilibrium':1,'increased':2,'advantage':1,'arboreal':3,'inspiriting':1,'indubitable':1,'educative':1,'account':1,'indigenous':2,'answer':3,'unimportant':1,'historic':1,'asymmetrical':1,'aerolite.':1,'awful':1,'instinctive':2,'emergence':1,'antiquity':2,'association':1,'eye-piece':1,'old-established':1,'evolution':1,'onion':1,'organ':3,'extremely':1,'unnecessary':1,'absurdly':1,'emphatic':1,'intensification':1,'activity':1,'entirely':2,'automatic':3,'essential':3,'associative':1,'adaptation':1,'unsatisfied':1,'abbreviated':1,'old':1,'x-ray':2,'insignificant':1,'energy':2,'animalcule':1,'hour.':1,'inkling':2,'astronomer':2,'individual':5,'all-pervading':2,'exuberant':1,'ascent':1,'extinct':5,'electric':20,'index':1,'apparatus':2,'opaque':1,'open':1,'ice':1,'hereditary':1,'increase':2,'appreciative':1,'indian':1,'eight-armed':2,'economical':1,'inborn':2,'indication':1,'antler':1,'increasing':2,'eagle':1,'evolving':2,'earlier':4,'explosive':1,'aeroplane':2,'intimate':1,'ever-lengthening':1,'exudation':1,'illustration':6,'outfit':1,'egg':1,'extraordinary':2,'experimenting':1,'immature':2,'expansion':2,'arithmetical':1,'invisible':2,'entrancing':1,'exciting':2,'advance':1,'enormous':10,'instant':1,'indivisible':1,'envelope.':1,'exceptionally':1,'amount':1,'ineffective':1,'anthropoid':3,'invitation':1,'offshoot':1,'observation':1,'expression':1,'elongated':1,'untutored':1,'utterly':1,'exuberance':1,'intellectual':1,'echo':1,'active':1,'appropriate':1,'eleventh':1,'extraneous':1,'eventful':2,'elementary':1,'inorganic':3,'immensely':1,'electronic':1,'ether':4,'ancient':3,'elastic':1,'eclipse.':1,'alligator':2,'unknown':1,'indispensable':1,'outline':2,'approximate':1,'immense':7,'intermediate':1,'examination':2,'inner':2,'interest':1,'ounce':1,'egg-layer':1,'exploring':1,'extensive':1,'imperfect':2,'amoeba':1,'inclined':1,'immediate':1,'idea':1,'appreciation':1,'external':2,'impulse':2,'atom':16,'upright':1,'improved':1,'institution':1,'encyclopaedia':1,'otter':1,'abundance':1,'exception':1,'apprenticeship':2,'hour':2,'eclipse':3,'harmonious':1,'obvious':1,'empty':2,'historical':1,'emotional':1,'outflame':1,'average':2,'undercharged':1,'assemblage':1,'enforced':1,'angel':1,'almost':2,'expanding':1,'expedient':1,'ant':3,'aristotle':1,'element':2,'apparently':1,'everyday':1,'open-water':1,'angle':2,'infantile':1,'awkward':1,'alphabet':1,'eloquent':1,'american':2,'event':1,'instance':1,'epoch':1,'internal':2,'inquiry':1,'oar':1,'animal':19,'elephant':1,'inch':19,'ordinary':6,'intelligent':6,'explanation':2,'unutterably':1,'independent':1,'extended':1,'easygoing':1,'opposite':1,'actual':2,'object':3,'astounding':2,'insect':5,'important':6,'appreciable':1,'advertisement':1,'infinite':3,'alpha':1,'irretraceable':1,'advantageous':1,'older':1,'undeniable':1,'age':2,'electron':8,'innocent-looking':1,'ocean':2,'intruder.':1,'exceedingly':1,'experimental':2,'african':2,'inhabitant':1,'opportunity':2,'order':1},'as':{'peacock':1,'all':2,'hunger':1,'being':1,'when':2,'mackerel':1,'dancers':1,'soon':1,'rest':1,'symbols':2,'brain':1,'bright':1,'dog':1,'vastly':1,'go':1,'graptolites':1,'expressions':1,'fine':1,'yet':4,'before':2,'one':6,'slow':1,'thrilling':1,'greenwich':1,'fit':1,'sodium':2,'possible.':1,'deposits':1,'examples':2,'to':38,'must':1,'wood':1,'smolts':1,'molecules':1,'ours':1,'gills':1,'has':6,'noctiluca':1,'frogs':1,'good':1,'pre-dravidians.':1,'easily':1,'very':1,'big':1,'locusts':1,'sappers':1,'possible':2,'dark':1,'every':1,'nearly':1,'they':17,'instinctive':1,'now':1,'dr':1,'crabs':1,'worlds':1,'evolution':1,'fossils':1,'heat-waves':1,'cavendish':1,'gifted':1,'modern':1,'large':3,'rods.':1,'stuff':1,'mind-body':1,'relics':1,'each':1,'beasts':1,'amoebae':1,'imprints':1,'mathematical':1,'reactions':1,'set':3,'rats':1,'grouse':1,'curved':1,'radium':2,'creation':1,'some':1,'dead':1,'parasites':1,'miniatures':1,'among':1,'are':2,'specified':1,'body-mind':1,'our':2,'fear':1,'best':1,'happens':2,'established':1,'shown':9,'palaeolithic':1,'for':1,'1850':1,'fingers':1,'food':3,'may':1,'health':1,'monkeyish':1,'copper':1,'public':1,'iron--and':1,'can':1,'granites':1,'we':59,'wheat':1,'inert':1,'cauliflower':1,'nature':1,'equivalent':1,'valuable':1,'atoms':1,'water':2,'basalts':1,'members':1,'represented':1,'oxalic':1,'safer':1,'dwindling':1,'by':1,'change':1,'on':1,'great':2,'kids':1,'of':1,'taking':1,'chamberlin':1,'thinking':1,'cormorants':1,'other':1,'grilse.':1,'peripatus':1,'heavy':2,'equally':1,'there':6,'bricks':1,'explained':1,'powerful':2,'marked':1,'parachutists':1,'walt':1,'freely':1,'einstein':1,'thick':1,'obliging':1,'earthworms':1,'he':3,'described':1,'crocodiles':1,'distinct':1,'twenty':1,'cradles':1,'two':1,'long':9,'quickly':1,'their':4,'much':4,'sponges':1,'man':1,'was':1,'empty':1,'clever':1,'corresponding':1,'that':7,'leptocephali':1,'shoots':1,'mentality':1,'about':1,'amphibians':1,'glass':1,'heat':2,'regards':11,'external':1,'mounted':1,'with':1,'those':9,'inconspicuous':1,'darwin':2,'hour':1,'brusque':1,'reliable':1,'this':2,'sea-anemones':1,'lungbooks':1,'will':1,'matter':3,'projecting':1,'thin':1,'many':6,'cats':1,'primitive':2,'refractors':1,'distinguished':2,'ants':2,'something':2,'collecting':1,'stubborn':1,'bullhead':1,'defined':1,'is':11,'year':1,'it':60,'an':14,'professor':5,'well.':1,'pieces':1,'numbers':1,'aristotle':1,'in':30,'handle':1,'lambs':1,'any':1,'if':16,'cave-men':1,'sir':3,'different':1,'compared':2,'no':1,'shell-shock':1,'means':1,'uranium':1,'far':5,'internal':1,'useless':1,'pure':1,'elephant':1,'resembling':1,'you':2,'volplanes':1,'higher':1,'open-water':1,'used':1,'beauty':1,'though':1,'contrasted':1,'mutual':1,'rain':1,'most':2,'but':1,'significant':1,'such':2,'elvers':1,'commensalism':1,'probable':1,'a':95,'crystals':1,'safe':1,'pithecanthropus':1,'light':1,'clear':1,'sun-spots':1,'well':11,'grilse':1,'donkeys':1,'having':1,'beds':1,'these':2,'electrons':1,'mechanical':1,'at':1,'the':98,'drawing':1,'restored':2},'associating':{'certain':1},'at':{'distances':1,'all':21,'rest':2,'four':1,'london':1,'its':10,'20':1,'work.':2,'mauer':2,'paris':1,'those':1,'heidelberg':1,'dates':1,'seventy':1,'his':2,'washington.':1,'mathura':1,'birth':1,'half':1,'12:30':1,'least.':1,'colonising':1,'night':9,'fixed':1,'right':4,'learning':1,'some':4,'coldrum':1,'home':4,'once.':1,'sunrise':1,'3':1,'various':3,'between':1,'nine':2,'each':1,'things--that':1,'hundreds':1,'here':1,'nightfall':1,'by':3,'great':2,'last':4,'many':2,'dublin':1,'so':1,'times':1,'http:':6,'first':9,'cambridge':1,'successive':1,'one':6,'another':2,'250':2,'total':2,'from':1,'twenty':1,'three':1,'least':20,'.':1,'their':2,'2':1,'186':2,'gibraltar':1,'leisure.':1,'500':1,'flight':1,'www.gutenberg.org':2,'that':6,'about':1,'but':1,'92':1,'present':12,'this':7,'work':3,'piltdown':1,'abrupt':1,'4557':1,'1.':1,'and':1,'it':1,'an':7,'niagara':1,'in':1,'any':9,'these':3,'different':4,'no':3,'perhaps':1,'things':1,'other':3,'sobral':2,'which':3,'new':1,'ordinary':1,'enormous':1,'simplicity':1,'opposite':1,'our':1,'earlier':1,'hand':2,'most':1,'two':1,'last--that':1,'such':1,'a':43,'lower':1,'e':1,'ottawa':1,'st':1,'809':1,'sunset':1,'the':123,'drawing':1,'once':11},'fumbling':{'at':1},'walks':{'of':1,'slowly':1,'erect':1},'watched':{'and':1},'tranquil':{'world':1},'dawn':{'of':10,'breaking':1,'to':1},'uplifts':{'of':1},'collie':{'at':1},'pliohippus':{'about':1},'2001':{'the':1},'predestined':{'plan.':1},'puppy':{'came':1},'contemporaries':{'in':1},'fry.':{'sir':1,'j':1,'but':1},'indemnify':{'and':1},'vocabulary':{'so':1},'walk.':{'how':1},'terra':{'firma':3},'gifts':{'as':1},'herbs':{'and':1},'environing':{'difficulties':2},'dives--':{'--carrying':1},'waterhouse':{'hawkins':1},'partitioned':{'box':1},'tricks':{'given':1},'mask':{'their':1,'the':1},'mimic':{'the':1,'is':1},'mass':{'and':3,'condensed':1,'of':20,'is':2,'spinning':1,'333':1,'persisted':1,'in':2,'gave':2},'dislodgment':{'is':1},'original':{'ancestors':1,'form':2,'plain':1,'nebula':1,'crust':1,'moorings':1,'greek':1,'peculiarities':1,'cradle':2,'home':3,'hole':1,'first':1},'external':{'methods':1,'opening':1,'hangers-on':1,'of':1,'partnership':1,'pouch;':1,'registration':1,'gills':2,'pouch':1,'method':1},'period--the':{'twenty':1},'sci':{'.':2},'consider':{'a':1,'what':1,'that':1,'.':1,'possibilities.':1,'the':7,'man':1},'elements.':{'sec':1},'31900':{'4':1},'instincts':{'and':1,'where':1,'are':1,'but':1,'.':2},'landlocked':{'corners':1,'dwindling':1},'debris':{'and':1,'of':1},'upkeep':{'of':1},'welfare':{'of':2},'reasoning':{'that':1,'man':1,'.':1},'causes':{'and':1,'of':1,'sleeping':4,'.':1,'the':1,'an':3},'particles':{'and':2,'move':1,'as':1,'are':4,'suspended':1,'in':2,'250':1,'even':1,'.':3,'which':3,'travelling':2,'was':1,'more':1,'may':1,'upon':1,'he':1,'on':1,'of':17,'will':1,'were':2,'the':2,'or':1},'careful':{'and':1,'comparison':1,'reading':1,'calculation':1,'observers':1,'piecing':1,'experiments':1,'way':1,'education':1},'disciples':{'of':1},'hunting':{'enabling':1,'on':1,'leopards':2,'or':2,'small':1},'spirit':{'of':4,'.':2},'to':{'all':6,'consider':4,'remarkable':1,'land-snails':1,'relieve':1,'yellow':1,'four':2,'mild':1,'skate':1,'go':13,'follow':1,'discern':1,'whose':1,'calculate':2,'animal':1,'paris':1,'shrinkage':1,'send':1,'environment':4,'charge':1,'reptiles':1,'swoop':1,'vegetation.':1,'include':1,'crest':4,'shoot':1,'point':3,'arboreal':2,'dispense':2,'induce':1,'me':2,'smack':1,'every':2,'trough':1,'fall':4,'affect':2,'converge':1,'monkeys':2,'look':6,'exaggerate':1,'tear':1,'try':2,'this':19,'settle':2,'us.':1,'speculation':1,'tortoises':2,'prevent':1,'force':1,'ten':1,'discover':4,'jump':1,'surrounding':1,'pass':7,'link':1,'further':2,'changefulness':1,'folk':1,'paralyse':1,'inspire.':1,'what':5,'giving':1,'disentangle':1,'asia':1,'him.':1,'experiment':4,'new':3,'alertness':1,'elsewhere.':1,'fend':1,'berthelot':1,'slow':2,'sink':1,'making':1,'evolutionist':1,'100':1,'fifteen':1,'interpret':1,'wait':1,'dry':9,'great':4,'receive':2,'30':1,'alaska':1,'anchor':1,'credit':3,'amount':1,'social':1,'climb':1,'otters':1,'changes':1,'say--of':1,'secure':2,'complying':1,'africa':1,'replace':2,'put':3,'decrease':2,'instinct--a':1,'establish':2,'estimate':3,'manipulate':1,'everybody':1,'use':5,'proceed':1,'prove':1,'two':5,'almost':1,'live':4,'doubt':2,'call':2,'strike':3,'survive':2,'themselves':1,'evolve.':1,'tell':4,'more':4,'breathe':5,'substances':1,'expose':1,'impress':1,'about':2,'extinction.':1,'particular':2,'scale.':1,'hold':1,'effort':1,'fly':2,'account':6,'pursue':1,'science':1,'work':2,'pieces--a':1,'reproduce':1,'learn':15,'meet':5,'pick':1,'control':2,'compare':1,'type.':1,'tap':1,'give':17,'sense':1,'accept':2,'pieces':1,'high':1,'his':10,'something':2,'slip':1,'arise':2,'handle':1,'keep':4,'attract':1,'occur':2,'huge':1,'end':2,'sit':1,'provide':3,'travel':10,'1':1,'how':1,'vital':1,'hop':1,'answer':4,'over-population':1,'stir':1,'both.':1,'utilise':5,'sir':2,'lag':1,'eighty':1,'germinal':1,'moult':1,'produce':1,'lighting':1,'lay':2,'date':1,'such':2,'bloom':1,'grow':1,'man':15,'a':76,'attempt':2,'remember':1,'light':5,'spout':1,'element':2,'inquire':4,'maintain':2,'deposit':1,'allow':4,'enter':3,'order':1,'punting':1,'contraction.':1,'help':3,'move':7,'vary':1,'stability':1,'insurgence':1,'its':16,'perfect':1,'26':1,'fit':2,'fix':3,'water-weed':1,'equalise':1,'absence':1,'overcome':1,'them':6,'good':1,'return':5,'greater':1,'introduce':1,'break':3,'mention':1,'conquer':2,'half':1,'accumulate':2,'speculate':2,'realize':1,'maintaining':1,'possess':3,'subtler':1,'form.':1,'evade':2,'condense':2,'vibrations':1,'realise':5,'each':2,'cliffs':1,'side':5,'mean':3,'square':1,'retrieve':2,'mental':2,'generation':2,'recapitulate':1,'tip':2,'expect':2,'measure':3,'our':13,'happen':1,'witness':1,'clothe':1,'depress':1,'profit':2,'open':3,'abide':1,'strangers':1,'sustain':1,'adapt':1,'7':1,'impart':1,'medicine':1,'twenty-five':1,'cause':1,'red':1,'metchnikoff':1,'assist':1,'associate':2,'interpose':1,'given':1,'sneak':2,'reason':1,'base':1,'struggle':1,'ask':2,'obliteration':1,'cough':1,'generate':1,'reflect':1,'prepare':1,'language':1,'david':1,'turn':4,'place':2,'deep-sea':1,'loud':1,'think':12,'south':1,'predominate':1,'feed':3,'striking':1,'feel':3,'one':6,'another':13,'carry':4,'radiate':1,'ring':1,'fiji':1,'172':1,'millions':1,'guess':1,'their':13,'bite':1,'construct':2,'anyone':1,'indicate':2,'master':2,'king-crabs':1,'white':1,'bits':1,'listen':1,'efface':1,'nutrition':1,'hug':1,'x-rays':1,'that':11,'continuous':1,'serve':2,'direct':1,'part':2,'peck':1,'insect-visitors--began':1,'10':1,'require':1,'tree':2,'project':3,'matter':1,'fruits':2,'gigantic':1,'and':6,'exert':1,'modern':1,'say':46,'lull':1,'have':19,'accompany':1,'any':2,'eels':1,'offer':1,'isolate':1,'gravity':1,'note':1,'blushing':1,'build':5,'which':31,'destroy':2,'begin':8,'acquire':1,'electric':1,'trace':2,'wind-blown':1,'reach':7,'complexity.':1,'most':3,'detect':4,'eight':1,'glow':6,'expound':1,'seize':1,'professor':1,'gather':2,'science.':1,'drive':1,'face':3,'furnish':1,'weigh':1,'justify':2,'institutions':1,'incomplete':1,'show':14,'fifty':1,'bring':3,'determine':3,'tree.':1,'melt':1,'earth':2,'find':19,'wriggle':1,'generation.':1,'knowledge':1,'environing':1,'explain':9,'storms':1,'eat':1,'surroundings':1,'betray':1,'darwin':3,'hope':1,'do':17,'waltz':1,'hit':2,'get':17,'beat':1,'express':1,'watch':1,'bear':3,'instinctive':1,'dr':1,'him':3,'comply':1,'reveal':1,'evolution':1,'investigate':1,'release':1,'them.':1,'freshwater':1,'where':2,'respond':1,'traverse':1,'set':1,'resist':1,'see':9,'sea':3,'violet':1,'fail':1,'find.':1,'gravitation':1,'sail':1,'birds':2,'pressures':1,'various':1,'conceptual':1,'donate':2,'glasgow':1,'man.':3,'notice':8,'extend':1,'parental':1,'deliver':1,'succeed':1,'wear':2,'travellers':1,'distinguish':2,'come':3,'improve':1,'both':2,'protect':3,'last':3,'many':2,'contract':1,'laplace':1,'plants':1,'admit':2,'cylindrical':2,'lash':1,'swallow':1,'radio-activity':1,'supply':2,'smother':1,'kin-sympathy':1,'subscribe':1,'pole':2,'air-breathing':3,'250':1,'technicalities':1,'speak':5,'decline':1,'raise':2,'deep':1,'teach':1,'create':2,'three':1,'.':2,'whom':1,'much':1,'change':2,'mars':2,'waste':1,'500':1,'life':2,'describe':3,'flight':1,'amphibians':1,'assert':1,'observe':2,'understand':9,'reason.':1,'an':14,'diffuse':1,'those':6,'sound':1,'adaptations':1,'these':2,'leave':4,'twigs':1,'britain':1,'near':1,'suppose':9,'guide':2,'spawn':4,'apprehend':1,'lapland':1,'it':7,'sting':1,'itself':2,'blame.':1,'everyday':1,'capture':4,'different':1,'develop':1,'perform':1,'suggest':3,'make':23,'cross':1,'unite':1,'check':1,'them--as':1,'split':1,'copying':1,'crustaceans':1,'several':1,'dusk':1,'kelvin':1,'nest':1,'drink':1,'hang':1,'effect':1,'viewing':1,'moving':1,'experiment.':1,'patagonia':1,'expend':1,'in':1,'miss':1,'mother':1,'very':2,'the':388,'left':1,'mingle':1,'being':1,'uranium':1,'accurate':1,'obtain':1,'rest':1,'electrification':1,'select':1,'harmonise':1,'identify':1,'human':2,'colonise':2,'fearful':1,'readers':2,'conclude':1,'deposits':1,'board':1,'snap':1,'save':2,'humanity':1,'scientific':1,'take':11,'swim':1,'read':4,'big':2,'possible':1,'dart':1,'five':1,'know':8,'decipher.':1,'press':1,'immediately':1,'tick':2,'insert':1,'rotate':6,'backboned':1,'electronic':1,'hunt':1,'tons':1,'roll':1,'collect':2,'continue':2,'seashore':1,'soft':1,'herons':1,'side--a':1,'shed':1,'right':1,'deal':8,'titan':1,'some':21,'play':2,'certain':1,'deduce':1,'convey':1,'escape':1,'star':1,'scale':2,'avoid':2,'separate':1,'ether':1,'leap':1,'behave':1,'cloud':1,'quote':1,'prof':1,'warranties':1,'trout':1,'illustrate':2,'be':180,'incandescence':1,'obey':2,'reaching':1,'rock':1,'breed.':1,'utter':1,'become':7,'instinct':3,'littoral':1,'five.':1,'throw':4,'shine':1,'stone':1,'age.':1,'conceal':1,'practical':1,'her':2,'act':2,'or':3,'imitation':1,'within':1,'guard':1,'promise':1,'sow':1,'excrementitious':1,'propel':1,'acquiesce':1,'support':2,'transform':1,'sunlight':2,'start':2,'suit':1,'enregister':3,'attach':1,'manufacture':1,'north':2,'complete':2,'form':13,'educate':1,'ascend':1,'believe':6,'regard':1,'heat':2,'hear':1,'another.':2,'heap':1,'atom':4,'promote':1,'considerable':2,'donate.':1,'count':3,'folk-ways':1,'us':24,'record':1,'convince':1,'grasp':2,'demonstrate':1,'stages':2,'similar':2,'agree':1,'150':3,'cover':3,'year':1,'rubble':1,'muscular':1,'disease':1,'as':1,'exist':4,'paraguay':1,'domesticated':1,'trip':1,'fill':2,'discriminate':5,'inborn':1,'compel':1,'other':8,'5':1,'branch':2,'test':1,'you':5,'shrink':2,'picture':1,'repeat':1,'indemnify':1,'mankind':1,'living':1,'walk.':1,'drift':1,'terra':3,'overtax':1,'recognise':6,'scores':1,'astronomy':1,'land':3,'sail.':1,'cling':2,'assume':1,'age':2,'lift':2,'time':1},'tail':{'and':2,'often':1,'is':1,'it':1,'as':1,'are':1,'in':1,'if':1,'from':1,'seems':1,'two':1,'.':5,'rivals':1,'which':2,';':1,'by':1,'projects':1,'a':1,'always':1,'coiled':1,'of':2,'served':1},'postglacial':{'times.':1},'th':{'.':1},'lankester':{'to':1,'has':1,'says:':1,'between':1},'animals--birds':{'and':1},'degeneration':{'may':1},'case':{'we':2,'better.':1,'although':1,'no':1,'these':1,'of':38,'is':2,'there':1,'it':3,'.':3,'leads':1,'to':1,'that':1,'however':2,'they':1,'in':2,'known':1,'probably':1,'the':2,'with':2,'than':1},'cause.':{'section':1},'cloud-belts':{'and':1},'puzzled':{'over':1,'when':1},'discrepant':{'.':1},'floated':{'on':1},'square-jawed':{'short-limbed':1},'trillions':{'of':9},'c-f.':{'the':1},'interpreting':{'the':1,'in':1},'instinct.':{'the':1},'m.d':{'.':2},'condition':{'of':2,'the':1,'had':1,';':1,'.':1},'s.f.':{'3':1},'accompanying':{'diagram':1},'marvellous':{'still':1,'atom':1},'ageing':{'.':1},'laying':{'down':2,'aside':1},'joined':{'to':1,'them--a':1},'large':{'and':3,'telescope':1,'insects':1,'fish':2,'in':1,'colony':2,'number':6,'bath':1,'brain':1,'as':3,'planets':1,'mirror':2,'skulls':1,'size':2,'rhinoceros':1,'scale':3,'heads':1,'lungs':1,'ventral':1,'masses':1,'proportion':1,'.':2,'terminal':1,'internal':1,'red':2,'we':1,'testes':1,'degree':1,'that':1,'quantities':1,'eggs':1,'ovaries':1,'however':1,'haunt':1,'lens':4,'meteorites':1,'coil':1,'marine':2,'telescopes':1,'areas':1,'a':1,'animals':1,'eye-sockets':1,'gape':2,'ones.':1,'magnet':1,'gibbon':1,'amount':1,'amphibian':1,'of':1,'excesses':1,'ready-made':1,'section':1,'anthropoid':1},'dinosaur':{'about':1,'reptiles.':1,'stock':1},'sand':{'and':3,'of':1,'over':1,'so':1,'.':2},'swirling':{'seething':1},'three-millionth':{'of':2,'part':1},'harry':{'johnston':1},'small':{'and':2,'shark':1,'family':2,'insects':1,'ears':1,'spider':2,'one':1,'bright':1,'spiders':1,'such':1,'globes':1,'intestine':1,'patch':1,'frog-hoppers':1,'creatures':1,'web':1,'compared':1,'group':1,'pin':2,'organisms':1,'water-animals':1,'gossamer':1,'organism':1,'per':1,'.':3,'particles':3,'to':3,'individuals':1,'vocabulary--he':1,'fraction':3,'units':1,'figures':1,';':1,'molecules':1,'coal-field':1,'tortoise-shell':1,'polyps':1,'fry.':1,'ripples':1,'multiple':1,'minority':1,'degree':1,'that':2,'may':1,'mammals':3,'tides':2,'whirling':1,'but':2,'it':1,'lens':1,'moths':1,'scale':2,'fishes':2,'number':1,'importance':1,'quantity':2,'volume':1,'about':1,'animals':4,'pests':1,'bullet':1,'items':1,'batteries':1,'corona':1,'bee':1,'staff.':1,'part':2,'donations':1,'anthropoid':1,'shore-animals':2,'arboreal':1,'sea-anemone-like':2,'marble--there':1,'crab':3,'are':1},'mammal':{'and':1,'essentially':1,'sucks':1,'is':1,'when':1,'mind':1,'s':1,'as':1,'mind.':1,'in':1,'the':1,'stocks':1,'with':1},'autotomy.':{'in':1},'abbreviated':{'recapitulation':1},'quicker':{'than':1},'methodical':{'habits':1},'proof--embryological':{'proof--man':1},'197':{'diagram':1,'000':1},'196':{'the':1},'191':{'hornbill':1,'life-history':1,'avocet':1,'spoonbill':1,'puffin':1,'falcon':1},'hour.':{'these':1,'the':1},'193':{'early':1},'192':{'hind-leg':1,'photo':1},'past':{'and':5,'a':1,'all':1,'generation.':1,'in':1,'century.':1,'ages--for':1,'generation':1,'there':1,'upon':1,'it':1,'amphibians':1,'one':1,'.':3,'at':1,'which':1,'time':1,'the':1,'still':1,';':1,'persisting':1},'displays':{'its':1,'.':1},'pass':{'on':2,'gradually':1,'from':3,'vertically':1,'suddenly':1,'over':1,'amongst':1,'by':1,'to':4,'behind':1,'through':11,'between':1,'along':2,'straight':1,'before':1},'situated':{'near':1,'at':1},'17.--a':{'map':1},'richard':{'owen':1},'clock':{'we':1,'would':1,'.':1,'struck':1,'beating':1,';':1},'section':{'of':2,'later':1,'1':1,'3':2,'2':1,'through':3,'4':2,'5':1},'reproduction':{'a':1,'both':1,'from':1,'for':1,'may':1,'is':2,'.':5,'which':1},'scientists':{'confront':1},'method':{'and':1,'used':1,'that':1,'simple':1,'of':6,'is':2,'exactly':1,'.':1,'namely':1,'much':1,'are':1,'which':1,'you':1,'was':2,'by':2,'if':1},'contrast':{'this':1,'to':3,'with':1,'between':2},'revealing':{'an':2},'full':{'and':1,'on':1,'terms':2,'license':1,'inheritance':1,'of':5,'stop':1,'stop.':1,'project':7,'flood':1,'daylight':1,'individual':1,'fathoms':1,'extent':1,'refund':2,'dawn':1,'resources':1},'escaping':{'pursuit':1},'installations':{'.':1},'argonaut':{'in':1},'leaping':{'a':1,'at':2},'7.--the':{'visible':1},'hours':{'on':1,'we':1,'from':1,'afterwards':1,'immediately':1,'of':1,'after':1,'days':1,'forty':1,'early':1,'to':1,'old':1,'in':1,'it':1,'i.e':1,';':1,'.':4,'until':1,'before':2},'concluding':{'this':1},'november':{'19':2,'6':1},'transformation':{'of':5,'comes':1,'such':1},'refractors':{'and':1,'are':1},'riviera':{';':1},'introductory':{'note':1,'the':1},'compliance':{'with':2,'requirements':1,'for':1,'.':1},'247':{'photo':2},'experience':{'and':2,'or':1,'for':1,'though':1,'of':1,'no':1,'it':1,'but':1,'.':1,'to':1,'nothing':1,'which':2,'in':2,'not':1,'known':1,'with':1,'by':1},'anthropologists':{'and':1},'bulges':{';':1},'periodic':{'shrinkages':1,'the':1,'variations':1,'tax':1},'social':{'group':1,'intercourse':2,'becoming':1,'person.':1,'face':1,'environment':1,'life--of':1,'systems':1,'heritage':2,'institutions--all':1},'action':{'and':2,'on':1,'like':2,'facility':1,'not':1,'of':4,'is':1,'it':1,'.':4,'how':1,'in':1,'following':1,';':1,'by':1},'matter--but':{'no':1},'slope':{'to':1,'from':2,'of':1},'struggle':{'all':1,'through':1,'for':21,'against':2,'out':1},'followed':{'on':1,'rapidly':1,'that':1,'with':1,'in':1,'some':1,'up':1,'without':1,'year':1,'from':1,'the':2,'was':1,'by':2,'roentgen':1},'moorland':{'.':1},'vii':{'the':1,'.':2},'aeschylus':{'gave':1},'hard-and-fast':{'boundary':1,'lines':1},'beheld':{'in':1},'pulls':{'the':2,'every':1},'substance.':{'it':1},'coercion':{'and':1},'nerve-centres':{'keep':1},'eddington':{'even':1,'of':1,'professor':1,'tells':1},'granular':{'appearance':1},'attendance':{'on':1,'fertilises':1},'magnitude--and':{'these':1},'educability.':{'young':1},'petroleum':{'ten':1},'6':{'1914.':1,'and':1,'great':1,'inches':1,'then':1,'.':5,'1919':1,'tadpole':1,'other':1,'the':2},'evolve.':{'viii':1},'more':{'limited':1,'developed':1,'accurate':2,'dynamic':1,'purely':1,'distant':1,'abundant':1,'rapid':4,'rapidly':2,'knowledge':1,'fit':2,'interesting':3,'complex':4,'passive':1,'to':3,'willing':1,'convoluted':1,'portentous':1,'inconspicuous':1,'familiar':1,'courage':1,'nearly':1,'trouble':1,'advanced':1,'debatable':1,'generalised':1,'masters':1,'like':3,'oxygen':1,'marvellous':1,'fully':1,'radiant':1,'loosely':1,'prolonged':1,'possibilities':1,'economically':1,'intelligence':2,'energy':1,'direct':2,'likely':2,'intelligible.':1,'besides.':1,'advantageous':1,'sail':1,'uniform':1,';':2,'numerous':3,'advantageously':1,'we':1,'explosive':1,'intimate':1,'importance':1,'masterful':1,'free':3,'atoms':2,'curved':1,'complicated':5,'besides':4,'flowering':1,'intelligent':1,'intense':1,'promiseful':1,'chapter':1,'about':3,'of':5,'thickly':1,'sensitive':3,'smoke':1,'adapted':1,'or':14,'frequent':1,'and':10,'primitive':2,'powerful':2,'marked':1,'highly':2,'quickly':2,'readily':3,'startling':1,'ancient':1,'illumined':1,'erect':1,'.':4,'wonderful':2,'resolute':1,'dome-like':1,'vigorous':1,'complete':2,'successful':1,'continuous':1,'mentality':1,'conspicuously':1,'but':1,'strenuous':4,'upright':1,'natural':1,'general':1,'than':64,'must':1,'parts':1,'romantic':1,'instructive':1,'grey':1,'discriminating':1,'matter':1,'actively':1,'promising':2,'drops':1,'ascetic':1,'varied.':1,'conjectural':1,'certain':1,'it':1,'comfortable':1,'in':1,'controlled':4,'convenient':1,'emancipated':1,'eloquent':2,'till':1,'vital':2,'gateways':1,'which':1,'so':1,'smell':1,'difficult':3,'clear-cut':1,'felt':1,'convincing':1,'alert':1,'important':3,'blood':1,'nutritive':1,'freely':1,'remote':1,'for':1,'effective':1,'mobile':1,'light':1,'definitely':1,'electrons':3,'wide-awake':1,'the':2,'marsupials':1},'door':{'and':1,'is':1,'two':1,'.':1},'testes':{'.':1},'substances':{'such':1,'or':1,'like':1,'give':1,'this':1,'disintegrate':1,'near':1,'but':1,'coloured':1,'as':1,'therefore':1,'permeating':1,'which':2,'in':1,'become':1,'the':1,'has':1,';':2,'are':5},'inquisitiveness':{'a':1,'and':1},'company':{'as':1,'with':1},'berridge.':{'shoebill':1,'woolly':1,'young':1,'surinam':1,'an':1,'common':1,'harpy-eagle':1,'the':3},'one-sided':{'as':1},'tested':{'for':1,'.':1},'foundations':{'of':4},'stampings':{'.':1},'keeping':{'this':1,'the':3,'his':1},'fatal':{'as':1,'.':1},'science':{'and':1,'lenard':1,'liquefies':1,'vol':3,'is':8,'it':1,'an':1,'produced':1,'as':1,'in':1,'should':1,'for':1,'introduction':1,'.':4,'to':1,'which':1,'surpasses':1,'has':3,'was':1,'naturally':1,'we':1,'after':1,'that':1,'who':1,'but':1,'tries':1,'were':1,'arrived':1,'encourages':1,'must':1,'a':1,'on':1,'this':1,'ever':2,'reads':1,'so':1,'of':5,'the':2,'makes':1},'centrifugal':{'force':1},'agoing.':{'illustration':2},'indicating':{'the':1,'that':1},'evolved':{'a':1,'and':2,'we':1,'from':5,'all':1,'but':1,'one':1,'reptiles':1,'amphibians':1,'hand':1,'in':2,'.':2,'or':1},'learn':{'and':2,'all':1,'more':2,'that':4,'.':1,'to':7,'its':2,'how':3,'the':2,'an':1,'with':1,'by':2,'quite':1,'if':1},'knocked':{'it':1},'lamp-shell':{'lingulella':1,'ligula':1},'male':{'and':2,'parent':1,'with':1,'of':3,'fish':2,'who':2,'or':1,'sea-horse':1,'mounts':1,'s':2,'helps':1,'kurtus':1,';':1,'has':3,'makes':1,'side':1},'plants--romance':{'of':1},'beautiful':{'and':2,'stone':1,'spectacles':1,'zoological':1,'is':2,'object':1,'one':1,'flint-shelled':1,'experiments':4,'green':1,'are':1,'sight':1,'pink-flush':1,'cradle':1,'brine-shrimp':1,'robe':1,'red':1,'opalina':1},'stated':{'that':1},'cosmic':{'dust':2,'rubbish':1},'wave.':{'illustration':1},'brain-mind':{'we':1},'suggestions':{'may':1,'of':2,'have':1},'accept':{'a':1,'the':1,'all':1},'states':{'and':2,'do':1,'we':1,'copyright':1,'of':2,'who':1,'.':3,'to':1,'without':2,'swims':1,'the':1,'where':1,'check':1},'obliquely':{'on':1},'sense':{'separated':1,'a':1,'and':2,'still':1,'of':19,'except':1,'but':1,'one':1,'born':1,'which':1,'in':1,'it':2,'such':1,'the':1,'.':2},'plan.':{'in':1},'dress':{'is':3,'it':1,'that':1},'struck.':{'there':1},'salts':{'of':3,'but':2,'.':2,'to':1,'as':1,'using':1},'axis':{'cylinder':1,'that':1,'of':3,'is':1,'but':1,'.':2,'to':1,'as':1,'at':1,'in':4,'once':3},'huge':{'electric':4,'paw':1,'family.':1,'agglomerations':1,'increase':1,'carcase':1,'crocodilian':1,'cavern':1,'three-horned':1,'extinct':2,'sieve':1,'electronic':1,'infantile':1},'respective':{'bodies':1},'instruments.':{'ii':1,'the':1},'imminent':{'destruction':1},'emancipated':{'more':1,'from':1,'.':1},'fruition':{'of':1},'gannets':{'and':1},'oligocene':{'the':1,'times':1,'period':1,'n':1},'glowing':{'metal':1,'into':1,'gas':1,'gases':4,'coal':1,'mass':2,'in':1,'hydrogen':4,'with':1},'cling':{'to':1,'on':1,'together':3,'firmly':1},'relinquished':{'the':1},'creature':{'and':2,'being':1,'is':3,'fond':1,'as':2,'standing':1,'from':1,'.':4,'to':2,'too':1,'expresses':1,'save':1,'reproduced':1,'eminently':1,'that':2,'with':3,'has':2,'like':1,'retreated':1,'whether':1,'of':2,'sometimes':1,'s':2,'the':1,'profits':1},'rungs':{'of':2},'plant':{'and':2,'we':1,'would':1,'may':1,'of':1,'about':1,'called':2,'as':1,'preparing':1,'or':1},'salt.':{'this':1},'lanky':{'legs':1},'intended':{'to':2},'thickened':{'skin':1},'perrin':{'the':1,'jean':1},'plane':{'of':6,'is':1,'namely':1,'.':1,'near':1,'in':1,'the':1},'waves':{'and':4,'longer':1,'give':1,'is':1,'whatever':1,'see':1,'are':5,'in':4,'279':1,'still':1,'ether':1,'from':1,'breaking':1,'.':9,'1':1,'sparkle':1,'only':1,'too':1,'which':5,';':1,'cause':1,'sent':1,'we':1,'used':1,'that':1,'our':1,'enter':1,'like':1,'five':1,'they':3,'must':1,'carried':1,'are--measuring':1,'light':1,'culminating':1,'transmitted':2,'can':1,'of':11,'the':4,'its':1,'or':1},'mendel':{'.':1},'acquisitions':{'gradually':1,'that':1,'of':3,'as':1,'in':1,'the':2},'resemble':{'a':2,'the':1},'boarders':{'those':1},'register':{'themselves':1,'the':2},'tentacles':{'and':1,'around':1,'some':1,'it':1,'can':1,'radiate':1,'round':1,'minute':1,'are':1},'cases.':{'using':1,'the':1},'fundamental':{'substance':1,'to':1,'nature':1,'importance':1,'instruments':1,'food-supply':1,'bodily':1,'entities--matter':1,'entities':2,'unity':1,'way':2,'existences':2,'facts':1,'impressions':1,'realities':1,'matter':1},'triassic.':{'comparatively':1},'grasshoppers':{'orthoptera':1},'replied':{'is':1},'passages':{'and':1},'barnard':{'yerkes':2},'self-destructively':{'would':1},'incessantly':{'bombarded':1},'reminded':{'that':1,'in':1},'trade':{'from':1},'attitude':{'and':1,'of':1,'as':2,'there':1},'paper':{'on':1,'nautilus':3,'bait':1,'exactly':1,'packet':1,'.':1,'were':1,'in':1,'edition.':1,'lying':1},'signs':{'and':1,'of':1,'printed':1},'looks.':{'illustration':1},'its':{'precise':1,'summer':1,'walking':1,'remarkable':1,'disturbances':1,'constituents':1,'beak':1,'mission':1,'years':1,'four':1,'brain':1,'shape':1,'disc':1,'existence.':1,'victim':2,'skin':2,'existence':1,'partisans':1,'previous':1,'completion':1,'particles':2,'limbs':2,'different-lengthed':1,'outer':1,'thumb':1,'anvil':2,'striking':1,'possessors':1,'young':3,'environment':4,'surroundings':2,'tail':2,'concavity':1,'microscopic':1,'molecules':1,'tail.':1,'gyges':1,'gills':2,'main':1,'position--it':1,'first':1,'giants':1,'breathing':1,'victims':2,'cloud-belts':1,'reptilian':1,'means':1,'far':1,'big':2,'oceans':1,'mouth':2,'young.':1,'germ-cells':1,'encircling':1,'emerald':1,'rotation':1,'far-reaching':1,'wings':4,'retreat':1,'lineage':1,'evolution':1,'name':1,'course':2,'bearings':1,'solution':1,'possibilities':1,'race':2,'activity':1,'soft':1,'lesson.':1,'exquisite':1,'ears':1,'upper':2,'habitat':1,'appearance':1,'energy':3,'fully-formed':1,'back':1,'collaterals':1,'prolonged':1,'opposite':1,'legacy':1,'bare':1,'measurement':1,'home':1,'functioning':1,'mother':3,'best':3,'mottled':1,'cilia':1,'leaf':1,'probable':1,'borrowed':1,'endowment':1,'self-effacement':1,'intimate':1,'definite':2,'frond-like':1,'dormitory':1,'venom':1,'new':1,'peg':1,'hind-legs':2,'speed':1,'body':7,'core':1,'toes':1,'business':1,'leg':1,'strata':1,'atoms':3,'extraordinary':2,'magnetism':1,'salient':1,'formation':1,'egg-cocoons':1,'trunk':1,'early':1,'path':2,'canals':1,'whiteness':1,'evolution.':1,'colours':1,'enormous':1,'shaggy':1,'brilliant':1,'many':2,'leaves':1,'parts':4,'greater':1,'counterpart':1,'wave-length':1,'pattern':1,'nucleus':1,'tongue':2,'whole':2,'relatives.':1,'origin':1,'diameter':1,'primitive':1,'own':18,'heart':1,'marginal':1,'coming':1,'habitual':1,'primary':3,'race.':1,'height':1,'utilisation':1,'date':1,'eggs':2,'brain.':1,'formidable':1,'owner':2,'table':1,'mere':1,'size':3,'wings.':1,'strong':2,'eye':1,'temperature':2,'width':1,'tremendous':1,'own.':1,'two':1,'spiral':1,'long':2,'plains':1,'secret':1,'wonderful':1,'prey':1,'pool':1,'way':5,'typical':1,'diving-bell':1,'legs':1,'voracity':1,'501':1,'interests':1,'mountains':1,'head':1,'stomach':1,'fiery':1,'high-pitched':1,'wits':1,'successful':1,'feathers':1,'great':1,'validity':1,'climax.':1,'neighbour':2,'heat':3,'cranial':1,'tentative':1,'constituent':1,'hole':1,'highest':1,'effort':1,'present':3,'kind':1,'lifetime':1,'skull':2,'characteristic':1,'straight':1,'bill':1,'attached':1,'gravitational':2,'father':1,'nine':1,'vitality.':1,'growing':1,'distribution':2,'millennia':1,'history':1,'predecessor':1,'climax':4,'influence':1,'faintness':1,'surface':7,'general':1,'return':1,'partner':1,'comparative':1,'sharp':1,'mouth.':1,'dress':1,'own--a':1,'swim-bladder':2,'huge':1,'ancestors':1,'stolidity':1,'winter':2,'paw':2,'flight':2,'air-dome':1,'centre.':1,'bell-like':1,'shoulders':1,'forests':1,'reality':1,'arboreal':1,'relatives':1,'strange':1,'sentiments':1,'special':1,'influences':1,'talons':1,'estuaries':1,'mammoth':1,'ordinary':1,'axis':13,'composition':2,'development':1,'immediate':1,'electric':1,'beginnings':1,'centre':4,'neck.':1,'nest':2,'teeth':1,'reach':1,'surface--before':1,'substitute':1,'companion':1,'gill-cavity':1,'dimensions':1,'journey':3,'moving':1,'colouring':1,'saucer-shaped':1,'share':1,'movements':2,'capacity':1,'burrow':2,'structure':1,'eyes':1,'so-called':1,'short':1,'branches':2,'gullet':1,'surprising':1,'revelations':1,'light':3,'colour':5,'starting-point':1,'life':2,'persistent':1,'benefactress':1,'tale':1,'inhabitants':1,'edge':1,'mass':2,'greatest':1,'broad':1,'volunteers':1,'path.':1,'original':3,'immensity':1,'function.':1},'roots':{'and':1,'to':2,'of':2},'imaginings':{'of':1},'rapidly':{'and':4,'on':2,'we':1,'towards':1,'altering':1,'revolving':1,'between':1,'round':1,'to':1,'in':1,'changing':1,'revolved':1,'alter':1},'shifts':{'the':1,'for':4},'man-ape':{'and':1,'to':1},'coarser':{'vibrations':1},'conjugation':{'of':1},'bell-animalcules':{'a':1},'adepts':{'at':1,'in':1},'isaac':{'newton':5},'travelling':{'and':2,'rapidly':1,'faster':1,'at':5,'the':1,'with':1,'round':2},'pinions':{'.':1},'atom--that':{'what':1},'formosa':{'those':1},'tentatively':{'just':1,'sets':1},'lowell':{'evolution':1,'made':2,'who':1,'to':1,'mars':1,'observatory.':1},'entire':{'shell':2,'uselessness':1,'system':1,'absence':1,'cessation':1,'belt':1},'secondarily':{'wingless.':1},'agitated':{'and':2,'communicate':1,';':1,'electrons':1},'saltatory':{'display':1},'iridescent':{'colours':1},'weeds':{'in':1},'speculate':{'where':1,'that':1},'laboratory.':{'a':1,'an':1},'sea-urchins':{'sea-lilies':1,'and':1,'we':1},'cambrian':{'and':1,'period':5,'correspond':1,'to':1,'reached':1,'the':1},'likeness':{'to':2},'fowlers':{'and':1},'all.':{'sec':1},'loosely':{'connected':1,'.':1},'20417.txt':{'or':1},'piping':{'cry':1},'nautiloids':{'and':1,'to':1,'began':1},'found':{'the':2,'is':1,'it':1,'an':1,'at':2,'in':22,'close':1,'next':1,'its':1,'elsewhere':1,'for':1,'their':1,'there':1,'long':1,'well-formed':1,'to':4,'out':1,'vigorous':1,'around':1,'in:':1,'that':11,'far':1,'gliding':1,'however':1,'but':1,'hundreds':1,'most':1,'everywhere':1,'not':1,'along':1,'quite':1,'by':2,'he':1,'a':5,'on':3,'practically':1,'no':1,'up':1,'.':2,'eighty-seven--and':1,'e.g':1},'energetically':{'rub':1,'through':1},'physiologically':{'expensive':1,'best':2,'.':1},'reactions':{'and':2,'to':1,'.':2,'which':1,'between':2},'england':{'and':1,'.':1},'oyster-catcher':{'and':1},'resolute':{'.':1},'fewer':{'and':1,'mistakes':1},'measurement':{'.':1},'blues':{'and':1,'are':1},'niger':{'120':1,'is':1},'really':{'a':1,'radiating':1,'taking':1,'move':1,'had':1,'occurred':1,'two':1,'excessively':1,'tell':1,'are':2,'travelling':1,'gigantic':1,'important':1},'try':{'to':4,'walking':1},'neanderthal':{'and':2,'men':4,'race':2,'ravine':1,'species':2,'man':10},'psychology':{'and':1,'that':1},'sea-meadows':{'and':1,'of':1,'as':1,'to':1},'boxed-in':{'energy':1},'research':{'on':1,'.':2,'as':1,'justified':1,'has':1,'shows':1,'must':1},'misses':{'the':1},'reward.':{'the':1},'kelvin':{'and':2,'who':1,'56':1,'one':1,'s':1,'lord':1},'denoted':{'by':1},'climatic':{'conditions':2},'occurs':{'even':1,'on':2,'about':2,'from':1,'is':1,'in':1,'with':1},'chapelle-aux-saints':{'175':1,'the':1},'belief':{'is':1,'that':2,'in':2},'risen':{'three':1},'drifting':{'past':1,'life':2},'porcelain':{'are':1},'qualify':{'the':1},'gravelly':{'bed':1},'imagine':{'them':1,'that':2,'could':1,'some':1,'how':2,'the':1},'stomach':{'and':1,'to':1},'rises':{'a':1,'to':5,'and':2,'why':1,'.':2},'occur.':{'illustration':1},'producers':{'using':1,'or':1},'albatross':{'and':1,':':2},'reared':{'themselves':1},'retained':{'in':1},'english':{'serial':1,'character':1,'disciples':1},'w':{'.':30},'expedient':{'by':1,'.':1},'mangrove-trees':{'or':1,'.':1},'exhibited':{'by':1,'in':1},'delicate':{'embryo':1,'body':1,'shell':2,'larva':1,'ctenophores':1,'experiment':1,'build':1,'films':1},'impart':{'violent':1},'reversing':{'layer':2},'slipped':{'on':1,'over':1,'from':1},'thereafter':{'perhaps':1},'mimetic':{'resemblance':1},'number':{'and':2,'on':1,'develop':1,'being':1,'of':42,'is':3,'one':1,'she':1,'which':1,'mr':1,'not':1,'.':2},'slipper':{'animalcule':3},'animals--beginnings':{'of':2},'annelids':{'related':1},'star-clouds':{'will':1},'differ':{'considerably':1,'from':1,'chiefly':1,'rather':1,'as':1,'very':1,'only':1,'greatly':1,'in':3},'heads':{'and':1,'the':1,'selected':1,'breaking':1,'it':1},'world...':{'.':1},'introduction':{'of':2,'3':1,'there':1,'every':1},'cradles':{'for':1},'calculations':{'based':1,'show':1},'essays':{'on':1},'molecular':{'motion.':1,'reality':1,'motion':1,'motions.':1,'motions':2,'disintegration':1,'movement':1},'elaboration':{'known':1},'relationship':{'and':1,'with':6,'between':1},'immediate':{'access':2,'surroundings':1,'precursors':2,'cradle':1,'circle':1},'appreciation':{'of':5},'self-mutilation':{'or':1},'zeppelin':{'or':1},'licensed':{'works':1},'calendar-keeping':{'and':1},'modes':{'of':6},'diffusion':{'or':1},'ungrateful':{'to':1},'observatory':{'greenwich.':6,'of':2,'victoria':2,'near':1,'fig':1,'such':1,'the':1,'or':1,'at':1},'vocal':{'and':1,'organs':2,'cords':2,'powers':1},'determined':{'beyond':1,'by':1},'fishermen':{'whom':1},'hot.':{'crossing':1},'algol':{'is':2,'has':1},'remembers':{'that':1},'streamed':{'night':1},'possibilities.':{'illustration':1},'well-developed':{'forehead':1,'head':1,'luminous':1,'form':1},'colour-resemblance':{'was':1},'vitally':{'interlinked':1,'important':1},'germ-cells--the':{'ovum':1},'reorganisation':{'which':1},'cleverness':{'.':1,'it':1,'in':1},'odd':{'cells':1,'which':1},'fashion.':{'finally':1},'internat':{'.':1},'commotion':{'is':1},'silvery':{'jacket':1,'air-bubble--air':1,'smolts':1,'halo':1},'also':{'among':1,'rang':1,'because':1,'followed':1,'unpalatable':1,'land-snails':1,'contribute.':1,'in':5,'it':1,'marked':1,'one':1,'mild':1,'are':1,'pass':1,'seen':1,'visible.':1,'handicapped':1,'opened':1,'for':3,'belong':1,'able':1,'due':1,'anatomical':1,'to':3,'implied':1,'aerates':1,'burrow.':1,'caused':2,'has':1,'more':1,'breathe':1,'be':6,'noteworthy.':1,'towards':1,'that':1,'very':3,'offered':1,'formed':1,'serve':1,'cheaper':1,'react':1,'produce':1,'rudimentary':1,'govern':1,'known':1,'necessary':1,'the':8,'proceed':1,'a':3,'on':1,'arranged':1,'driving':1,'showed':1,'receive':1,'of':3,'drop':1,'will':1,'defective':1,'became':1,'involved':1,'found':1,'enacted':1,'changes':1,'experimental':1,'something':1},'internal':{'surfaces':4,'partnership':1,'furnishings':1,'revenue':1,'tides':1,'adjustments':1,'as':1,'surface':1,'parasites':1,'source':1,'heat':3,'secretions':1,'game':2,'atomic':1,'secretion':1,'experimenting':1,'gills':1,'structure':2,'unpaying':1},'centrosomes':{'one':1},'seized':{'the':1,'by':2},'play':{'a':2,'among':1,'we':1,'for':1,'of':3,'is':2,'an':2},'index':{'of':1},'swiftly':{'gliding':1,'electrons':1},'nasal':{'bones':1},'complexity.':{'corpuscles':1},'virus':{'or':1},'plan':{'.':1},'accepting':{'unsolicited':1,'it':1},'colliding':{'and':1,'of':1},'head-end':{'remains':1},'demand':{'a':2,'which':1},'galway':{'that':1},'whalebone':{'whales':2,'plates':2},'lessons':{'both':1,'for':1,'of':1,'began':1,'had':1,'learned':1},'long-headed':{'square-jawed':1},'sometimes':{'work':1,'almost':1,'hard':1,'marked':1,'one':1,'niggardly':1,'as':1,'manages':1,'at':1,'have':1,'seen':1,'sought':1,'slumped':1,'happens':2,'to':4,'leading':1,'make':1,'there':1,'justifies':1,'few':1,'only':1,'much':1,'helps':1,'replaced':1,'several':1,'thousands':1,'difficult':1,'swim':1,'alongside':1,'far':1,'however':1,'but':1,'sooner':1,'they':1,'competitive':1,'an':1,'a':2,'many':1,'no':1,'constitutional':1,'used':2,'deposit':1,'found':1,'the':4},'cover':{'the':2,'itself':1,'in':1,'an':1},'firma':{'and':2,'also':1},'artistic':{'race':2,'drawings':1,'sense':1},'donkeys':{'.':1},'attacking':{'a':2},'hydatina--has':{'nine':1},'far-flung':{'fire-mists':1},'golf':{'ball':2},'hoar-frost':{'or':1},'gold':{'constituted':1,'leaf':2,'is':2,'.':1,'will':1,'to':1,'in':1,'has':1,'into':1},'evaporation':{'and':1},'agassiz':{'once':1},'fatal.':{'it':1},'pill-like':{'ball':1},'hinkins':{'son.':2},'impact':{'of':2},'ape-man':{'reconstructed':1,'to':1,'as':2,'and':1},'food-signal':{'.':1},'spineless':{'cactus':1},'writes':{':':1,'so':1},'fauna--the':{'two':1},'failed':{'.':1},'life--of':{'which':1},'factor':{'which':1,'that':1},'indifference':{'to':1,'that':1},'armour':{'of':1,'or':1},'giants':{'and':2,'over':1},'noctiluca':{'whose':1,'which':1},'sand-pit':{'at':2,'must':1},'dependent':{'on':6},'liquid':{'and':1,'we':1,'when':1,'air':3,'can':1,'cling':1,';':1,'the':1,'.':3,'or':2},'adventurers':{'all':1},'flowing':{'of':1,'through':1,'out':2},'sunny':{'side':1,'bank':1},'clavius':{'the':1},'oceans.':{'they':1},'closely':{'comparable':2,'investigated':1,'corresponding':1,'resemble':1,'interwoven':1,'wrapped':2,'to':2,'resembling':1,'similar':2},'compass':{'and':1,'there':1,'possible':1},'man-of-war':{'there':1,'119':1},'4230':{'2':1},'enemy':{'home.':1},'devoured':{'by':1,'.':1},'avocet':{'s':2},'progressive':{'evolution':1,'mammals':1,'conquest':2,'mammals.':1,'.':1,'simian':1},'paddling':{'with':1,'in':1},'body.':{'this':1,'what':2,'illustration':1,'if':1},'sojourn':{'.':1},'surrendering':{'the':1},'croatia':{'and':1},'liver-fluke':{'of':1},'obscure':{'the':1,'but':2},'river':{'and':2,'heads':1,'.':3,'in':1,'the':1,'or':2},'approaching':{'the':1},'bulky':{'fuel':1},'body':{'and':14,'equally':1,'up':1,'acquired':1,'is':14,'thus':1,'one':1,'as':3,'at':1,'during':2,'in':1,'into':1,'if':1,'again':1,'containing':1,'or':2,'from':2,'possible.':1,'that':2,'decreases':1,'.':15,'to':6,'which':3,'engulfing':1,'before':1,'was':1,'until':1,'shows':1,'locate':1,'do':1,'though':1,'may':2,'becomes':1,'breaks':1,'of':11,'but':4,'were':1,'such':1,'with':2,'by':3,'sways':1,'on':1,'has':2,'always':2,'might':2,'could':2,'say':1,'worth':1,'will':1,'so':3,'overcharged':1,'keeps':1,'far':1,'the':1,'clearness':1,'called':1,'elongated':1,'are':2},'delicately':{'and':2,'built':2},'set':{'off':1,'encoding':1,'of':5,'up':4,'free':3,'electrons':1,'in':6,'forth':8,'apart':1},'ferments':{'.':1},'temperatures.':{'but':1},'enabled':{'to':3,'physicists':1,'us':1},'vertebrates':{'are':1,'or':1,'arose':1,'except':1},'sex':{'another':1,'for':1,'often':1},'see':{'among':1,'right':1,'reference':1,'is':1,'in':7,'it':1,'billions':1,'at':2,'signs':1,'our':1,'.':1,'theoretically':1,'if':1,'again':1,'what':5,'for':1,'explain':1,'that':12,'when':1,'next':1,'how':3,'much':1,'fig':1,'evidences':1,'sections':1,'into':1,'life':1,'means':1,'edge-on':1,'photograph':1,'diagram':1,'them':1,'violet.':1,'now':1,'a':8,'on':2,'evolution':1,'this':2,'later':1,'us':1,'whether':1,'paragraph':2,'so':1,'these':1,'the':7},'sec':{'.':77},'migration':{'and':1,';':1,'or':1,'up':1,'in':2},'sea':{'and':15,'cambridge':1,'salt':1,'is':2,'it':1,'117':1,'including':1,'are':3,'in':3,'.':13,'by':1,'stood':1,'for':2,'pelagic':1,'there':2,'shore':1,'should':1,'to':3,'2':1,'too':1,'has':1,'was':1,'we':1,'that':1,'very':1,'but':2,'others':1,'128':1,'rises':1,'desert':1,'a':2,'especially':1,'of':2,'as':2,'while':1,'gathers':1,'does':1,'usually':1,'the':9,'where':1,'or':2},'aberdeen':{'with':1},'outward':{'behaviour':1,'from':1,'by':1},'shower':{'of':3},'eminently':{'educable.':1,'educable':1},'foraminifer':{'polystomella':2},'taming':{'of':1},'jewels.':{'there':1},'dilutes':{'as':1},'exudation':{'of':1},'endure':{'the':1},'europe':{'a':1,'from':2,'for':1,'.':2,'so':1,'have':1,'were':1,'such':1,'slopes':1,'was':2,'or':1},'jaws.':{'power':1},'eustachian':{'tube':2},'incident':{'is':1},'mingling':{'of':1,'with':1},'things--that':{'fits':1},'energy--may':{'appear':1},'prospects':{'of':1},'lingulella':{'of':1},'improved':{'nervous':1,'habits':1,'by':1},'barely':{'separated':1},'harpy':{'occurs':1},'possible.':{'the':3,'for':1,'illustration':1},'connection':{'with':12,'however':1,'between':2},'amoeba':{'pelomyxa':1,'is':1,'61':1,'greatly':1,'overtakes':1,'pursues':1},'lash':{'large':1,'or':1},'everything.':{'sheer':1},'whole':{'prospect':1,'solar':1,'follows':1,'series':1,'is':1,'creation':1,'it':3,'earth':6,'floating':1,'civilisation':1,'declined':1,'physical':1,'stretch':1,'integrative':1,'to':1,'of':4,'world.':1,'body':1,'we':1,'universe.':1,'originated':1,'sufficient':1,'material':2,'but':1,'grilse':1,'somewhat':1,'world':3,'structure':1,'simpler':1,'a':1,'progressive':1,'bubble':1,'thing':1,'truth':1,'universe':3,'the':1,'extent':1,'or':1,'history':2},'1919':{'to':1,':':1,'.':1,'one':1},'loaf':{'taken':1},'volcanic':{'material':1,'ash':1,'gases':1,'activity':1},'bell':{'be':1,'becomes':1,'is':1,'however':1,'at':1,'which':1,'the':1,'its':1},'etre':{'of':1},'seems':{'a':1,'little':1,'transitional':1,'that':8,'almost':1,'certain':1,'clear':1,'no':2,'possible':1,'an':1,'to':19,'so':1,'at':1,'permissible':1,'of':1,'not':1,'impossible':1,'highly':1,'far':1},'acted':{'on':1},'corresponds':{'to':5,'with':1},'race.':{'the':1},'hollow':{'caves':1,'flattened':1},'unicellular':{'and':1,'protozoa':1,'plants':1,'algae':2},'agents':{'and':1},'adaptation':{'of':2,'to':5,'.':1},'church':{'pictures':1,'is':1,'there':1},'sees':{'and':1},'reflective--which':{'is':1},'belt':{'of':1,'the':1},'moon--the':{'mountains':1,'earth':1},'publishing':{'co':2},'originators':{'of':3},'lizards':{'and':2,'paddling':1,'the':1,'turtles':1},'acceptance':{'.':1},'clay.':{'the':1},'intricacies':{'of':1},'extravagant':{'in':1},'scions':{'of':1},'extreme':{'changes':1,'is':2,'end':1,'cold--an':1,'rarity':1},'firm':{'of':1,'fulcrum':1,'basis':1},'resting':{'on':2,'or':1,'during':1},'pliocene':{'and':1,'that':1,'period':1,'.':1,'as':1,'were':1,'before':1,'n':1,'or':1,'times':1},'squirrel':{'and':2,'making':1,'is':2,'with':1},'high-pitched':{'voice':1},'fire':{'a':1,'on':1,'and':1,'for':2,'is':1,'but':1,'as':1,'which':1,';':2,'until':1},'amphibians':{'and':4,'frogs':1,'some':1,'known':1,'as':1,'before':1,'sprang':2,'fed':1,'from':1,'for':1,'had':1,'.':4,'which':1,'was':1,'we':1,'towards':1,'led':1,'that':1,'burrowing':1,'altogether':1,'fishes':1,'with':3,'by':1,'retained':1,'implied':1,'were':1,'called':1},'fritz':{'mueller':1},'races':{'brethren':1,'and':1,'to-day':1,'of':6,'than':1,'met':1,'as':1,'--which':1,'go':1,'the':1,'or':2,'must':1},'representative':{'and':1,'of':6,'fauna':1,'illustrations':1,'--from':1},'formless':{'gaseous':1},'sixes':{'fives':1},'handling':{'organ':1},'uncertain':{'.':2,'some':1,'but':1,'ground':1},'7700':{'0':1},'reliable':{'a':1,'calculations':1},'admire':{'in':1},'receive':{'specific':1,'a':1,'the':3,'from':1,'them':1},'formats':{'will':1,'readable':1},'amniota':{'in':1},'projecting':{'filaments':1,'upper':1,'wire':1},'robin':{'redbreast':1},'secluded':{'retreat.':1},'pound':{'of':5,'to':1},'jettisons':{'the':1},'agitation':{'of':1},'moth':{'emerges':1,'emerging':1,'e.g':1,'is':1,'should':1,'76':1,'are':1,'the':1,'has':2,'settled':1,'automatically':1},'von':{'indetal':1},'owen':{'said':1},'binding':{'the':1},'level.':{'yet':1},'36':{'seconds':1,'photo':1},'feather-wing':{'a':1},'cerebrum':{'the':1},'owes':{'much':1},'beautifully':{'worked':1,'modified':2},'vanish':{'.':1},'acquires':{'a':1},'greenwich.':{'comet':1,'the':1,'fig':3,'typical':1},'processes--':{'1':1},'cyclostomes':{'such':1},'shorten':{'and':1},'beune':{'throughout':1,'179':1},'shorter':{'and':4,'the':1,'in':1,'period--its':1,'waves':3},'read':{'partly':1,'that':2,'these':1,'it':1,'this':1,'understand':1,'the':3,'by':1},'pecking':{'scratching':1},'serum':{'of':1},'survey':{'of':4,'the':1},'specimen':{'of':3},'knitting':{'needle':1},'snail':{'chopped':1,'and':2,'is':1,'s':2},'comprehensive':{'articles':1},'blue-greens':{'harmonise':1},'alert':{'very':1,';':1,'than':1},'viewing':{'displaying':1},'levels':{'.':2,'in':1},'leaps':{'violently':1,'along':1,'from':2,'through':1},'necessity':{'and':1,'has':1,'for':2},'mussel':{'cannot':1,'.':2},'recent':{'observation':1,'advances':2,'study':1,'eclipse':1,'discovery':1,'british':1,'times':3,'discoveries':3,';':1,'years':5,'research':2,'achievement':1,'view':1},'race-continuing':{'adaptations':1},'expend':{'this':1,'considerable':1},'inches.':{'i':1,'illustration':1},'food-plant':{'to':1,'in':1},'concrete':{'suggestions':1,'mental':1},'regulating':{'and':1,'charities':1},'qualities--notably':{'health':1},'ltd.':{'a':1,'electric':1,'this':1,'professor':1,'charles':1,'an':1,'rotating':1,'the':3},'crayfish':{'and':1},'body-building':{'by':1},'woodward':{'s':1},'abbreviation':{'the':1},'hercules':{'a':1,'108':1,'37':1},'spinners':{'let':1},'plant-like':{'animal':2},'tribe.':{'keen':1},'readers':{'who':1,'wishing':1},'recommended':{'to':1},'making.':{'but':1},'resemblances':{'to':1},'causing':{'an':1},'parents':{'and':2,'bring':1,'thrusting':2,'in':1},'types--':{'lost':1},'physics--the':{'wonders':1},'sojourning':{'for':1},'surprised':{'by':1},'putnam':{'s':2},'provisional.':{'illustration':1},'clutches':{'.':1},'victims':{'such':1,'or':1},'demands':{'.':1,'general':1},'couple':{'of':1},'wives':{'are':1},'stockholm.':{'a':1,'wing':1},'suffering':{'from':1},'sea-lettuce':{'or':1},'shading':{'off':1},'emergence':{'of':11},'projects':{'freely':1,'from':1},'heightened':{'.':1},'sorting':{'out':2},'imposed':{'by':1},'dislodged':{'sea-anemone':1},'hue.':{'there':1},'aridity':{'set':1,'led':1},'sulphite':{'screen':1},'communications':{'in':1},'well-poised':{'head':1},'continue':{'consistently':1,'on':1,'its':2,'to':5},'spiny':{'ant-eaters':1},'exquisitely':{'beautiful':1},'tribes':{'of':1},'horsetails':{'which':1},'disorder':{'and':1,'of':1},'interbreeding':{'of':1,'.':1},'irresistibly':{'suggests':1},'methods':{'and':1,'we':1,'used':1,'like':1,'that':1,'of':10,'is':1,'it':1,'.':3,'to':1,'have':1,'really':1},'spring':{'and':2,'wheat':2,'of':1,'tides':2,'tide':2,'flower-perfumed':1,'out':1},'leptocephali':{'a':1},'obscure.':{'seasonal':1,'when':1,'illustration':1,'hunger':1},'mighty':{'theory':1,'swarms':1,'globe':1,'dead':1,'swarm':1,'flame':1,'animal':1,'shadow':1},'sight':{'and':2,'this':1,'of':1,'who':1,'.':2,'in':2,'not':1,'hearing':1,'more':2},'steam-engine':{'.':1},'curious':{'about':1,'organ':1,'sideways':2,'is':1,'blood-containing':1,'thing':1},'battalion':{'of':1},'committing':{'ourselves':1},'gill-clefts--':{'a':1},'stamens':{'kneads':1,'holding':1},'measurements':{'1':1,'at':1,'which':1,'.':1},'behave':{'as':2,'like':1},'newcomb':{'popular':1,'is':1,'the':1},'dating':{'from':1},'lowell.':{'the':1},'answers.':{'the':1},'inclination':{'to':1},'be':{'invariable':1,'splitting':1,'founded':1,'sunk':1,'spaced':1,'reshufflings':1,'poorly':1,'compact':1,'to':2,'fatal':1,'separated.':1,'brown':1,'counted.':2,'radio-active':1,'exact':1,'transformed.':1,'illustrated':1,'perceived':2,'dealt':4,'small':1,'ultra-violet':1,'noted':4,'ten':1,'invaded':1,'dried':1,'picked':2,'further':1,'estimated':1,'expressive':1,'even':2,'giving':1,'beaten':1,'liberated':1,'prejudicially':1,'learned':2,'told':2,'met':1,'active':1,'implicit':1,'obtained':1,'great':1,'broken':4,'involved':1,'accomplished':1,'periodic':1,'settled':1,'composed':1,'named':1,'followed':2,'explained':3,'visible':4,'readily':2,'fed':1,'working':1,'positive':1,'wiped':1,'two':2,'therefore':1,'taken':4,'more':6,'inclined':1,'suffused':1,'known':1,'producing':1,'modified':1,'evolved':1,'following':1,'cited':1,'something':1,'allowed':1,'terrestrial':1,'influenced':1,'white-hot.':1,'unavailable.':1,'six':1,'1':1,'located':1,'called--it':1,'fostered':1,'undergoing':1,'reconciled':1,'earlier':1,'wrong':1,'understanded':1,'waves':1,'a':27,'overtaken':1,'light':1,'rather':1,'so':2,'pulled':1,'counted':2,'over':1,'interpreted':1,'produced':2,'still':2,'negotiated':1,'actually':1,'better':1,'permanent':1,'overcome':1,'affected':1,'easily':2,'indivisible.':1,'always':1,'identified':1,'applied':1,'found':11,'physiologically':1,'suspended':1,'investigated':1,'our':2,'avoided':1,'borne':1,'shown':3,'washed':1,'hastily':1,'content':2,'laid':1,'believed.':1,'given':1,'completely':1,'put':3,'universally':1,'enormous':1,'created':4,'blown':1,'omitted':2,'one':4,'done':2,'adopted':1,'directly':1,'impossible':2,'earthworms':1,'little':2,'approximately':1,'too':7,'final':1,'discovered':2,'that':11,'released':1,'somewhat':1,'eliminated':2,'convinced':1,'ungrateful':1,'frankly':1,'splendidly':1,'determined':1,'supposed':1,'17-1':1,'and':1,'lightly':1,'well':1,'confessed':1,'turned':2,'buried':1,'seen':22,'clearly':2,'built':1,'thoroughly':1,'able':5,'lit':1,'absorbed':1,'green':1,'sure':2,'clearer':1,'paid':1,'said':19,'nothing':1,'measured':2,'considered':4,'calculated':1,'sometimes':1,'inferred':1,'looked':1,'accounted':2,'left':3,'shot':1,'supported':1,'fifty':1,'rotating':1,'carefully':1,'enormously':1,'slow':2,'based':1,'going':1,'judged':2,'credulous':1,'employed':1,'guarded':1,'exceptional':1,'between':2,'liable':1,'nibbled':1,'delicately':1,'set':1,'swept':1,'seas':1,'observed':2,'luminous':2,'best':1,'subject':1,'invoked':1,'halved':1,'enough':1,'unable':1,'allotted':1,'drawn':3,'profitable':1,'we':1,'renamed.':1,'however':2,'clues':1,'improved':1,'many':1,'called':14,'plants':1,'conquered':1,'adapted':1,'asked':3,'otherwise':1,'regulated':1,'deflected':1,'associated':4,'unearthed':1,'destroyed':2,'described':6,'three':2,'quickly':1,'recognised':2,'expected':1,'copied':1,'life':3,'robbed':1,'sufficient':1,'gas':1,'worked':1,'present':1,'inconspicuous':1,'sound':1,'abandoned':2,'freely':2,'almost':1,'violently':1,'thus':1,'helped':1,'examined':2,'in':8,'reminded':1,'linked':1,'stimulated':2,'patient':1,'split':2,'agitated':1,'several':3,'difficult':1,'used':5,'upon':1,'compared':2,'arrived':1,'prophesied':1,'circumvented':1,'kept':1,'older':1,'changes':1,'constitutional':1,'thought':3,'very':11,'the':11,'realised':1,'departed':1,'less':1,'stored':1,'handed':1,'useful':4,'recapitulated':1,'rapid':1,'regarded':7,'lured':1,'transformed':2,'easy':1,'engulfed':1,'increased':1,'read':1,'dissected':1,'required.':1,'dark':1,'accepted':2,'advanced':1,'necessary':1,'like':4,'admitted':5,'either':1,'translated':3,'simply':1,'reduced':1,'right':1,'often':1,'exposed':1,'some':2,'understood':2,'curious':1,'dissociated':1,'gradually':1,'expressing':1,'eating':1,'bold':1,'remembered':4,'analysed':1,'precious.':1,'accompanied':1,'about':2,'cautious':1,'carried':1,'getting':1,'entailed':1,'of':6,'discussed':2,'urged':1,'avoided.':1,'within':1,'bound':2,'due':1,'.':4,'mere':1,'indispensable':1,'there':1,'noticed':3,'much':2,'infected':1,':':1,'forming':1,'satisfactorily':1,'removed':1,'true':4,'made':11,'arranged':1,'embedded':1,'placed':3,'below':1,'converted':2,'mature':1,'pumped':1,'clear':1,'darker':1,'proud':1,'proved':1,'moved':1,'slowing':1,'an':5,'as':5,'at':2,'constructed':1,'effected':1,'beyond':1,'inborn':1,'no':15,'discerned':1,'when':1,'dimmed':1,'other':1,'transported':1,'included':1,'fastened':1,'utilised':2,'doubted':1,'far':1},'paloloworm':{'of':1},'obscures':{'them':1},'agreement':{'and':2,'disclaim':1,'by':1,'for':2,'shall':2,'amongst':1,'.':3,'will':1,'you':3,'the':1,'with':1,'violates':1,'nor':1,'before':1},'departures':{'among':1,'from':2,'of':2,'or':2,'behaviour-variations':1,'they':1,'in':2,'occur':1},'1919.':{'taken':1},'method.':{'illustration':1},'tidal':{'action':1,'energy':1,'river':1,'theory':1,'waves':1},'-273':{'deg':1},'by':{'saying':1,'all':4,'endeavour':2,'less':1,'being':3,'gradual':1,'both':1,'seizing':1,'worms':1,'rest':1,'rotating':1,'experiments':1,'animals':1,'ice':1,'human':1,'disadvantageous':1,'glue-like':1,'budding':3,'abundant':1,'its':4,'pterodactyls':1,'homology':2,'limbs':1,'dividing':2,'consistently':1,'dubois':1,'glowing':1,'passage':2,'coaxing':1,'insects':2,'other':2,'reptiles':1,'helmholtz':1,'hideous':1,'meadows':1,'it.':1,'division':1,'them':1,'someone':1,'influences':1,'means':18,'food':1,'overflows':1,'dr.':1,'permission':20,'cutting':1,'friction':1,'prof':5,'instinctive':1,'dr':4,'day':4,'association':1,'viscid':2,'moist':1,'name':1,'profound':1,'h':1,'bay':1,'involution':1,'surrendering':1,'vibrations':2,'ductless':1,'bats':1,'mr':3,'automatic':1,'legions':1,'liberating':1,'immigrants':1,'ferments':1,'burying':1,'intelligence':1,'radium':1,'some':7,'rivers':1,'crows':1,'full':1,'sight':1,'defences':1,'our':5,'civilisation':1,'tracheate':1,'intercrossing':1,'even':1,'what':2,'still':1,'superposing':1,'ejecting':2,'driving':1,'deliberate':1,'memories':1,'circulating':1,'representatives':1,'artificial':1,'birds':2,'e-mail':1,'acting':1,'experiment':2,'various':3,'vascular':1,'out-side':1,'new':1,'falling':2,'reading':2,'numerous':2,'u.s':1,'contrast':1,'columbus':1,'blowing':1,'scientific':1,'cellulose':1,'nature':2,'men':2,'water':1,'pressure':1,'experimenting':2,'threads':1,'others':3,'holding':1,'hiding':1,'comparison':1,'great':1,'accident':1,'your':1,'g':1,'freely':1,'ribs':1,'larger':1,'lichens':1,'experience':8,'plunging':1,'periodic':1,'radiation':1,'social':1,'passing':3,'changes':1,'frequent':1,'this':3,'discharging':1,'volcanic':1,'gas-bubbles':1,'burning':1,'striking':1,'suddenly':1,'churning':1,'powerful':1,'one':2,'spinning':1,'very':1,'air-breathing':1,'incandescent':1,'motor':1,'such':3,'collisions':1,'shortening':1,'revolutionising':1,'relapses':1,'squirting':1,'considering':1,'accumulating':1,'to':1,'taking':1,'people':1,'two':3,'.':1,'their':6,'cooling':1,'physicists':1,'calculations':1,'which':13,'dalton':1,'themselves':1,'variational':1,'reflex':1,'more':1,'introducing':1,'endeavour.':1,'that':2,'fire':1,'frost':1,'amphibians':1,'jellyfishes':1,'heat':2,'carrying':1,'blood.':1,'domestication.':1,'careful':1,'travelling':1,'those':1,'plants':2,'keeping':1,'migrants':1,'applying':1,'understanding.':1,'contracting':1,'solid':1,'thousands':1,'severe':1,'air-tubes':1,'air':2,'gills':2,'many':6,'growing':1,'making':2,'providing':1,'laplace':1,'clock-work':1,'imitation':1,'and':4,'firing':1,'roentgen.':1,'biologists':1,'almost':1,'j':19,'it':1,'an':6,'collision':1,'pressing':1,'grazing':1,'numbers':1,'planets':1,'sense':1,'anything':1,'any':2,'increased':1,'terrestrial':1,'sir':2,'different':2,'beginning.':1,'no':1,'studying':1,'tucking':1,'sending':1,'uranium':1,'ideas':4,'astronomers':1,'brian':2,'mr.':1,'strange':1,'geographical':1,'peoples':1,'over-population':1,'absorbing':1,'smell':2,'continuous':1,'accidental':1,'students':1,'amphibians.':1,'hand':1,'watching':1,'chance':3,'gravitation':1,'moving':1,'kin':1,'coercion':1,'successive':2,'fishes':1,'changing':1,'causing':1,'inconceivable':1,'moons':1,'man':4,'a':57,'night':3,'using':4,'fully':1,'pithecanthropus':1,'professor':7,'circumventing':1,'itself':3,'hungry':1,'sudden':1,'these':1,'peculiarities':1,'big-brained':1,'far':1,'fresh':1,'the':161,'starting':1,'drawing':1,'contingents':1},'analysing':{'light':4,'portion':1},'evolved--destined':{'in':1},'anything':{'and':1,'for':1,'was':1,'wot':1,'into':1,'else':1,'the':1,'with':1},'modernity':{'in':1},'nautilus':{'a':1,'nautilus':1,'pompilius':1,'is':1,'it':1,'186':3,'argonauta':2,'the':1,'hardly':1,'or':1,'are':1},'ear-bones':{'of':1},'deserves':{'to':1},'hatched':{'larvae':1,'salmon':1,'.':1,'bird':2,'in':1,';':1,'the':1},'repair':{';':1,'change':1},'into':{'flippers':2,'gold':1,'being':1,'ocean-troughs':1,'existence':1,'its':10,'masses':1,'lake':1,'forms':1,'internal':1,'combination-boxes':1,'sound':1,'his':1,'very':2,'dark':1,'boxes':1,'every':2,'shreds.':1,'this':2,'glass-eels':1,'activity':2,'freshwater':1,'unit-bodies':1,'reactions':1,'smaller':1,'radium':1,'some':2,'zones':1,'our':1,'canada':1,'organisms':1,'space':4,'definite':1,'safety':1,'new':2,'fragments':1,'red':1,'power':1,'water':1,'active':2,'simpler':1,'about':1,'many':1,'mutually':1,'connection':1,'one':4,'puzzle-boxes':1,'another':1,'thick':1,'little':1,'man--the':1,'distinct':1,'two':11,'their':3,'stars':1,'white':1,'energy':2,'empty':1,'continents':1,'account.':1,'heat':1,'races':1,'pieces':1,'plants':1,'these':1,'work':1,'britain':1,'this.':1,'matter':1,'gigantic':1,'something':3,'gas.':1,'it':5,'deep':1,'an':3,'as':1,'itself':1,'eras':1,'close':2,'mountain':1,'different':1,'things':1,'unity':1,'vital':1,'electrical':1,'which':2,'emphatic':1,'independent':1,'effect':1,'waves':1,'dust':1,'such':1,'extremely':1,'man':1,'a':24,'varieties':1,'electrons':1,'the':45},'encasements':{'with':1},'appropriate':{'action':1,'trigger-pulling':1,'trigger':1,'conditions':1,'one':1},'chalk-forming':{'animals':3,'foraminifera':1},'primarily':{'restricted':1},'repaid':{'when':1},'harnessed':{'electricity':1},'claspers':{'and':1},'spending':{'our':1},'gases':{'on':1,'from':1,'exposed':1,'of':1,'is':2,'in':1,'.':3,'spread':1,'can':1,'which':1,'between':1,'with':1,'into':1},'thirdly':{'every':1,'when':1},'double-armed':{'spiral':1},'burrow.':{'evolution':1},'suit':{'and':2,'of':2,'various':1},':':{'seasonal':1,'summer':1,'all':1,'skeleton':1,'photo':80,'magnetic':1,'rotating':2,'rischgitz':6,'disintegration':1,'its':1,'before':1,'death':1,'baron':1,'royal':8,'hermit-crab':1,'to':1,'only':1,'fig':11,'stephen':2,'darwin':1,'dead-leaf':1,'protective':2,'wave':1,'early':1,'falcon':1,'silk':1,'minute':1,'james':7,'cagcombe':2,'vortex':1,'h':6,'side-view':1,'greenland':1,'life-history':1,'national':2,'spoonbill':1,'yerkes':3,'astrophysical':2,'jupiter':1,'are':1,'leadbeater.':2,'conjectures':1,'what':2,'paintings':1,'ten-armed':1,'new':10,'discovery':2,'volvox':1,'variability':1,'we':3,'full':1,'reproduced':11,'underwood':2,'harvard':4,'ernest':2,'by':1,'suggested':1,'c':2,'improved':1,'g':6,'o':2,'whence':1,'pictorial':1,'hence':1,'origin':1,'pelican':1,'elliot':1,'surinam':1,'lafayette.':1,'proterospongia':1,'throughout':1,'from':13,'there':1,'imperial':4,'storm':1,'inclined':1,'flinty':1,'albatross':1,'photos':2,'true':1,'photograph':3,'avocet':1,'f':2,'this':1,'science':1,'mount':8,'j':24,'will':1,'w':22,'reproduction':1,'gambier':6,'making':1,'male':1,'laplace':1,'http:':1,'and':1,'nautilus':1,'is':1,'modern':1,'thus':1,'it':2,'surface':1,'an':5,'arrangements':1,'niagara':1,'british':12,'in':1,'woodpecker':1,'ascii':1,'if':1,'dying':1,'january':1,'six':1,'when':1,'puffin':1,'1':4,'how':2,'rischgitz.':2,'lafayette':1,'elliott':3,'lick':4,'hornbill':1,'electric':1,'okapi':1,'after':6,'diagram':5,'genealogical':1,'restoration':2,'such':1,'inconceivable':1,'man':1,'a':28,'natural':2,'for':2,'whenever':1,'light':1,'professor':3,'daily':2,'electrons':1,'english':1,'the':38,'egg':1,'wing':1},'opens':{'and':1,'many':1,'with':1,'up':1},'considerably':{'in':1,'less':1},'excavating':{'a':2},'elsewhere':{'as':1,'.':1,'in':1,'e.g':1},'inches':{'high':1,'square':2,'off':1,'of':1,'away':2,'long':5,'one':1,'shorter':1,'to':1,'below':1,'long.':1,'in':7,';':1,'per':1},'vicissitudes.':{'the':1},'slums':{'in':1},'moon--meteors':{'and':1},'archaic':{'mammals':1,'animal':1},'link':{'lives':1},'pacific':{'and':1,'golden':1,'west':1,'oceans':1,'oceans.':1,'ocean':1,'in':1},'legs.':{'illustration':1},'atom':{'and':5,'is':7,'within':1,'it':1,'as':2,'itself':1,'are':1,'in':2,'passes':1,'amounts':1,'there':1,'.':6,'to':6,'which':1,';':2,':':1,'was':3,'energy':1,'gives':1,'known':2,'such':1,'by':1,'a':1,'of':17,'can':1,'were':1,'the':4,'or':1},'coldest':{'places':1},'line':{'represents':1,'or':1,'from':1,'that':1,'of':21,'is':2,'capable':1,'but':1,'.':2,'to':1,'can':1,'altogether':1,'seen':1,'the':1,'gave':1,'with':2,'between':1,'across':1,'at':1},'considerable':{'and':1,'force':1,'mental':1,'evidence':1,'periods':1,'.':1,'strength':1,'uniformity':1,'heights':1,'dispersion':1,'results.':1,'degree':1,'loss':1,'fascination':1,'part':1,'effort':2,'distance':3,'amount':2,'magnitude':2,'time':2,'aid':1,'changes':1,'quantity':2},'posted':{'on':1,'with':3,'at':1},'open.':{'but':1},'ut':{'84116':1},'spectroscope':{'and':3,'reveals':1,'we':3,'enables':1,'splits':1,'for':1,'49':1,'any':1,'is':5,'in':1,'it':1,'an':1,'will':3,';':2,'can':1,'which':1,'sorts':2,'the':2,'.':3,'by':1,'shows':1},'burrows':{'circulating':1},'moths.':{'illustration':1},'us':{'and':6,'consider':2,'plainly':1,'feel':1,'is':2,'others':1,'phenomena':1,'back':2,'see':2,'through':1,'something':1,'directly':1,'in':2,'pulls':1,'precisely':1,'its':1,'select':1,'even':1,'better':1,'by':2,'for':2,'how':2,'inquire':1,'there':1,'when':1,'except':1,'.':11,'particles':1,'to':19,'take':2,';':1,'across':1,'picture':1,'return':2,'little.':1,'that':7,'very':2,'some':1,'stop':1,'bear':1,'indulge':1,'not':1,'with':3,'than':2,'a':8,'on':1,'about':1,'to-day':1,'remember':1,'this':1,'many':1,'as':2,'keep':1,'try':1,'turn':1,'so':1,'of':2,'the':3,'once':1,'say':2,'at':2},'paired':{'fins':1},'ball.':{'illustration':1},'mature':{'sperm-cell':1,'egg-cell':1,'animal':1,'.':1},'laplace':{'10':1,'s':3,'one':1,'spoke':1,'to':1},'side.':{'--i':1,'--1':1},'storing':{'fishes':2,'up':1},'genial':{'climatic':1},'aerial':{'and':1,'but':1,'journeys':2},'protrusive':{'lips':1,'face':2},'creature.':{'there':1,'sec':1},'defined':{'is':1,'primitive':1},'likewise':{'a':2,'have--there':1,'evolution':1,'react':1,'connected':1,'crumbs':1,'were':1,'simpler':1},'influence':{'and':2,'on':1,'of':5,'well':1,'retreats':1,'will':1,'in':1,'the':1,'or':1,'must':1},'surpassing':{'themselves':1},'char':{'that':1},'duration':{'of':2},'diverse':{'forms':2,'territory':1,'description':1,'angles':1,'results':1},'nautical':{'almanac':2},'pontobdella':{'an':1},'living.':{'some':1,'parental':1},'element.':{'two':1},'intrepid':{'explorers':1},'puzzling':{'and':1,'phenomenon':1},'tuft':{'as':1},'fixing':{'itself':1},'uranium':{'and':1,'then':1,'x.':1,'for':1,'would':1,'may':1,'should':1,'itself':1,'salt':1,'.':3,'spontaneously':1,'are':1,'in':1,'has':1,'changes':1,'by':1,'he':1},'preventing':{'their':1,'the':1},'close-packed':{'refractive':1},'conceptions':{'of':1},'points':{'one':1,'we':1,'that':1,'clearly':1,'of':4,'away':1,'back':1,'should':1,'to':2,'in':1,'forward':1,'.':1,'or':2,'out':3},'sails':{'for':1},'revision':{'.':1},'elements':{'a':1,'on':2,'commands':1,'for':1,'oxygen':1,'that':1,'may':1,'sun':1,'into':1,'in':2,'about':1,'.':2,'to':1,'as':2,'are':4,'have':1,'each':1,'it':1,'such':1},'small-brained':{'archaic':1},'energetic':{'particles':1,'men':1,'electrons':1,'actions':1},'beginnings':{'of':4,'.':1,'on':1},'sal-ammoniac':{'but':1},'faintly':{'lit':1,'visible':2},'bibliographies':{'appended':1},'habits--the':{'truly':1},'sides':{'and':1,'of':7,'nor':1,'to':1},'ago':{'and':2,'is':2,'in':3,'it':2,'as':1,'at':1,'178':1,'174':1,'for':1,'regarded':1,'when':3,'.':10,'to':1,'that':1,'may':1,'illustration':1,'they':1,'others':1,'with':1,'a':1,'showed':1,'the':4,'or':1,'are':1},'furthest':{'in':1},'land':{'and':3,'ran':1,'is':2,'surface':1,'skimming':1,'at':2,'have':1,'.':11,'bridges':1,'tending':1,'to':1,'there':1,'had':3,'actually':1,'also':1,'5':1,'between':1,'has':3,'was':2,'over':1,'meant':1,'but':1,'by':1,'continued':1,'than':2,'plants':1,'flora':1,'animals':10,'should':2,'animals--the':1,'leaving':1,'implied':1,'many':2},'sail.':{'the':1},'reasoned':{'discourse':2},'marble--there':{'are':1},'rescued':{'triumphantly':1},'diffraction':{'grating':2},'walked':{'about':1,'through':1},'cryptozoic':{'or':1},'opposing':{'the':1},'came':{'a':2,'about':6,'from':3,'barking':1,'into':1,'to':11,'slowly':1,'in':1,'first':1,'before':1},'harks':{'back':1},'fresh':{'waters--the':1,'racial':1,'contacts':1,'starts':1,'waters':2,'air':1,'water':7,'invention':1,'gulps':1,'offshoot':1,'supplies':1,'experiments':1,'expression':1,'or':2},'having':{'a':4,'little':1,'implies':1,'no':1,'comparatively':1,'somehow':1,'to':1,'only':1,'entangled':1,'planets':1,'not':1,'learned':1,'the':2},'placentals--show':{'a':1},'repeopled':{'by':1},'hampton':{'court':3},'code':{'of':1},'partial':{'counts':1,'eclipse':1,'or':1},'rubbish':{'is':1},'illustrates':{'very':1,'the':3,'part':1,'evolution':1},'scooped':{'the':1,'out':1},'knotted':{'spiral':1},'results':{'a':1,'what':1,'which':1,'of':6,'in':1,'.':2,'to':1,'are':2,'have':1,'were':1,'affecting':1,'the':2},'existing':{'lizards':1},'illustrated':{'and':1,'on':1,'when':1,'its':1,'in':1,'the':1,'by':3},'stops':{'struggling':1,'with':1,'its':1},'broader':{'palates':1},'dainty':{'and':1},'seemed':{'then':1,'for':1,'no':1,'almost':1,'to':2,'so':1},'tearing':{'small':2,'away':1},'club-mosses':{'and':1},'iii':{'adaptations':1,'.':2},'concerned':{'chiefly':1,'is':1,'here':1,'simply':1,';':1,'with':1},'hunger':{'and':2,'is':2,'in':1},'rufous':{'brown':1},'young':{'and':2,'emerge':1,'mound-birds':1,'reeds':1,'cheetahs':2,'water-bird':1,'fish':1,'woodpeckers':1,'orang':1,'foxes':1,'one':2,'crocodile':2,'as':1,'ducklings':1,'at':1,'in':2,'earth':1,'herring':1,'birds':5,'creatures':2,'eels':4,'described':1,'for':1,'liberated':1,'perhaps':1,'bittern':2,'frog':1,'.':4,'crocodiles':1,'fishes.':1,'fry':1,'bird':1,'elver':1,'then':1,'life':1,'thrush':1,'form':1,'that':1,'mammals':1,'ones':17,'twined':1,'text-book':1,'man':1,'a':1,'about':1,'animals':1,'turtles':1,'e.g':1,'this':1,'science':1,'frog-hopper':1,'toads':1,'moorhen':1,'plovers':1,'can':2,'mammal':1,'the':1,'stages':1,'are':3},'send':{'donations':1,'it':1,'out':2},'universes--':{'island-universes':1},'citing':{'these':1},'outwards':{'from':1,'for':1},'resources':{'and':1,'of':2,'upon':1,'are':1,'more':1},'inference.':{'on':1},'matter--other':{'new':1},'garden':{'on':1},'continues':{'to':3,'the':1,'sitting':1},'waters.':{'the':1},'mouth-parts':{'the':1,'.':1},'mixing':{'colours':4,'with':1,'in':1},'continued':{'and':1,'elevation':1,'conquest':1,'.':1,'to':3,'through':1,'in':1,'the':1,'over':1},'minerals':{'the':1,'.':1},'squids':{'various':1},'archaeopteryx':{'jurassic':1,'after':1,'.':1,'91':1,'the':1,'was':1},'earth-knot':{'of':1},'back-teeth':{'were':1},'anxious':{'warning':1},'race':{'because':1,'is':1,'depends':1,'well-defined':1,'owes':1,'if':1,'living':2,'would':2,'since':1,'.':9,'to':2,'which':1,'between':1,'was':1,'lived':1,'that':1,'after':2,'but':1,'includes':2,'they':1,'now':1,'by':1,'possess':1,'a':1,'of':3,'as':1,'without':2,'through':1,'or':3,'say':1},'trypanosome':{'which':2,'that':1},'others--the':{'placentals--show':1},'trypanosoma':{'gambiense':2},'mediterranean':{'region':1,'or':1,'for':1},'wavy-to':{'curly-haired':1},'unprofitable':{'for':1},'imply':{'enormous':1,'an':1,'ether':1,'it':1},'burrower':{'which':1},'munitions':{'which':1},'primeval':{'supporting':1,'coherence':1,'vegetation':1,'amphibians':1,'stuff':2},'make.':{'the':1},'that.':{'now':1},'apparatus':{'and':1,'for':3,'being':1,'of':1,'to':1,'which':1,'fine':1,'by':1},'waning':{'of':2,'remain':1},'expressed':{'by':1,'is':1,'.':1,'itself':1,'in':1,'along':1,'the':1},'hereditary':{'and':1,'enregistration':1,'obligations':1,'items':1,'pre-arrangements':1,'qualities':1,'capacity':1,'or':1,'enemies':1},'consistently':{'the':1,'presenting':1,'offer':1},'vapours--the':{'reversing':1},'indestructible':{'and':1,'it':1},'expresses':{'emotion':1,'the':1,'itself':2,'his':1,'its':1},'guinea-pigs':{'we':1},'bird':{'flies':1,'multiplying':1,'into':1,'dived':1,'it':1,'migration':1,'in':3,'feeding':2,'had':1,'sails':1,'.':5,'to':2,'without':1,'has':3,'was':2,'shows':1,'then':1,'we':1,'showing':2,'but':1,'with':1,'than':1,'about':1,'mimicry':2,'archaeopteryx':2,'of':6,'looked':1,'s':8,'allied':1,'the':1,'or':2,'hesperornis':2},'thin':{'dry':1,'atmosphere':1,'gas':1,'gases':1,'as':1,'sheets':1,'coatings':1,'out':1},'scenery':{'on':1,'effects':1,'if':1},'advantageously':{'sensitive':1},'scepticism':{'at':1},'led':{'eventually':3,'.':1,'to':7,'our':1,'was':1,'by':1},'license.':{'1.e.6':1},'convergences':{'and':1},'leg':{'to':1,'is':2,'but':1,'.':1,'broken':1,'in':1,'across':1},'respectively':{'.':1},'gathered':{'five':1,'together':1,'obviously':1},'dressed':{'but':1},'let':{'go':1,'the':2,'themselves':1,'them':2,'us':20},'octave':{'of':1},'consideration':{'of':2,'that':1},'invented':{'to':1,'cannot':1,'by':1,'something':1},'fifteen':{'thousand':1,'or':1,'miles':1,'in':1,'minutes':2,'feet--the':1},'physiology':{'and':2,'of':1,'would':1,'.':1},'darwinism':{'and':1},'substratum':{'on':1,'was':1,'.':1},'great':{'restriction':1,'evolutionary':2,'deliberateness':1,'effect.':1,'friction':1,'swooping':1,'philosopher':1,'skill':1,'speed':2,'projection':1,'resemblance':1,'patches':1,'density':1,'distances;':1,'auk':1,'storms':1,'improvement':1,'source':1,'collections':1,'majority':5,'division':2,'advantage':2,'advances':1,'oceans':1,'theme.':1,'coal-fields':1,'school':1,'clouds':1,'gift':1,'naturalist':1,'investigator':1,'aridity':1,'rocks':1,'excellence':1,'red':1,'truth':1,'waterfalls':1,'biological':1,'river':2,'italian':1,'dexterity':1,'wariness':1,'thinkers':1,'telescope':1,'deal':4,'series':1,'globe':1,'yerkes':1,'astronomer':1,'individual':1,'measure':1,'racial':1,'factors':1,'cerebral':1,'nebula':4,'southward':1,'ice':4,'abysses':4,'increase':1,'importance':4,'leap':2,'difficulties':3,'safety':1,'steps':8,'contrast':2,'claws':2,'beetling':1,'scientific':1,'power':1,'educability':1,'french':2,'difficulty':1,'reason':1,'extent':1,'congestion':1,'cities':1,'orb':1,'change':1,'advance':1,'search':1,'piece':1,'cavities':1,'pressure':1,'many':1,'step':5,'range':1,'comet':2,'canopy':1,'changes':1,'tongues':1,'groups':1,'unrest.':1,'height':1,'channels':1,'improvements':1,'doctrine':1,'illumination':1,'ridge':1,'service':2,'outbreaks':1,'depths.':1,'question':1,'nebular':1,'.':3,'swarm':1,'secret':2,'development':1,'interest':5,'brazilian':1,'length':1,'100-inch':1,'war':2,'fire-mists':1,'gaseous':1,'fiery':1,'quantities':1,'whirling':2,'it':1,'bulk':1,'part':3,'gain':1,'wheatfields':1,'abundance':1,'divisions':1,'fold':1,'deeps':2,'plain':1,'strides':1,'official':1,'value':1,'excitement':1,'sun-spot':2,'freedom':1,'refractors':1,'and':2,'tracts':1,'discovery.':1,'comet--the':1,'modern':1,'influence':1,'haunt':1,'haunts':1,'cluster':1,'as':4,'reptiles.':1,'glaciation':1,'numbers':1,'in':1,'diversity':2,'cleverness':1,'continents':1,'pink':1,'compared':1,'club-moss':1,'variety':3,'things':1,'forests':1,'flood':1,'electrical':1,'significance':1,'intelligence':1,'physical':1,'scarlet':2,'staying':1,'ball':1,'volumes':1,'disadvantages':1,'invasions':1,'gallery':1,'spot':1,'claw':1,'falls':1,'depths':2,'leaps':1,'invasion':2,'bustard.':1,'types':1,'acquisitions':2,'zooelogical':1,'accumulations':1,'complexity':1,'races':1,'mass':1,'fundamental':1,'velocity':1,'laboratories':1,'salt':1},'engage':{'the':1},'credits':{'every':1},'technical':{'section':1,'improvements':1},'involved':{'astronomers':1,'a':2,'this':1,'in':3},'resulting':{'from':1,'spectrum':1},'opinion':{'seems':1,'as':1,'now':1,'says':1,'about':1},'residents':{'in':2},'amphibians;':{'but':1},'pleistocene':{'perhaps':3,'period':2,'while':1,'era':1,'or':1,'before':1},'involves':{'a':1,'much':1,'hard':1,'nutritive':1},'holmes':{'kept':1,'writes':1,'poked':1},'chains':{'bind':1,'is':1,'or':1,'which':1},'halfpenny':{'it':1},'complying':{'with':3},'333':{'432':1},'mariners':{'before':1},'it--whatever':{'that':1},'hedgehog-like':{'test':1},'tools':{';':1},'fit.':{'at':1},'standing':{'stones':1,'on':1,'out':1,'with':1,'before':1},'bloweth':{'where':1},'recalling':{'even':1,'the':1},'whipping':{'in':1},'self-luminous':{'.':1},'next':{'set':1,'generation':1,'period':1,'grade':1,'stroke.':1,'year':1,'tooth':1,'to':2,'few':1,';':1,'article.':1,'notice':1,'that':1,'moult':1,'chapter.':1,'atom':1,'great':1,'room':1,'morning':1,'offshoot':1,'the':1,'page':1},'eleven':{'years':1},'doubt':{'and':1,'about':1,'for':1,'that':20,'whether':1,'many':1,'there':1,'some':1,'it':1,'as':7,'at':1,'the':1,'by':1},'animal.':{'illustration':1},'doubling':{'of':1},'midday':{'work':1},'pencil':{'on':1,'upon':1},'occurred':{'about':1,'without':1,'in':1,'the':1,'along':1,'more':1},'bodily':{'and':4,'life':2,'frame':2,'immortality':1,'attributes':1,'along':1},'carrying':{'a':1,'them':3,'her':2,'an':1,'the':1,'its':2},'extinction.':{'the':1},'baby':{'reveals':1,'orang':2,'had':1,'orang-utan':2,'chimpanzees':2,'learning':1},'balls':{'on':1},'animals':{'show':2,'abundant':1,'had':1,'should':1,'to':5,'overcome':1,'take':1,'division':1,'breathing':1,'showing':1,'cannot':1,'not':2,'monkeys':1,'like':6,'where':1,'enjoy':1,'illustrating':1,'often':1,'191':1,'began--a':1,'namely':1,'sec':1,'are':12,'living':5,'hide':1,'lead':1,'below':1,'tend':2,';':2,'we':2,'were':4,'however':1,'illustration':1,'sink':1,'put':1,'come':2,'on':2,'began.':1,'e.g':2,'of':7,'allied':1,'or':5,'secure':1,'physophora':2,'61':1,'1872':1,'protozoa':1,'illustrate':1,'from':2,'would':2,'there':4,'.':14,'live':2,'themselves':1,'was':1,'that':3,'but':1,'with':2,'must':2,'made':1,'these':1,'say':1,'remain':1,'learn':1,'called':1,'and':16,'do':1,'likewise':2,'is':6,'it':2,'as':1,'have':19,'in':5,'radiolarians':1,'thoroughly':1,'began':1,'burrow':1,'globigerinid':1,'which':7,'many':1,'important':1,'such':5,'man':1,'a':2,'lower':1,'especially':1,'together':2,'without':1,'the':5,'left':1},'retreated':{'northwards':1,'within':1},'this':{'freak':1,'impression':1,'selection':1,'phenomenon':1,'being':1,'when':1,'sporting':1,'leads':1,'distant':1,'consists':1,'earth':1,'oldest':1,'reasoning':1,'tendency':1,'seemed':1,'colony-making':1,'certainly':1,'outer':2,'advance--the':1,'work.':3,'common':1,'sheaf':1,'state':3,'instrument':2,'magnetic':1,'does':2,'has':5,'might':2,'over':1,'happened':1,'kingdom':1,'then':1,'good':1,'greater':1,'advantage':1,'means':5,'very':1,'period':5,'early':2,'hermon':1,'diary':1,'probably':1,'not':1,'world':2,';':1,'vapour':1,'organ':1,'progressive':1,'did':1,'pinch':1,'pillar':1,'dinosaur':1,'stuff':1,'she':1,'reasonable':1,'succession':1,'small':1,'ultra-violet':1,'movement':2,'page':1,'view':3,'system':1,'the':6,'namely':1,'picture':2,'colossal':1,'garment':1,'globe':1,'notochord':1,'persistent':1,'relative':1,'second':1,'owing':1,'result':1,'mirror':1,'ruse':1,'belief':1,'blue':1,'project':3,'still':1,'for':1,'waning':1,'distinctive':1,'away':1,'thickness':1,'case':8,'time.':1,'race':1,'vascular':1,'new':2,'falling':1,'before':1,'method':2,'law':1,'discovery':2,'body':1,'variability':1,'wheat':1,'theory':9,'fish':1,'creature--far':1,'applies':2,'agreement':16,'possibility':1,'like':1,'extraordinary':1,'surely':1,'web':1,'marquis':1,'vigorous':1,'path':1,'estimate':2,'respect':2,'by':1,'change':2,'stage':1,'chapter':1,'on':1,'great':3,'substance':1,'license':2,'argument':1,'of':2,'motion':3,'quaint':1,'range':1,'regular':1,'lively':1,'pictorial':1,'argue':1,'makes':2,'or':1,'inference':1,'family':1,'point':9,'simple':3,'image':1,'within':2,'colony':1,'number':1,'incessant':2,'will':2,'fiery':1,'raises':1,'littoral':1,'inorganic':1,'drawing':2,'electronic':3,'attendant':1,'sympathetic':1,'little':1,'ancient':1,'lens':2,'would':2,'attraction':1,'important':1,'outline':5,'question':3,'spiral':1,'.':2,'immense':1,'wonderful':2,'low':1,'statement':1,'ocean':1,'mysterious':1,'australian':1,'scheme':1,'was':15,'energy':7,'minor':1,'gives':1,'sort':2,'direction':1,'partly':1,'way':11,'that':4,'explanation':1,'continuous':1,'gas':1,'took':1,'but':1,'haunt':1,'implied':1,'instrument.':1,'reason.':1,'particular':1,'implies':3,'rivalry':1,'white':2,'must':2,'steel':1,'pull':3,'kind':5,'made':1,'conception':1,'conviction':1,'characteristic':1,'work':11,'sifting':1,'air':1,'planet':1,'below':1,'paragraph':1,'fertilisation':1,'can':3,'cannot':1,'were':2,'merely':1,'property':1,'x-ray':2,'distance':6,'and':3,'layer':2,'constant':1,'resemblance':1,'century':1,'process':1,'molecular':1,'is':63,'modern':1,'turned':1,'it':5,'swarm':1,'an':1,'sample':1,'cluster':1,'as':1,'ether':1,'at':2,'file':2,'sense':3,'relic':1,'mysteriously':1,'apparently':1,'internal':1,'film':1,'absolute':1,'again':2,'law.':1,'moves':1,'twofold':1,'woodpecker':1,'age-old':1,':':2,'eloquent':1,'radiation':1,'thorough':1,'any':1,'note':1,'field':1,'strange':2,'inquiry':1,'ante-natal':1,'answer':1,'subject':1,'shows':1,'conclusion':1,'tension':1,'neolithic':1,'book':3,'living':1,'may':7,'ebook':6,'to':3,'diagram':2,'scale':2,'nucleus':1,'purpose':2,'position':1,'discharge':1,'bodily':1,'opportunity':1,'wonder-world':1,'a':1,'in':2,'amoeboid':1,'observation':1,'imply':1,'light':1,'voice':1,'shift.':1,'dog':1,'obviously':1,'points':1,'principle':1,'time':2,'velocity':1,'effect':2,'egg':1,'order':1,'fact':4},'cuvier':{'1769-1832':2},'pour':{'from':1},'reproduce':{'it.':1,'tell':1},'publications':{'as':1},'of':{'dissolution':1,'comparatively':1,'four':4,'straws':1,'chameleons':1,'electricity':18,'ceylon':1,'out-breeding':2,'lord':1,'arboreal':4,'pigment':2,'thinopus':1,'every':2,'radio-active':3,'vastly':1,'monkeys':5,'kataleptic':1,'unrelated':1,'relics':3,'venus':5,'clothes':1,'force':2,'senescence':1,'infancy':1,'direct':1,'surrounding':1,'second':1,'microscopists':1,'even':1,'change.':1,'organisms':2,'thunder':1,'nature.':2,'asia':1,'children':2,'change;':1,'salt-accumulation':1,'fossil':1,'new':6,'increasing':3,'ever':2,'men':7,'unexhausted':1,'atoms':25,'anthropology':1,'100':1,'cardboard':1,'dry':2,'luther':1,'light.':3,'smoke':1,'changes':1,'golden':1,'feelings':1,'patience':1,'negative':5,'civilisation.':1,'telegraph':1,'thorndike':1,'musk':2,'x-rays--the':1,'glass':3,'continual':3,'things.':1,'93':1,'92':1,'work':3,'mammalian':1,'parachuting--a':1,'mr':1,'radiance':2,'india':1,'corroborating':1,'present-day':2,'absolute':1,'reptiles--snakes':1,'nuts':1,'damages.':1,'how':2,'messrs':1,'ordinary':1,'after':1,'vicious':1,'long-continued':1,'parallel':1,'types':1,'effective':1,'carbonic':1,'order':1,'wind':1,'over':7,'crumbs':1,'symmetry':2,'bodies--evolution':2,'better':2,'them':36,'widely':1,'penetration':2,'molecules.':1,'pinkish':1,'silver':1,'oxygen':7,'brightness':1,'each':10,'telescope':2,'spider':2,'parasites':1,'armour--the':1,'hive-bees':1,'forty':1,'particles':3,'heavenly':1,'millions':6,'stamping':1,'turning':1,'monkeys--activity':1,'eternal':1,'strata':3,'free':2,'sensory':1,'struggle':1,'mastering':1,'calcareous':1,'detecting':3,'monkey':2,'enormous':2,'perhaps.':1,'cosmic':1,'days':1,'hearing':4,'another':3,'scissors':1,'thick':1,'electronic':4,'mercury':2,'ten':2,'pelagic':1,'legs':3,'dogs':1,'hydatina--has':1,'project':8,'matter':67,'torpedo-net.':1,'iron':10,'feeling':3,'oxygen-capture':1,'mind':10,'spectrum':1,'controversy.':1,'oxygen-combustion':1,'relatively':1,'affairs':3,'snow':3,'metallic':1,'chitin':2,'australia--all':1,'knowledge--the':1,'blue':1,'anatomy':1,'drought':2,'nutritive':3,'observation':1,'fitter':1,'professor':4,'metal':1,'swamps':1,'dover':1,'pollen':1,'hunger':1,'insects':8,'nerve-cells':3,'counteractive':1,'lessons':1,'latent':1,'sugar':1,'structure.':1,'fluid':1,'energy--what':2,'tuberculosis':1,'saturn':2,'dr':1,'to-day--the':1,'fields':1,'shape':1,'progress.':2,'architecture':2,'freshwater':1,'steam':3,'head-brains':1,'radium':15,'testing':1,'combustion':2,'rings':1,'artificial':1,'paternal':1,'luminescent':1,'finger':1,'caves':1,'profitable':1,'nature':18,'were':2,'wear':1,'carbon':1,'flowering':3,'caledonia':1,'out-flowing':1,'climate':3,'air--a':1,'distinction':1,'inquisitive':1,'tons':2,'250':1,'merchantibility':1,'three':2,'quickly':1,'much':4,'sponges':1,'parents':1,'life':50,'in-breeding':2,'chili':1,'air':8,'horse-power':1,'zoologists':1,'balance':1,'amphibians--the':1,'remembering':1,'seven':1,'is':1,'it':16,'brake':1,'in':1,'comparative':1,'things':5,'daughter-units':1,'damages':1,'colonies':1,'capacities':1,'typhoid':1,'rain':1,'hand':1,'kin':1,'patagonia':1,'turtle-backs':1,'opportunity':1,'butter':1,'engrained':1,'neptune':1,'contact':1,'greatest':1,'the':1665,'kinship':1,'deep-red':1,'indigo':2,'newton':2,'disguise':3,'human':9,'life-preserving':1,'yet':1,'evolution.':5,'vibration':1,'leibnitz':1,'alchemy':1,'transformed':1,'innocent':1,'humanity':1,'survival':1,'possible':3,'it--for':1,'desire':1,'melting':2,'insurgence':1,'plants--romance':1,'haunts--such':1,'homing':1,'people':1,'dead':2,'deflection':1,'jupiter':5,'escape':1,'animate':4,'proceeding':1,'ice':1,'everything':1,'conquering':2,'man--body':1,'palatable':1,'losing':1,'self-preserving':1,'primitive':4,'successive':3,'obtaining':2,'intellectual':1,'bats':2,'palaeozoic':1,'support':2,'flying':2,'jealousy':1,'sunlight':2,'grasping':1,'head':2,'forming':4,'becoming':3,'heat':14,'solar':1,'crystal':1,'meteorites.':1,'temper':1,'paragraphs':1,'muscular':1,'evidence':2,'prayer':1,'physical':1,'discriminate':1,'lungs':1,'inborn':1,'no':4,'font-de-gaume':2,'reality':1,'tin':1,'holding':1,'smell':5,'white-hot':2,'clear-cut':1,'diet':1,'rising':1,'authorities':1,'to-day':15,'potato':1,'time':10,'serious':1,'remarkable':2,'colour-change':2,'varying':1,'computation':1,'skin':7,'passage':1,'reptiles':6,'protective':3,'exact':1,'feeble':1,'minute':5,'level':1,'magnet':1,'coincidences':1,'excellence':1,'slouching':1,'backboneless':2,'speculation':1,'perceptual':2,'tortoises':1,'thinkers':1,'radium.':1,'mind--even':1,'bacteria':1,'water-plants':1,'constitution':1,'uniform':2,'wave-motion':1,'falling':1,'flame.':1,'tibet':1,'hairs':1,'mauer.':1,'water':19,'meteorites':3,'magnetism':1,'galileo':1,'change':4,'box':1,'brilliant':1,'smoke-like':1,'exploitation':1,'sex--beginning':2,'ineffective':1,'locomotion':2,'useful':2,'relations.':1,'illumination':1,'sympathetic':1,'working':2,'positive':8,'uncritical':1,'france':3,'prey':2,'assimilation':1,'cases':2,'capturing':2,'haddington':1,'avoiding':1,'nature--on':1,'inveterate':1,'stature':1,'following':1,'making':4,'warm-bloodedness':1,'breeds':1,'spy':1,'development--that':1,'238':1,'mankind--steps':1,'hydrogen':9,'rays':3,'winter':1,'condensation.':1,'species':4,'vital':3,'huge':2,'may':1,'mankind':3,'such':9,'man':52,'natural':6,'neck':1,'liquid':1,'st':1,'lagoon':1,'years':25,'course':35,'experiments':1,'cold':3,'still':3,'birds':13,'limbs':1,'apes':3,'forms':1,'physics--research':1,'ours':3,'fire-mist':1,'years--but':1,'tails':1,'half':1,'twilight':1,'name':1,'times':4,'creation.':1,'establishing':2,'rock':1,'square':1,'elephants':1,'receipt':2,'prisms':2,'woodcraft':1,'catching':1,'entering':1,'wheat--changes':1,'living':17,'space':10,'these--which':1,'looking':3,'receiving':1,'picture-logic':1,'california':1,'marine':1,'advance':2,'sparrows':1,'language':1,'tree-sloths':1,'british':1,'motion':6,'thing':1,'deep-sea':1,'learning.':1,'adventure':4,'surviving':1,'coming':1,'one':18,'gases':1,'them--':1,'field-voles':1,'rome':1,'size':2,'little':5,'man--the':1,'anyone':2,'cooling':1,'2':1,'alfred':1,'white':1,'exploring':1,'that':14,'centipedes':1,'flowers':1,'eohippus':1,'12':1,'meteors':5,'third':1,'sailing':1,'three-spined':2,'trekking':1,'cards':1,'gigantic':3,'wandering':1,'and':3,'gathering':1,'chlorophyll':1,'psychical':1,'any':20,'1903.':1,'bavaria':1,'coal':3,'efficient':1,'physiologists':1,'equipment':1,'potential':1,'hydrogen--which':1,'invertebrate':1,'printed':1,'men--conspicuous':1,'america':2,'greyish':1,'dragon-flies':1,'average':1,'later':1,'science.':2,'wing':1,'salt':2,'precise':2,'far-reaching':1,'bright':2,'uranus':1,'slow':2,'only':1,'wood':1,'flood.':1,'awareness':1,'masking':1,'space.':1,'nearly':3,'lighter':3,'primates':2,'aluminum':1,'miles':13,'girdles':1,'vision':4,'famine':1,'weapons--the':1,'registering':1,'ways':2,'definite':2,'colours':2,'man.':7,'crookes':1,'vertical':1,'parental':10,'style':1,'dome':1,'rapidly':1,'cities':1,'vaporous':1,'many':15,'contract':1,'disappointment':1,'equatorials':1,'expression':2,'radio-activity':3,'bricks':1,'colony':1,'ants':2,'60':1,'air-breathing':2,'straws.':1,'learning':3,'67':1,'extinct':2,'technicalities':1,'one-celled':2,'mars':10,'reflex':2,'500':2,'observers':1,'external':1,'attentive':1,'diffuse':1,'those':9,'sound':1,'specialised':1,'these':71,'danger.':1,'life.':5,'mound':1,'trackless':1,'sudden':1,'ferns':1,'rock-cod':1,'helium':2,'everyday':1,'movements':1,'different':15,'lava':1,'shifts':2,'speech':1,'intermediary':1,'noble':1,'oil':6,'arctic':2,'insects.':1,'persons':1,'fruit':2,'delicate':1,'waves.':1,'implements':1,'fixing':1,'bodies':2,'summer':1,'being':8,'slime':1,'actions':1,'violent':3,'touch':1,'water-basins':1,'death':3,'thinking':4,'rose':1,'geological':1,'clay.':1,'4':3,'grip':1,'around':1,'larva':1,'crustaceans':1,'dark':3,'quickness':1,'using':1,'meaning':1,'acute':1,'fossils':2,'heat-waves':1,'heredity':2,'lightning':1,'donations':1,'coal--a':1,'chronology':1,'racial':3,'ascent':2,'self-effacement':1,'semotilus':2,'critical':1,'expressing':1,'transmutation':2,'measuring':1,'iron-forming':1,'wheat':2,'scientific':3,'uneasy':1,'sixty':2,'stone':2,'beavers':1,'chamberlin':2,'mutually':1,'corals':1,'or':3,'cambridge':2,'goethe':1,'communication':3,'electricity.':1,'wave-movements':1,'your':1,'mental':2,'her':8,'camouflaging':1,'dispersion':1,'low':1,'stars':16,'energy':35,'continents':1,'wits':1,'mammals':9,'water-vapour':1,'practically':1,'grass':1,'taste':2,'certain':5,'deep':1,'general':2,'as':1,'lichen':1,'associating':1,'planets':1,'retiring':1,'meteorites--pieces':1,'deviation':1,'separate':1,'teeth':2,'fresh':1,'rainbow-colour':1,'building':3,'condensation':2,'remote':1,'bilateral':1,'dislodgment':1,'starting':1,'all':34,'suns':1,'worms':2,'seals':1,'zinc':4,'reasoning':1,'careful':1,'red-hot':2,'meteorites--a':1,'wyoming':1,'postglacial':1,'devonian':1,'very':6,'combustible':1,'fat':1,'coloured':2,'trillions':5,'interpreting':2,'instinct.':1,'condition':1,'elusiveness.':1,'prolonged':2,'large':4,'dinosaur':1,'sand':2,'small':10,'mount':2,'rats':1,'methodical':1,'past':2,'invention':2,'1904-5':1,'further':1,'creatures':2,'babylonia':1,'what':25,'sun':1,'emotions':1,'thickness':1,'public':1,'movement':7,'condensed':1,'escaping':1,'malaria':1,'answers':1,'behaviour':14,'1843':1,'compliance':2,'experimenting':3,'miniature':2,'social':2,'action':2,'matter--but':1,'sticking':1,'family':3,'transit':1,'africa':1,'inorganic':2,'eye':1,'discriminative':1,'distinct':1,'petroleum':1,'two':7,'comparing':1,'promoting':2,'minor':1,'more':5,'horses':2,'substances':2,'chimpanzee':2,'particular':2,'stampings':1,'weathering':1,'science':29,'nine':1,'spontaneous':1,'beautiful':1,'messages':1,'stinging':3,'niagara':3,'sharp':1,'flint':1,'offspring':2,'terrestrial':6,'viviparity':1,'glowing':7,'civilisation':2,'germinal':1,'blood':1,'waves':10,'prospecting':1,'a':310,'life-forms':1,'pithecanthropus':8,'sun-spots':2,'renewing':1,'shore':1,'tentacles':2,'cases.':1,'perception':2,'healthfulness':1,'music.':1,'egg':2,'playing':2,'paper':3,'existence':1,'its':73,'club-mosses':1,'25':2,'26':1,'20':1,'solving':1,'gentleness.':1,'late':1,'microscopic':3,'it.':1,'good':2,'food':13,'compound':1,'association':4,'instructions':1,'mystery':1,'exquisite':1,'predatory':1,'heavy':1,'england':2,'restless':2,'nitrogenous':1,'fish':1,'hard':1,'energy.':1,'trilobites--jointed-footed':1,'neanderthal':3,'research':1,'nautiloids':2,'safety':3,'7':1,'celebes':1,'meteoric':2,'rejuvenescence':1,'bass':1,'extraordinary':2,'reason':2,'rainbow-tinted':1,'metamorphosis':1,'computers':1,'round':1,'copper':4,'limestone':1,'mimetic':1,'soapy':1,'star-clouds':1,'earthworms':1,'horse':3,'temperature':6,'twenty':2,'186':4,'gibraltar':1,'einstein.':1,'molecular':1,'aristocracy':1,'relationship':1,'1919':1,'1918':1,'part':1,'half-made':1,'sheer':2,'dissection--or':1,'egg-cells':2,'messrs.':1,'ages':7,'germ-cells--the':1,'atoms--the':2,'flaming':2,'scotland':2,'moist':1,'labour':6,'useless':2,'sea-perches':1,'eggs':7,'most':5,'achievement':1,'branching':1,'galway':1,'evolution--factors':1,'mobile':1,'seething':1,'electrons':32,'physics':6,'lying':2,'stones':1,'hoar-frost':1,'gold':6,'disturbances':2,'to-day.':1,'hereditary':3,'fine':1,'giant':2,'securing':1,'mauer':1,'nervous':2,'fishes--the':1,'less':1,'gills':1,'darwin':3,'his':27,'trees':2,'germ-cells':2,'rest':1,'instinctive':5,'silk':4,'stone.':1,'birds.':1,'common':2,'activity':2,'experiments;':1,'body':4,'art':1,'intelligence':12,'sex':1,'individual':5,'aberdeen':1,'practice':1,'gravitation':3,'pictures':2,'classes':1,'various':8,'conditions':1,'europe':3,'responses':1,'craters':1,'invisible':1,'both':2,'attainment':1,'foreign':1,'tactility':1,'amoeba':2,'experimental':1,'distress':1,'supply':1,'simple':3,'whatever':2,'whelk':2,'unicellular':1,'incandescent':1,'zeta':2,'decline':1,'damp':1,'brick':1,'meeting':1,'treatment':1,'modern':20,'flight':11,'fire':3,'gas':8,'amphibians':8,'reason.':1,'magnetised':1,'plants':4,'opportunity.':1,'solid':4,'straight':1,'ape-like':1,'lenard':1,'moth':1,'itself':2,'currents':1,'saline':1,'communal':1,'trial':2,'pecking':1,'yucca':1,'higher':5,'development':3,'brooding':1,'moving':4,'birch':1,'recent':5,'lower':2,'luminescence':1,'sight.':1,'chickens':1,'concrete':1,'body-building':1,'pigeons':2,'matter.':4,'space;':1,'atomic':1,'matter;':1,'praying':1,'letting':1,'cut':1,'internal':5,'deliberately':1,'heidelberg':3,'chess':1,'australia':7,'reptilian':1,'showing':1,'stockholm.':2,'life--a':1,'wings':1,'insect':1,'ponds':1,'individuals':1,'mathematical':2,'methods':1,'spring':1,'creation':4,'some':25,'yolk':3,'sight':3,'curious':1,'sieves':1,'pitchblende':2,'civilization':1,'300':2,'lakes':1,'tidal':2,'starlings':1,'intense':1,'analysing':1,'feigning':1,'prothyl':1,'modernity':1,'deepish':1,'chaps.':1,'naturalists':1,'chalk-forming':2,'deep-violet':1,'statistics':1,'placing':1,'long':3,'mimicry':2,'mountains':1,'inches':1,'adjusting':1,'frost':1,'fisheries':1,'atom':1,'energy--traceable':1,'migrating':1,'considerable':2,'hair':1,'skull':2,'characteristic':2,'spectroscope':1,'sifting':3,'us':3,'similar':2,'non-living':1,'flow':1,'sepia':1,'warning':2,'dragging':1,'whirligig':2,'tentative':1,'heat.':1,'endurance':1,'uranium':3,'occasional':1,'explaining':3,'elements':2,'energetic':1,'problems':1,'astronomy.':1,'allowing':1,'fishes':11,'cuttlefish':1,'structure':3,'temperament':1,'land':4,'reasoned':2,'age':1,'attaining':2,'conjugal':1,'ready-made':1,'knotted':1,'existing':1,'disintegration':1,'rufous':1,'young':2,'stable':1,'indicating':1,'breathing':1,'matter--other':1,'moribund':1,'putting':3,'intelligence--of':1,'minerals':1,'race':1,'smaller':1,'gripping':1,'rivers':2,'fermenting':1,'unavailable':1,'opaque':1,'giving':2,'slight':1,'habituation':1,'atoms--different':1,'experiment':1,'bird':1,'scenery':1,'let':2,'fifteen':1,'physiology':1,'extreme':1,'great':21,'evolution--the':1,'amphibians.':1,'haunts':1,'leaving':1,'evading':2,'stars--the':3,'opinion':2,'marmosets':1,'it--whatever':1,'tools':1,'cloud':2,'lime':2,'use':2,'from':4,'doubt':1,'contentment':1,'crab':1,'oily':1,'visibility':2,'bodily':1,'opposing':1,'animals':21,'this':81,'us.':1,'crickets':1,'reeds':2,'calculation':1,'high':3,'birnam':1,'something':4,'water.':3,'sir':7,'counting':1,'six':2,'animal':17,'hormones':2,'intelligent':4,'tension':1,'maternal':1,'them--simple':1,'sugar-bird':1,'primers':1,'tethering':1,'light':49,'lines':1,'predacious':1,'evolutionary':1,'unpalatable':1,'130':1,'agricultural':1,'ease.':1,'burning':1,'la':2,'water-weed':2,'surgeons':1,'vibration.':1,'labor':1,'instruments':1,'derivative':1,'greater':1,'material':2,'billiard':1,'rotation':2,'day':1,'worlds':2,'profound':2,'slipping':1,'truth':2,'pools':1,'lung':1,'evolution--how':1,'doing':3,'cultivated':2,'whitish':1,'books':2,'separating':2,'our':53,'sexual':1,'special':2,'gossamer':4,'time.':1,'exporting':1,'red':7,'lizzie':2,'electricity--electric':1,'mares':1,'organic':4,'behaviour.':2,'south':1,'disembodied':2,'activity.':1,'quality':2,'ancient':5,'nebulae':3,'all--the':1,'their':48,'nebular':1,'time--man':1,'mankind--notably':1,'hearing.':1,'inner':1,'x-rays':9,'negro':1,'manipulation':1,'branches':1,'july':2,'shrapnel':1,'isolation':1,'reproduction':1,'negatively':1,'steep':1,'poisons':1,'apparently':1,'food-supply':1,'gravity':2,'which':46,'unsettled':1,'soap':2,'vegetation':4,'digestive':2,'cracking':1,'preliminary':2,'sally':1,'dorsal':1,'volunteers':1,'disease':1,'mechanical':3,'mother-of-pearl':1,'fact':2,'atmosphere':1,'charles':1,'woolly':1,'seaweed':3,'utter':1,'fear':1,'trying':1,'knowledge':4,'millennia':1,'surroundings':1,'spontaneity':1,'molecules':3,'emitting':1,'thousands':6,'means':1,'perfection':2,'words':2,'crabs':1,'evolution':46,'brain':1,'numerous':1,'amphibia':1,'light--is':1,'view':8,'multiplying':3,'elusiveness':2,'powder':1,'violet':2,'humane':1,'wire':2,'genius':1,'mind.':3,'identification':1,'routine':1,'progress':2,'open-sea':2,'joy':1,'agencies':1,'pilgrims':1,'equal':2,'migration.':1,'passing':3,'preparedness':1,'stars--to':1,'sea-worms':1,'tremendous':1,'armadillos':1,'immense':1,'waste':1,'phosphorescent':1,'antlers':1,'sex--emotions':1,'environment.':1,'tactics--self-effacement':1,'an':58,'volunteer':1,'economised':1,'asexual':1,'air-tubes':1,'britain':1,'wild':2,'almost':1,'surface':1,'zoophytes':1,'perhaps':1,'forceps':1,'ante-natal':3,'habitats':1,'locomotion.':1,'neolithic':2,'lichen;':1,'cubic':1,'clouds--some':1,'colouring':1,'dust':4,'britain.':1,'whale':2,'poultry':1,'colour':8,'nebulous':2,'thought':3,'position':4,'flesh':1,'domestic':1,'radium--the':1,'sea-dust':2,'skill':2,'rapid':2,'battery':1,'slits':1,'government':1,'utah':1,'mistake.':1,'facial':1,'backboned':2,'perpetual':1,'electrons.':4,'works':1,'soft':2,'inexperienced':1,'replacement':3,'feelers.':1,'phenomena':2,'gossamer.':1,'ideals':2,'homo':1,'kinds':2,'peter':1,'recognition':1,'lead':1,'cabbages':1,'ether':3,'mutation':1,'reaching':1,'cellulose':1,'stellar':2,'pressure':2,'enregistering':1,'instinct':4,'about':8,'rare':1,'getting':5,'mendelism':1,'biscuit':1,'sea-horse':1,'swimming':1,'warranty':1,'reptile':1,'washington':1,'promise':1,'registration':2,'protozoa':2,'properties--ready':1,'mississippi':1,'spiral':2,'invisibility':5,'fundy':1,'north':2,'interest':3,'surgeons.':1,'hundreds':2,'shark-like':1,'marquis':2,'cells':3,'variations':1,'graphite':1,'penetrating':1,'rabbits':2,'universal':1,'reptiles.':1,'periods':1,'ink':1,'crystals':2,'agriculture':1,'40':1,'other':7,'branch':1,'disposing':1,'star':1,'tides':4,'astronomy':5,'coloration':1,'association--why':1,'15-20':1,'liver':1},'newts':{'and':1},'scatter':{'over':1,'them':1},'weaker':{'stocks':1},'bent':{'out':2},'reeds':{';':1,'the':1,'are':1,'143':1},'process':{'and':2,'by':1,'like':1,'for':1,'may':1,'of':22,'is':2,'had':1,'.':3,'does':2,'went':1,'has':2,'was':1,'the':1,'advanced':1},'lock':{'that':1},'slim':{'contracting':1},'purposes':{'of':1,'which':1,'.':1},'pieces':{'and':1,'because':1,'of':11,'is':1,'.':1,';':1},'high':{'and':2,'rounded':2,'authority':1,'rate':1,'frequency':1,'something':1,'speed':2,'forehead':1,'temperature':1,'there':1,'.':3,'chemical':1,';':2,'mountains':2,'degree':1,'water':5,'foreheads':1,'perfection':1,'places':1,'level':3,'grounds':1,'at':1},'slip':{'down':1,'into':1},'class.':{'a':1},'educational':{'corporation':1},'sand-grouse':{'into':1},'mutually':{'beneficial':4},'destroying':{'sheep':1},'cycads':{'and':1,'our':1,'which':1},'astronomers':{'rely':1,'regard':1,'calculate':1,'wondered':1,'that':1,'of':1,'believe':4,'who':2,'prefer':1,'we':1,'however':1,'to':2,'now':1,'have':4,'in':1,'hold':1,'.':1,'think':6},'pair':{'of':5},'animal':{'and':6,'settles':1,'often':1,'family':1,'intelligence':1,'is':10,'it':1,'accumulates':1,'one':1,'as':2,'in':2,'frequents':1,'plankton.':1,'life--story':1,'well':1,'will':1,'enters':1,'from':1,'world...':1,'world--even':1,'ways':1,'heat.':1,'except':1,'.':3,'to':2,'or':3,'which':1,'youth.':1,';':1,'has':3,'divides':1,'more':1,'kingdom':4,'play':1,'complete':1,'may':4,'about':1,'but':1,'aware':1,'behaviour':6,'heat':1,'races':1,'lives':2,'tended':1,'somewhat':1,'instinct':2,'world':1,'with':2,'population':3,'a':3,'evolution':1,'microbes':1,'of':4,'could':1,'depending':1,'life':8,'behaviour.':4,'like':6,'remains':1,'s':3,'can':1,'man':1,'trypanosome':1,'the':1,'makes':2,'called':2},'hormones':{'has':1,'or':2,'which':1},'mysteries':{'of':1,'the':1,'which':1,'.':1},'palates':{'than':1},'establishment':{'of':13},'paler':{'type':1},'yellowish':{'then':1,'tinge':1},'stow':{'them':1},'await':{'an':1},'tied':{'on':1},'purpose.':{'1.f.5':1},'permanent':{'inhabitants':1,'caterpillar':1,'as':1,'future':1,'markings':1,'in':1,'residents':2},'lines.':{'these':1,'in':1},'men--primitive':{'men--races':1},'fits':{'the':1},'cabbage':{'found':1},'hawk':{'moth':1},'solidarity':{'with':1},'varied':{'from':3,'face':1,'electrical':1,'at':1,'in':1,'stock':1},'ingersoll':{'s':2},'voracity':{'.':1},'prawns':{'and':2},'element':{'from':1,'giving':2,'is':3,'after':1,'uranium':1,'.':3,'as':1,'going':2,'can':1,'in':7,'known':1,';':1,'into':1},'allow':{'them':1,'for':1,'disclaimers':1,'chemical':1,'part':1,'the':3,';':1},'okapi':{'and':2,'is':1,'was':1},'alloy':{'that':1},'food-canals':{'to':1},'volunteers':{'and':4,'associated':1,'with':1},'moulton.':{'according':1},'counted':{'the':1,'by':1,'for':1,'.':1},'archimedes':{'.':1},'thigh':{'on':1},'produces':{'a':2,'the':2,'only':1,'tides':2,'its':1},'frontispiece.':{'illustration':1},'phalanger':{'flying':1},'peck':{'their':1,'without':1},'move':{'on':1,'about':4,'towards':1,'up':1,'to':1,'through':1,'at':1,'in':1,'the':1,'with':1,'across':1},'produced':{'a':1,'on':2,'and':1,'by':13,'in':2},'nerve-cord':{'.':1},'existence.':{'when':1,'5':1,'if':1},'triassic':{'blue':1,'reptile':2,'for':1,'mammals':1,'when':1,'period':2,'era':1,'attained':1,'precede':1},'perfect':{'weather':1,'.':1},'saturn':{'and':1,'886.0':1,'is':3,'next':1,'itself':1,'uranus':1,'in':1,'november':1,'revolve':1},'broiling':{'heat':1},'progeny':{'from':1},'surgeons':{'of':1},'equalise':{'temperatures.':1},'coral-reefs':{'where':1,'are':1},'hermit-crab':{'and':3,'which':1,'stock.':1,'fixes':1,'s':1,'passed':1,'with':2},'meantime':{'with':1},'degrees':{'a':1,'from':1,'of':2,'.':1,'below':1,'centigrade':1},'spoiling':{'the':1},'instruments':{'and':2,'multiplied':1,'great':1,'used':1,'would':1,'for':1,'have':1,'of':2,'.':2,'as':1,'cannot':1,'sec':1,'are':2,'which':1,'or':1,'can':1},'tubeful':{'of':1},'derivative':{'works':3},'forest':{'and':1,'life':1,'to':1,'tract':2,'.':2,'primeval.':1,'in':1,'was':1},'rill.':{'no':1},'piecing':{'together':1},'existences':{'such':1,'which':1},'outlined':{'it':1,'.':1},'innermost':{'region':1},'ship':{'and':1,'when':1,'without':1,'through':1,'.':1},'billiard':{'table':1,'balls':1},'snake':{'to':1,'dasypeltis':1,'with':2,'pushes':1},'rotation':{'on':1,'increased':1,'caused':1,'it':1,'.':3,'of':6,'than':1},'cage':{'professor':1,'in':1},'realize':{'the':1},'intelligent':{'and':2,'control':1,'use':1,'interest':1,'they':1,'efficiency':1,'educability':1,'way':1,'attention':1,'beings':1,'actions':2,'behaviour':4,'appreciation':2,'insect':1,'student-citizen':1,'learning':1,'activity':1,'device':1,'learning.':1,'creatures':1},'traced':{'on':1,'back':1,'its':1},'concave':{'and':1},'sufficiently':{'close':1,'generous':1,'shallow':1,'hard':1,'low':1},'vibrations':{'and':1,'of':1,'in':2,'constituting':1,'must':1},'truth':{'that':1,'of':1,'though':1,'but':1,'they':1,'in':4},'invertebrates':{'and':1},'persia':{'turkestan':1},'accompanied':{'by':2},'beneath':{'shines':1,'the':8},'stock':{'separated':1,'and':3,'of':4,'spreading':1,'took':1,'marked':1,'.':5,'to':2,'as':1,'common':1,'in':1,';':1,'has':1,'was':1,'the':4},'traces':{'of':4,'are':1,'which':1,'in':1},'enigmatic':{'objects':1},'profile':{'view':4},'salps':{'related':1},'beginner':{'s':1},'doing':{'clever':1,'damage.':1,'things':1,'work':1,'when':1,'.':1,'this':1,'apparently':1},'sidelight':{'on':1},'society':{'society':1,'the':1,'made':1},'frequency':{'of':2,';':1},'static':{'to':1},'irritation':{'may':1},'agriculture':{';':2},'wander':{'separately':1},'witness':{'a':1,'an':1},'fundamentally':{'instinctive':1},'colour-varieties':{'there':1,'which':1},'knickerbocker':{'press':1},'bad':{'debts.':1,'business':1},'venom':{'on':1},'dominated':{'by':1},'adaptive':{'to':1,'radiation.':1,'device--more':1},'architecture':{'though':2},'harvest-mouse':{'constructing':1},'shut':{'our':1,'to':1,'their':1},'thrush':{'seized':1,'s':3,'managed':1,'at':2,'which':1},'perish':{'if':1},'incalculable':{'and':1,'abundance':1,'millions':1},'decay.':{'sec':1},'body-cavity':{'fluid':1},'surely':{'a':1,'follows':1,'is':1,'have':1,'the':1,'difficult':1},'steering':{'.':1},'shortest':{'waves':2,'.':1},'things.':{'lord':1,'reliable':1,'contrast':1},'apprehend.':{'the':1},'pursuits.':{'everything':1},'could':{'just':1,'be':20,'it':2,'resist':1,'see':2,'skate':1,'exist':1,'at':1,'have':1,'measure':1,'extract':1,'use':1,'make':2,'actually':1,'survive':1,'then':1,'we':1,'run':1,'form':1,'stop':1,'discover':1,'possibly':2,'produce':2,'not':8,'believe':1,'fly':2,'photograph':2,'boast':1,'keep':1,'harness':1,'support':1},'tube-feet':{'are':1},'david':{'fife':2},'length':{'and':1,'about':1,'may':1,'of':14,'is':1,'.':6,'as':1,'7':1,'were':1,';':1,'has':1},'removing':{'any':1},'stimulate':{'organs':1},'gamekeeper':{'but':1},'granules.':{'from':1},'respond':{'to':1,'when':1},'blown':{'by':1,'to':1,'into':1,'away':2,'back':1},'scene':{'of':1,'showing':1,'with':1,'in':6},'earth':{'and':21,'receives':1,'often':1,'escapes':1,'revolves':1,'is':13,'within':1,'rotated':1,'it':4,'slowing':3,'down':1,'as':2,'259':1,'are':2,'in':4,'yet':1,'before':1,'even':1,'passes':1,'from':4,'for':3,'to':4,'giving':1,'began':1,'there':3,'when':3,'except':1,'.':36,'how':1,'does':1,'take':1,'which':5,'mars':1,'passing':2,';':3,'must':1,'was':3,'naturally':1,'circles':1,'became':1,'we':3,'turning':1,'passed':1,'that':1,'may':1,'completed':1,'were':3,'but':2,'92.9':1,'although':2,'included':1,'during':2,'on':2,'with':3,'by':1,'he':1,'a':1,'rotating':1,'has':2,'to-day':2,'would':3,'14':1,'always':1,'did':3,'of':2,'no':1,'itself':2,'against':1,'will':3,'s':24,'owing':1,'so':1,'had':2,'intercepts':1,'the':6,'pulled':1,'or':2,'turns':1,'at':3},'owner':{'and':1,'would':1,'of':3,'.':1,'s':1,'any':1},'blows':{'its':1},'scent':{'a':1,'of':1,'no':1},'interest.':{'as':1},'buoyed':{'up':1},'two.':{'illustration':1,'but':1},'light--visible':{'and':1},'fascinating':{'study':1,'tantalising':1,'spectacle':2},'behaves':{'so':1,'in':1},'system':{'and':7,'comets':1,'is':2,'as':2,'sec':1,'are':3,'in':2,'would':1,'once':1,'there':1,'.':11,'to':1,'revolving':1,'has':1,'was':2,'then':1,'we':1,'full':1,'ranged':1,'formed':1,'but':2,'with':1,'by':1,'must':1,'for':1,'of':9,'will':1,'the':5,'mean':1,'at':1},'sea-lilies':{'crustaceans':1,'water-fleas':1},'world--even':{'the':1},'opossum':{'carrying':2},'time--man':{'s':1},'king-crabs':{'.':1},'travelled':{'far':1,'at':1},'egg-layer':{'in':1},'thick.':{'the':1,'we':1},'interests':{'it':1},'accompany':{'actual':1},'stars':{'and':5,'comets':1,'enormously':1,'show':1,'being':1,'is':1,'within':1,'visible':1,'as':1,'sec':1,'are':13,'have':1,'in':4,'whose':1,'tending':1,'appear':1,'stretch':1,'circulating':1,'.':13,'to':1,'varies':1,'does':1,'which':6,'going':1,'themselves':1,'has':3,'across':1,'can':1,'we':3,'form':1,'that':1,'forming':1,'let':1,'with':1,';':2,'a':1,'pull':1,':':2,'like':1,'of':1,'into':1,'will':1,'thin':1,'were':2,'the':4,'planet':1,'or':3,'at':1},'quarry':{'.':1},'depressing':{'energy':1},'stimulation--giving':{'off':1},'prominent.':{'the':1,'5':1},'steel':{'we':1,'civilisation':1},'quietness':{'of':1},'migrating':{'of':1,'from':1},'poulton':{'s':1},'extraordinarily':{'efficient':1,'mammal-like':1,'like':2,'gaunt':1},'wicketed':{'sides':1},'negatively':{'electrified.':1,'charged':1},'steep':{'and':1,'mountain':1,'ladder':2,'cliff':1},'torrent':{'.':1},'undercharged':{'body':1},'ingenious':{'methods':2},'platypus':{'of':3},'partnership':{'commensalism':1,'is':2,'with':3,'between':2},'poisons':{'including':1,'which':1,'.':1},'gently':{'through':1,'with':1},'gentle':{'reactions':1},'affinities':{'both':1,'to':1},'clearly':{'necessary':1,'that':1,'defined':1,'of':1,'showing':1,'marked':1,'or':1,'seen':1,'visible':1,'in':2,'drawn':1,'worked':1,'outlined':1},'viewed':{'copied':1,'or':1},'food-debris':{'millennium':1},'depict':{'quite':1},'studying':{'head':1,'the':2},'possibility.':{'it':1},'mechanism':{'of':1},'decomposing':{'animal':1},'ashore':{'.':1},'photosphere':{'that':2,'there':2,'but':1,'.':2,'surrounding':1,'as':1,';':1,'beneath':1,'shows':1},'scooping':{'in':2,'out':1},'sirius':{'the':1,'8.7':1},'persistence':{'of':1},'accuracy':{'when':1,'than':1,'.':1},'worldwide':{'task':1},'brazil':{'18':1},'regard':{'them':1,'these':1,'it':1,'to':15,'as':1,'the':3},'shaped':{'as':2,'like':1,'something':1,'in':1},'seed-box':{'but':1,'.':1},'device':{'whereby':1,'for':1,'this':1,'of':1,'is':1,'to':1},'so-called':{'flying':1,'abdominal':1,'grouse':1,'chameleon':1,'sargasso':1,'rings':1,'electro-magnetic':1,'rays':1,'anvil':1},'river-mussels':{'yielded':1},'predacious':{'creatures':1},'tramps':{'the':1},'bred':{'to':1},'stronger':{'and':1,'.':1,'should':1},'curiously':{'enough':1,'wasplike':1},'face':{'a':2,'tentatively':1,'set':1,'certain':1,'is':1,'illustration':1,'.':1,'to':4,'allowing':1,'directly':1,'of':4,'166':1,'with':1,'region':2},'perceiving':{'moving':1},'kipling':{'s':1},'mechanical':{'skill':1,'energy':5,'apparatus':2,'means':1},'wounded':{'in':2},'brer':{'rabbit--who':1},'fact':{'a':1,'about':5,'led':1,'for':1,'that':35,'remains':1,'of':8,'is':16,'less':1,'means.':1,'.':2,'to':1,'so':1,'too':1,'which':1,'in':1,'emphasized':1,'was':1,'the':1},'atmosphere':{'and':4,'heavy':1,'all':1,'from':1,'of':3,'is':1,'it':1,'but':1,'.':4,'will':2,'without':1,'envelops':1,'catch':1,'absorbs':1,'the':1,'rises':1,'was':1,'or':1,'nor':1},'best-defined':{'period':1},'nest-building':{'and':1,'in':1},'woolly':{'rhinoceros':2,'opossum':2,'caterpillars':1},'bring':{'me':1,'about':3,'modern':1,'down':3,'their':1,'forth':2},'14.--the':{'moon':1},'evolutionary':{'prospect':3,'process':1,'results':1,'spiral':1,'tack':1,'steps':1,'significance':1,'method':1,'change':1},'manchester':{'used':1,'chemist':1},'lloyd':{'morgan':4},'rough':{'surfaces':1,'awns':1},'principal':{'of':1,'office':1},'trying':{'time':1,'to':7,'first':1,'it':1,'one':1},'championed':{'evolutionism':1},'jaw':{'and':1,'from':1,'of':3,'belong':1,'seems':1,'but':1,'which':1,'the':1},'jar':{'and':1,'the':1},'should':{'it':2,'see':3,'expect':2,'have':7,'go':1,'find':1,'differ':1,'there':1,'also':2,'naturally':1,'be':19,'get':2,'they':1,'not':4,'fly':1,'remember':1,'gather':1,'say':2,'experience':1,'greatly':1,'think':1,'at':1},'buttons':{'on':1,'occasionally':1},'unpalatable':{'mimicked':1,'insects':1,'things':1,'.':2,'sponge':1,'caterpillars':1,'or':1},'planted':{'in':1},'molecules':{'is':1,'deep':1,'as':1,'are':2,'have':2,'in':2,'250':1,'travel':1,'.':4,'thick.':1,'cling':1,'into':1,'then':1,'which':2,'form':1,'that':1,'cannot':1,'let':1,'by':1,'of':16,'large':1,'small':1,'at':1},'volts':{'.':1},'hope':{'to':1,'that':4,'.':1},'meant':{'a':2,'even':1,'for':1,'many':1,'to':3,'much':2,'utilising':1,'entering':1,'in':1,'the':3,'total':1,'transcending':1,'by':3,'more':1},'handle':{'there':1,'off':1,'than':1,'in':1},'means':{'over':1,'an':3,'in':1,'any':1,'power.':1,'for':3,'no':1,'.':1,'much':1,'girdling':1,'more':1,'we':1,'that':15,'half':1,'losing':1,'a':5,'mastery':1,'of':30,'foresight':1,'were':1,'making':1,'the':5,'first':1},'intellectually':{'.':1},'prohibition':{'against':1},'fronds':{'are':1},'a.c.':{'.':1},'h':{'the':1,';':1,'.':43},'molecule.':{'single':1},'taxes':{'on':1,'.':1},'summon':{'it':1},'hemispheres':{'and':1,'destined':1},'are.':{'for':1},'coco-nut':{'fibre':1,'shell':1,'palm':1},'stuff':{'from':2,'which':1,'into':1,'.':1,'they':1,';':1,'began':1,'out':1},'bayliss':{'has':1},'inter-relation':{'established':1},'memory-image':{'of':1},'tap.':{'watch':1},'strengthened':{'when':1},'frame':{'the':2},'shreds':{'as':1},'packet':{'containing':1,'no':1,'turned':1,'though':1},'elusiveness':{'there':1,'so':1},'bolivia.':{'illustration':1},'5.--diagram':{'showing':1},'once.':{'in':1},'carboniferous':{'blue':1,'flora':1,'forests':1,'period':4,'epoch':1,'eras':1,'were':1,'the':2,'.':1,'era':1},'frog-hoppers':{'while':1},'packed':{'with':1,'together':1},'ascends.':{'illustration':1},'wire':{'or':1,'that':1,'is':1,'an':1,'to':1,'so':1,'they':2,'between':1,'leaves':1,'the':2,'its':1},'growths':{'on':1},'jurassic':{'archaeopteryx':1,'is':1,'period':2,'yellow':1,'era':1,'which':1},'nuclear':{'bodies':1},'migrations':{'were':1,'are':1,'have':1,'occurred':1},'germ-cell':{'just':1},'quickest':{'to':1},'white-hot':{'metal':2,'hydrogen':1,'iron':1,'.':1},'membrane':{'and':1},'open-sea':{'or':1,'animals':4,'cetaceans':1,'crustaceans':1,'young':1,'knife-blade-like':1,'prawns':1,'bacteria':1},'self-preservative':{'fashion':1},'email':{'contact':1,'newsletter':1,'business':1},'ends':{'and':2,'on':1,'of':2,'marked':1,'lizzie':1},'explosive':{'manifesting':1,'life':1,'rush':1,'by':1},'trilobite':{'90':1,'trilobites':1,'in':1},'ancestry--are':{'branches':1},'seaweeds':{'and':2,'among':1,'are':1,'which':1,'growing':1,'the':1},'ignorance':{'of':1,'preyed':1},'wave-motions':{'of':1,'are':1,'can':1},'wingless':{'insects':1,'larval':1,'creatures':1},'hoatzin':{'inhabits':2},'reappears':{'in':1},'restrictions':{'whatsoever':2},'drum':{'to':2},'migration.':{'looking':1},'figures':{'to':1,'we':1,'with':1,'are':3,'.':1},'cinder':{'.':1},'humanoid':{'to':2,'precursors':1,'stock':4},'adjusted':{'on':2,'coloration':1,'in':1},'co':{'.':2},'conflagration':{'had':1,'that':1},'conclude':{'our':1,'that':1},'ca':{'the':1},'mid-rib':{'and':2},'vibration.':{'no':1},'sea-worms':{';':1},'cv':{'the':1},'hawkins':{'from':1},'palm-bones':{'and':1,'the':1,'cmc':1},'8.7':{'procyon':1},'trigger-pulling':{'.':1},'dazzling':{'light':1},'body-cells.':{'it':1},'poured':{'a':1,'on':1},'looting':{'and':1},'duckweed':{'usually':1},'feather':{'as':1,'which':1},'waste':{'matter':2,'energy':1,'to':1,'heat':1,'products':1,'its':1},'descent.':{'retrospect':1},'c.':{'punnett':1},'coherence':{'of':2},'mammals.':{'the':1,'now':1,'what':1,'cretaceous':1},'tycho':{'upper':1},'neighbour':{'succeed':1,'.':1},'accident':{';':1,'.':1},'forests.':{'the':1},'domestication.':{'instinctive':1},'expounded':{'with':1},'spain':{'this':1,'showing':2,'179':1,'show':1},'gradual':{'building':1,'unfolding':1,'evolution':1,'establishment':1,'alterations':1,'sifting':1,'increase':2,'migration':1,'emancipation':1,'shading':1,'assortment':1,'ascent':1,'emergence':1,'change':2},'nerve-fibre':{'branches':1,'ends':1,'s.f.':1,'from':1,'or':1},'triggers':{'of':1},'reminiscence':{'as':1},'lung-fishes':{'or':1,'that':1},'lichen':{'and':1,'where':1},'pictures':{'guesses':1,'for':1,'that':1,'of':1,'.':2,'they':1,'the':1},'deductible':{'to':1},'discoveries':{'made':2,'which':2,'that':1,'of':4,'.':1,'have':2,'in':2},'spectrum--should':{'be':1},'salmo':{'all':1},'omne':{'vivum':1},'vm':{';':1},'adventures':{'at':1},'excessively':{'small':1,'minute':3},'raison':{'d':1},'jenner':{'weir':1},'carbohydrates':{'e.g':1},'of.':{'a':1},'fashioning':{'of':1,'beautifully':1},'spends':{'the':1},'romance':{'of':5,'to':1},'concealed':{'among':1,'beneath':1},'colony.':{'within':1},'estuaries':{'and':3,'while':1,'are':1,'penetrated':1},'outbreak':{'must':1},'nebulae.':{'some':1,'illustration':1,'in':1},'unimaginable':{'energy':1},'lichen;':{'one':1},'mud-skipper':{'periophthalmus':3},'emotionally':{'excited':1},'dusk':{'of':1,'is':1,'does':1},'wisest':{'not':1},'upon':{'it.':1,'a':3,'them':1,'another':1,'marquis':1,'insects':1,'men':1,'request':1,'it':3,'one':1,'water':1,'and':1,'as':1,'itself':1,'they':1,'the':26,'an':1,'its':3,'by':2},'v.':{'experiential':1},'infinite':{'temporal':1,'space':2,'in':1,'number':1,'time':1},'britain.':{'iv':1},'identity':{'of':1},'transformation--the':{'heat':1},'genus':{'eoanthropus':1,'oncorhynchus':1,'which':1},'off':{'and':1,'the':19,'into':1,'as':2,'at':2,'another':1,'in':4,'throughout':1,'fine':1,'again':1,'rays':1,'from':8,'intruders':2,'.':3,'other':1,'crowds':1,'neolithic':1,'his':1,'intruding':1,'half':1,'such':1,'by':3,'a':4,'on':1,'natural':1,'this':1,'of':1,'electrons':1,'gigantic':1},'mention':{'briefly':1,'the':1,'one':1},'tinge':{'is':1,'.':1},'colour':{'and':9,'almost':1,'is':1,'as':1,'in':1,'affects':1,'that':1,'.':6,'also':1,'does':1,'permanently':1,'disclosed':1,'which':1,'has':1,'seen.':1,'gives':1,'be':2,'corresponding':2,'means':1,'becoming':1,'with':1,'a':1,'being':1,'yellow-brown':1,'of':8,'depends':1,'the':1,'changes':2},'polyp':{'about':1},'directly.':{'some':1},'patterns':{'.':1},'cutting':{'down':1,'off':1,'at':1},'ear-passage':{'to':1,'into':1},'drawing':{'a':1,'shows.':1,'planetesimals':1,'food':1,'flying':1,'their':2,'by':4,'shows':2},'asymmetrical':{'flat-fish':1},'reefs':{'that':1},'negligence':{'strict':1},'flesh':{'and':2,'exposed':1,'of':1,'but':1,'are':1,'or':1,'available.':1},'moments':{'at':1},'gulls':{'pick':1},'flywheel':{'a':1,'and':1,'would':1,'.':2,'or':1,'if':1},'sea-dust':{'and':1,'always':1,'which':1,'.':1},'rooms':{'but':1},'predicts':{'the':1},'years':{'and':3,'required':1,'ago--a':1,'acquired':1,'life':1,'comprised':1,'1921':1,'as':1,'are':1,'in':4,'old':2,'yet':1,'before':4,'mercury':1,'invented':1,'would':1,'till':1,'with':1,'there':1,'.':13,'to':7,';':2,'must':1,'we':1,'ago.':3,'may':2,'after':1,'reached':1,'but':2,'it':1,'sink':1,'during':1,'elapsed':1,'dr':1,'he':1,'ago':28,'for':1,'these':1,'of':4,'work':1,'dealt':1,'the':4,'or':1},'paul':{'s':1},'glue':{'probably':1},'web':{'on':1,'of':2,'is':3,'site':4,'page':1,'which':1,'has':1,'pages':1},'generous':{'to':1,'lines':1,'if':1},'bibliography':{'elmhirst':1,'the':2,'darwin':1,'arrhenius':1},'lanugo':{'which':1},'apple--out':{'of':1},'transparent':{'layers':1,'all':1,'coating':1,'arrow-worm':1,'early':2,'azure':1,'open-sea':1},'ichthyosaurs':{'plesiosaurs':1},'combine':{'and':1,'to':1},'wet':{'cloth':1,'all':1,'weather':1,'moss':1},'5':{'and':1,'what':1,'has':1,'ft':1,'limbless':1,'1909':2,'mind':1,'per':1,'.':8,'feet':2,'matter':1,'000':5,'5':1,'in':1,'the':1,'mimicry':1,'500':1,'shows':1},'practise':{'self-effacement':1,'parental':1},'increased':{'power':1,'freedom':1,'its':1,'liberation':1,'masterliness':1,'difficulties':1,'at':1,'in':1,'our':1,'the':2,'still':1,'by':1,'production':1},'government':{'or':1},'biologists':{'have':1,'that':1},'new--a':{'restless':1},'smithsonian':{'report':10},'mathura':{'on':1},'increases':{'our':1,'.':1,'in':1},'five':{'digits':1,'hundred':3,'minutes':1,'of':1,'million':1,'times':3,'feet':1,'to':1,'straws':1,'she':2,'in':1,'--and':1,'vertebrae':1,'years':1,'.':1,'or':3,'millions':1},'belgium':{'the':1},'tick':{'a':1,'for':1,'one':1},'descendant':{'of':2},'backboned':{'race':1,'animals':9,'animals.':1},'onion':{'round':1},'258':{'the':1,'electrons':1},'parasite':{'and':1,'to':1,'from':1,'like':1},'glass-eels':{'about':1},'two-thousandths':{'of':1},'ductless':{'glands':2},'nerves':{'and':1,'of':1,'which':1,'.':1},'inexperienced':{'enemies':1},'replacement':{'of':1,'copy':2,'or':3},'gaining':{'a':1,'strength':2},'indications':{'even':1},'habitat':{'and':1,'penetrate':1,'or':1},'underwent':{'great':1,'an':1},'gossamer.':{'on':1},'daylight':{'.':1},'choosing':{'times':1},'paving-stones':{'green':1},'restlessness.':{'they':1},'transport':{'as':1},'avoid':{'a':1,'the':2,'reading':1},'dago':{'dagoes':1},'mars.':{'but':1},'does':{'we':1,'no':1,'this':4,'energy':1,'comparatively':1,'it':2,'but':1,'.':3,'much':1,'so':4,'at':2,'cannot':1,'in':1,'not':35,'the':1,'its':1},'passion':{'plunged':1},'cylindrical.':{'5':1},'mammoth.':{'the':1},'biology':{'of':1,'in':1},'blowing':{'upon':1},'predispositions':{'to':1,'of':1},'selecting':{'individual':1,'out':1},'tenability':{'of':1},'performances.':{'a':1},'pressure':{'and':2,'would':1,'inside':1,'so':1,'in':2,'the':2,'etc.':1,'currents':1},'enregistering':{'these':1,'the':1,'within':1},'century.':{'during':1,'illustration':2},'abdominal':{'ribs':1},'germination':{'and':1},'r':{'and':1,'.':14},'cribb.':{'boiling':1,'transformation':1},'hiding':{'them':1},'gained':{'most':1,'racial':1,'considerable':1,'proof':1},'mammoths':{'.':1},'asks':{'at':1,'why':1,'that':1},'seeds':{'and':1,'because':1,'for':1,'of':3,'.':1,'can':1,'become':1,'themselves':1,'with':1},'bounded':{'by':1},'swimming':{'and':2,'gently.':1,'experience':1,'ostrich':1,'persons':1,'near':1,'in':5,'diving':1,'across':1},'letters':{'of':2,'in':1},'elephants.':{'the':1},'hermit-crabs':{'hide':1,'place':1,'it':1,'have':1},'lung':{'and':1,'the':1,'.':1},'tiny':{'knob':1,'bags':1,'freshwater':1,'rill.':1,'irregular':1,'shift':1,'molecules':1,'fragments':1,'drops':1,'whirlpool':1},'cultivated':{'plants':6,'the':1,'wheat':1,'ear.':1,'in':1},'protozoa':{'and':2,'to-day':1,'which':1,'is':1,'should':1,'to':1,'as':1,'are':1,'sponges':1,'in':2,'animals':1,':':1,'like':1},'offices.':{'sec':1},'swimmers':{'and':2,'include':1,'nekton':1},'charities':{'and':1},'mere':{'density':1,'molluscs':1,'bulk':1,'visible':1,'cooling':1,'specks':1,'position':1,'association':1},'parentage':{'of':2},'67000':{'inch':1},'larvae':{'hanging':1,'or':1,'which':3,'in':1},'slow-worm':{'is':1},'half-monkeys':{'or':1},'larval':{'state':1,'stages':2,'salmon':1,'period':1,'stage':1},'spots':{'and':1,'on':2,'like':1,'of':1,'or':1,'increase':1,'are':1,'which':1,'the':2,'where':1,';':1,'must':1},'scanty':{'remains':2,'and':1,'fossil':1,'plankton':1},'recognised':{'and':1,'for':1,'as':1,'in':2,'moreover':1,'by':2},'hundred-millionth':{'of':1},'place.':{'illustration':1,'one':1},'specimens':{'of':1,'in':1,'were':1},'naturally':{'prolific':1,'give':1,'trails':1,'finds':1,'expect':1,'came':1,'appears':1,'opens':1,'he':1},'function':{'of':1,'in':1},'funnel':{'through':1},'cosmopolitan':{'in':1},'surgeons.':{'every':1},'washerwoman':{'and':1},'construction':{'underwent':1,'from':1,'of':2},'convergence':{'the':1},'basin':{'of':1},'contraction.':{'uranium':1},'count':{'them':1,'the':1,'for':3},'marquis':{'wheat':4,'.':1},'evident':{'in':1},'shrunk':{'by':1},'gravitational':{'pull':2,'influence':2,'theory':1,'attraction':2},'official':{'project':1,'observatory':1,'version':1,'page':1},'smooth':{'continuance':1,'carapaces':1,'formation':1,'atoms':1},'triumphant':{'flight':1},'excitement':{'though':1,'.':1},'placed':{'a':1,'on':3,'them':2,'for':1,'exactly':1,'an':1,'to':1,'at':1,'in':2},'frugivorous':{'stock':1},'convince':{'us':1},'monument':{'of':1},'problem':{'no':1,'of':10,'could':1,'.':2,'as':1,'surely':1,'the':1,'is':2},'profusion':{'.':1},'bearing':{'protrusible':1,'on':1,'batteries':1,'this':1,'the':1},'irish':{'elk':1},'ferocious.':{'embryological':1},'recognize':{'water':1},'nearness':{'to':1,'of':2},'rubble':{'innumerable':1},'faintness':{'.':1},'slowing':{'down':8,'down--the':1},'arms.':{'this':1},'beach.':{'but':1},'leptocephalus.':{'2':1},'aristotle':{'observed':1,'s':1,'or':1},'ink':{'in':1},'www.gutenberg.org':{'this':1,'title':1,'you':1,'2':1,'1.e.2':1},'effected':{'a':2,'within':1,'by':3,'in':1},'planting':{'it':1},'expensiveness':{'of':1},'readjustments':{'of':1},'radiolarians':{'and':1,'of':1,'with':1},'variety':{'and':1,'of':16,'is':1,'after':1,'surpassed':1,'.':2,'has':1,'with':1},'tenth':{'printing':1},'eastern':{'baltic':1},'forests':{'and':2,'a':1,'from':1,'which':1,'that':1,'of':4,'there':1,'.':1,'roamed':1,'in':1,'the':2,'he':1},'slumbers':{'in':1},'reach.':{'animal':1},'details':{'of':2,'is':1,'revealed':1},'behold':{'a':1},'thickness--a':{'sea':1},'outlines':{'of':1,'at':1,'spectroscopy':1},'repeat':{'all':1,'gives':1,'that':1},'again.':{'moreover':1,'illustration':2,'that':1},'in:':{'http:':1},'tides':{'and':3,'we':1,'which':2,'than':1,'of':1,'had':1,'it':1,'but':1,'.':6,'will':1,'to':1,'ranked':1,'are':4,'have':1,'act':1,'at':1,';':1,':':1,'the':1,'290':1,'must':1},'casque':{'is':1},'subtlest':{'of':1},'again:':{'the':1},'in.':{'with':1},'13.--saturn':{'november':1},'ideals':{'which':1,'in':2},'shattering':{'itself':1},'veil':{'of':1},'coloration':{'and':1,':':2,'is':1,'when':1,'serves':1,'coloured':1,'will':1,'the':1,'.':1,'or':3},'exposure':{'to':1,'of':1},'draperies':{'gliding':1},'bivalve':{'mollusc':1,'shell.':1},'lasted':{'beyond':1,'or':1,'for':1},'rule':{'and':1,'feed':1,'we':1,'that':1,'is':1,'two':1,'exist':1,'in':1,';':1,'out':1},'eddies':{'of':1,'rising':1},'pitt':{'offered':1},'gardens':{'in':1},'practicability':{'of':1},'three-toed':{'horse':2},'surrounding':{'stimuli.':1,'space':2,'colour':1,'flesh':1,'them--are':1,'sky--this':1,'world':1,'the':2,'gravel':1,'conditions':1,'ether':1,'bodies':1},'magnetic':{'force':1,'storm':1,'circuits':1,'phenomena':1,'sense':1,'storms':2,'effect':1,'deflection':2,'field':7,'circuit':2,'field--which':1,'action':1},'saves':{'their':1},'desirable':{'for':1},'rapid':{'and':3,'abbreviation':1,'precisely':1,'often':1,'power':1,'striking':1,'colour-change':3,'series':1,'that':2,'passage':1,'motion':1,'as':1,'way':1,'waves--the':1,'elimination':1,'succession':1,'changes':1,'than':1,'change':1,'movement':1},'nursery':{'for':1},'controversial':{'stage':1},'crete':{'greece':1},'oldest':{'known':3,'of':1,'rocks':1,'stars':1,'egyptian':1},'worked':{'flints':1,'up':1,'itself':1,'steadily':1,'the':1,'by':1,'out.':1,'out':8},'1915.':{'a':1,'magnetic':1,'electrons':1,'geological':1},'ceases':{'to':1,'.':1},'physiological':{'life':1,'expensiveness':1,'point':1,'equilibrium':1,'partnership':1,'evidence':1,'characters.':1,'inequilibrium':1,'action':2,'difference':2,'types':1,'proof':1},'ventral':{'lungs':2,'scales':1},'centrosome':{'introduced':1},'neighbours':{'of':1,'.':1},'microscopist':{'named':1},'mckready':{'a':1},'diverted':{'into':1},'worth':{'remembering':1,'dwelling':1,'having':1,'.':1},'alternating':{'current':1,'occurrence':1,'yellow':2},'them--which':{'give':1},'aurora':{'borealis':4,'is':1},'waters--the':{'dry':1},'impinged':{'on':1},'coal-measures':{'the':2,'were':1},'alevins':{'which':1},'slowed':{'down--sometimes':1},'exaggerate':{'the':1},'pinch':{'of':2},'cmc':{';':1},'globule':{'about':1},'nondescript':{'not':1},'jungle-fowl':{'of':1},'290':{'photo':1,'the':1},'291':{'photo':1},'dwindled':{'away':1,'vestiges':1},'speck':{'of':2,'against':1},'tree-kangaroos':{'tree-sloths':1},'labyrinthodonts':{'some':1},'surmounting':{'the':1},'overlying--the':{'photosphere':1},'seas.':{'perhaps':1,'evolution':1,'like':1,'recent':1},'microscopists':{'and':1},'------':{'------':2,'866400':1,'2163':1},'others.':{'1.d':1},'them--are':{'of':1},'alsatian':{'wolf-dog':2},'neap':{'tides':1},'580':{'000':1},'calcium':{'vapour':1},'gatepost':{'208':1,'the':1},'lizard':{'which':2,'is':1,'they':1,'chlamydosaurus':1,'draco':1,'called':1},'consequent':{'changes':1,'aridity':1},'lampreys':{'petromyzon':2},'glands':{'notably':1,'such':1,'of':1,'on':1},'salt-accumulation':{'is':1},'reconstruction':{'of':2,'by':2},'toll':{'to':1},'suppose':{'for':1,'that':8,'it':1,'at':1,'each':1,'the':2},'consisting':{'of':2},'told':{'edited':1,'in':1,'author':1,'us':1,'that':1},'crunch':{'with':1},'machine.':{'a':1},'simultaneously':{'.':1},'sinks':{'down':1,'again':1,'and':1,'into':1},'lithosphere':{'is':1},'human':{'and':1,'embryo':7,'development.':1,'ingenuity':1,'being':2,'sense':1,'mind':2,'society':1,'beings':2,'thought.':2,'in':3,'knowledge.':1,'use':1,'eye':2,'ovum':1,'remains':2,'.':1,'tail':1,'civilisation.':1,'progress':5,'type':1,'body':3,'progress.':1,'kind':1,'gestures':1,'races':1,'blood':3,'characters':1,'ear':2,'mind.':1,'evolution':1,'branches':1,'evolution--factors':1,'skull':4,'brain':4,'was':2,'ascent.':1,'face':1,'race':3,'limit':1,'qualities':1,'teeth':1,'life.':1,'institutions':1},'kindred':{'and':1,'on':1,'animals':1,'especially':1,'.':1},'residual':{'gases':1},'out-flowing':{'lobes':1,'processes':1},'protection':{'for':1,'of':2,'possessed':1,'.':1,'also--protection':1,'implied':1,'every':1,'before':1},'pursuit':{'and':1},'ploughed':{'field':1},'promiseful':{'life':1},'obtained':{'our':1,'by':1,'would':1,'.':1},'aerial.':{'the':1},'daughter':{'colonies':1},'items':{'and':1,'among':1,'are':1,'tend':1},'frog-hopper':{'becomes':1,'makes':1},'anchor':{'.':1},'smoke':{'a':1,'no':1,'in':1,'that':1},'browsing':{'by':1},'bettered':{'surroundings':1},'otters':{'and':1,'it':1,'foxes':1},'glittering':{'points':1},'diameter':{'and':1,'for':1,'of':7,'is':2,'there':1,'number':1,'.':4,'lifts':1,'are':1,';':2,'one':1,'whereas':1},'secure':{'a':1,'and':1,'that':1,'survival':1,'evidence.':1,'position':1,'the':4,'floating':1},'discontinuous':{'variation':1},'-cell':{'with':2},'highly':{'probable':8,'endowed':1,'interesting':1,'magnified.':1,'developed':3,'probably':1,'intelligent':1,'specialized':2,'perfected':1},'lafayette.':{'the':1},'opportunities':{'to':1,'animals':1,'for':1,'.':1},'glance':{'at':1},'total':{'loss':1,'or':1,'of':2,'energy':1,'number':1,'thickness':2,'amount':1,'solar':2,'emancipation':1,'length':1,'age':1,'as':1,'quantity':1},'experimentation':{'in':1},'plot':{'at':1},'answers-back':{'that':1},'alligator':{'yawning':2},'grounds':{'of':1,'.':1},'negative':{'and':1,'electricity':10,'electricity.':1,'taken':1,'pole':2,'are':1,'units':1,'the':1},'reid.':{'sir':1,'common':1},'crocodilian':{'various':1},'mightiest':{'elevators':1},'knoll':{'and':1},'girdling':{'the':2},'thorndike':{'s':1,'says':1,'hits':1,'is':1},'recuperate':{'by':1},'separated':{'from':2,'freshwater':1,'off':4,'by':1,'.':2},'traceable':{'back':1},'ascribe':{'it':1},'aware':{'of':7,'that':1},'separates':{'the':1,'monkeys':1,'it':1},'continual':{'sinking':1,'motion':1,'motion.':1,'occurrence':1},'allies':{';':1,'in':1},'dando.':{'orang-utan':1,'young':1,'chimpanzee':1},'society.':{'professor':2},'twenty-one':{'miles--in':1},'antenna-bearing':{'segmented':1},'crest':{'to':4,'.':1,'so':1,'or':1,'of':1},'books.':{'each':1},'work':{'and':7,'associated':2,'is':6,'within':1,'as':1,'in':8,'any':1,'electronically':2,'out':2,';':2,'from':1,'recorded':1,'.':10,'to':2,'offers':1,'which':1,'under':1,'you':2,'if':1,'badly':1,'that':1,'may':1,'with':1,'by':1,'on':3,'b':1,'of':6,'well':2,'against':1,'without':2,'can':1,'the':3,'or':8},'eclipse':{'may':2,'of':7},'worm':{'invasion':1,'the':1,'on':1,'.':1},'worn':{'down':1,'and':1},'theories':{'may':1,'of':5,'to':1,'have':1,'dispense':1,'put':1},'mammalian':{'heart':1,'evolution':1,'mother':1,'golden':1},'eighteen':{'to':1},'era':{'and':2,'what':1,'there':1,'miocene':1,'jurassic':1,'of':2,'silurian':1,'when':1,'corresponds':1,'.':6,'in':3,'after':1},'transparency':{'or':1},'already':{'a':2,'existed':1,'we':1,'learnt':1,'likened':1,'spoken':1,'use':1,'dead':1,'and':1,'known':1,'been':1,'have':1,'mentioned':1,'seen':1,'the':1,'referred':2,'at':1},'ascetic':{'non-growing':1},'radiance':{'from':2},'indicated':{'to':1,'by':3,'in':1},'cited':{'as':1},'india':{'146':1,'and':1,'into':1,'it':1,'malay':1,'persia':1,'.':1},'indicates':{'a':3,'the':2},'fanciful':{'imaginings':1},'present-day':{'and':1,'forms':1,'animals':1,'science':1,'theories':1,'survivors':1,'mud-fishes':1},'immemorial.':{'in':1},'aerated':{'and':1},'handiness.':{'the':1},'inhabitants':{'of':2,'is':1},'finger-post':{'on':1},'crumbs':{'from':3},'egyptian':{'tombs':1},'nuts':{'these':1,'it':1,'193':1,'for':1},'makes':{'a':4,'and':1,'for.':1,'for':1,'no':2,'this':1,'adjusting':1,'some':1,'it':5,'us':1,'an':1,'against':1,'the':9,'tree-stems':1,'its':3,'more':1},'far':{'and':1,'less':1,'over':3,'back':1,'as':9,'at':1,'in':1,'south.':1,'beyond':1,'out':1,'given':1,'end':1,'for':1,'away':2,'since':1,'exceeding':1,'been':1,'.':2,'behind':1,'too':4,'above':2,'surpasses':1,'east':3,'more':5,'north':3,'greater':1,'that':1,'from':6,'transcending':1,'advanced':1,'on':1,'off':1,'ahead':1,'up':2,'below':2,'swing':1,'the':3,'south':1},'aerates':{'the':1,'them':1},'ordinary':{'fish':1,'tissues':1,'flower-vase':1,'single':1,'questions':1,'education':1,'tadpoles':1,'temperature':1,'chemical':1,'way':2,'mammals':1,'conditions':1,'protozoon':1,'life':2,'star':1,'wheats':1,'big':1,'routine':1,'pressure':1,'routine--not':1,'bony':1,'cells':2,'standards':1,'matter':3,'familiar':1,'mammal':1,'acceptation':1},'beach':{'which':1,'.':1},'gamble':{'writes':1,'continues':1},'discoveries.':{'already':1},'guanin':{'.':1},'fever':{'and':1},'transforming':{'the':1},'ladder':{'of':3},'after':{'and':1,'all':2,'they':3,'generation':1,'some':1,'it':1,'an':1,'satisfaction':1,'itself':1,'well-being':1,'lull':2,'another':7,'our':1,'repeated':1,'its':2,'what':1,'death':1,'fuller':1,'her':1,'cache':1,'hour':1,'by':1,'their':2,'millennium':1,'which':1,'marsh':2,'sojourning':1,'he':2,'head':1,'his':2,'branch':1,'undergoing':1,'that':2,'max':2,'william':2,'fritz':1,'five':1,'nearly':1,'birth':2,'new':1,'fifteen':1,'themselves':1,'man':1,'a':10,'spawning':2,'exposing':1,'being':1,'this':1,'floods':1,'professor':2,'prolonged':1,'element':1,'planet':1,'race':1,'t':2,'mr':1,'the':14,'marsh.':2,'wandering':1,'age':2,'lloyd':1},'movable':{'tongue':1,'.':1},'customs':{'point':1},'lay':{'their':2,'eggs':1,'there':1,'them':1,'emphasis':1},'outbursts':{'of':2,'have':1},'maxim:':{'it':1},'law':{'of':3,'.':1,'in':1,'but':1,'that':1},'meaningful':{'situation':1},'nipped':{'in':1},'elusive':{'and':1,'.':1},'cools':{'to':1},'appreciate':{'water':1,'a':1,'the':1},'greek':{'helios':1,'logos':1,'word':1,'tortoise':1,'eagle':1,'alphabet':1,'philosophers':1,'meaning':1,'thinkers':1},'verb':{'to':1},'green':{'chlorophyll':1,'yellow':1,'in':3,'plants.':1,'blue':2,'flagellates--the':1,'surroundings':1,'variety':1,'tree-snake':1,'frog':1,'hydra':2,'herbage':1,'plants':2,'ball':1,'seaweeds':1,'pigment':2,'ones':1,'phase':1,'box':1,'on':1,'grains':1,'of':1,'leaves':2,'lizard':1,'alga':1,'or':2},'parish':{'to':1},'coral-snake':{'can':1},'order':{'and':2,'than':1,'that':1,'diverging':2,'of':12,'is':1,'.':1,'to':4,'in':1,'the':1,'monkeys':1},'sandstones':{'and':2,'mudstones':1},'office':{'is':2},'borealis':{'the':1,'is':1,'would':1,'coloured':1},'satisfied':{'with':1},'pascal':{'s':1},'ancients':{'seem':1,'were':1},'japan':{'to':1},'bubbles':{'which':1},'breeding-place':{'represents':1,'corresponds':1},'yellow-crowned':{'penguin':2},'sheaf':{'of':2},'production':{'of':3,'as':1,'promotion':1},'precipitate':{'when':1,'which':1,'.':2},'split':{'so':1,'off':1,'up':5,'longitudinally.':1},'then':{'there':5,'rubs':1,'they':2,'able':1,'is':3,'violet':1,'it':8,'are':2,'have':2,'another--to':1,'consists':1,'follow':1,'intact':1,'find':1,'waited':1,'for':1,'may':1,'since':2,'uranium':1,'to':4,'another':1,'has':1,'sent':1,'supposed':1,'be':3,'we':3,'partly':1,'that':2,'our':1,'pecked':1,'took':1,'drew':1,'sprinkle':1,'imperfectly':1,'visits':1,'although':1,'endure':1,'dives--':1,'diminish':1,'unless':1,'he':2,'illustration':1,'perceived':1,'necessary':1,'succeeded':1,'wafts':1,'follows':1,'inhabiting':1,'departs':2,'a':2,'so':1,'red':1,'the':7,'round':1,'comes':1,'arose':1},'them':{'and':9,'the':3,'penetrating':1,'on':2,'insulators':1,'stream':1,'show':2,'is':2,'fall':1,'an':1,'down':1,'against':1,'as':3,'116':1,'including':1,'are':7,'have':4,'in':9,'protecting':1,'32':1,'before':2,'even':1,'sir':1,'he':1,'astronomy':1,'from':2,'would':1,'no':1,'perhaps':1,'deeply':1,'away':1,'there':1,'when':2,'off':1,'.':19,'up':2,'to':8,'call':1,'which':1,'black':1,';':2,'sluggish.':1,'was':1,'until':1,'more':1,'weigh':2,'that':2,'may':1,'after':1,'bipeds--we':1,'illustration':1,'were':1,'jumping':1,'if':1,'know':1,'they':1,'coming':1,'such':1,'now':1,'with':2,'by':2,'apart':1,'a':2,'both':1,'about':1,'give':1,'for':2,'indifferent.':1,'face':1,'always':1,'into':1,'but':1,'namely':1,'together':1,'grows':1,'though':1,'electrically':1,'conquer':1,'gigantic':1,'requires':1},'affected':{'by':4},'babies':{'born':1},'fragment':{'of':2},'locusts':{'and':1,';':1},'safe':{'and':1,'among':1,'both':1,'situations':1,'to':5,'as':1,'cradle':2,'in':2},'fabre.':{'a':1,'the':1},'young.':{'our':1,'the':1,'sec':1},'band':{'of':1,'across':1},'giraffe':{'the':1,'s':1,'coloured':1},'reconverted':{'in':1},'sack':{'of':1},'they':{'represent':2,'all':2,'show':4,'move':1,'soon':1,'go':2,'find':1,'seemed':1,'derive':1,'also':3,'swam':2,'had':5,'send':1,'actually':1,'only':1,'persist':1,'practise':1,'happened':1,'grip':1,'eventually':1,'return':1,'get':2,'propelled':1,'cannot':3,'please.':1,'affect':1,'now':1,'possess':3,'perceived':1,'showed':1,'called':1,'did':3,'die':2,'seldom':1,'hunt':1,'settle':1,'found':2,'require':1,'enjoy':1,'successively':1,'often':1,'began':3,'resist':1,'imply':1,'decided':1,'are':130,'pass':4,'differ':2,'what':1,'said':1,'stood':1,'appear':2,'served':1,'tend':1,'attracted':1,'experiment':1,'radiated':1,'got':1,'learned':1,'ever':1,'correct':1,'can':13,'crunch':1,'obey':1,'never':1,'analysed':1,'disappeared':2,'were':27,'succeed':1,'let':1,'sink':1,'become':3,'put':2,'wanted':1,'come':1,'tenant':1,'receive':1,'could':4,'keep':1,'turn':1,'range':1,'act':2,'usually':1,'think':1,'feed':3,'emerge':1,'secure':1,'render':1,'point':1,'walk':1,'fast':1,'sow':1,'beheld':1,'reached':1,'illustrate':3,'use':1,'would':9,'create':1,'breed':1,'vibrate':1,'mark':1,'swarm':1,'call':1,'too':2,'then':1,'strike':1,'inflate':1,'tell':1,'therefore':1,'manufacture':1,'enable':1,'form':4,'fall':1,'corresponded':1,'must':5,'count':1,'account':1,'include':1,'look':3,'consist':2,'wish':1,'mount':1,'originate':1,'see':1,'will':5,'remain':1,'supposed':1,'learn':1,'meet':1,'emit':1,'and':1,'sometimes':2,'proved':1,'do':9,'likewise':1,'escape':2,'say':1,'have':33,'need':3,'seem':4,'made':6,'cool':1,'occur':1,'fill':1,'lie':1,'squat':1,'migrated':1,'built':1,'deserve':1,'travel':2,'generally':1,'extracted':1,'split':1,'test':1,'roll':1,'begin':2,'may':12,'absorb':1,'knew':1,'reach':5,'gradually':2,'reflect':1,'produce':2,'develop':1,'grow':1,'died':1,'varied':1,'cause':3,'give':4,'remember':1,'resemble':2,'nevertheless':1,'register':1,'appreciate':1,'correspond':1,'walked':1,'directly':1,'justify':1,'make':3,'came':1,'left':1},'molecules.':{'there':1,'illustration':1},'lifelong':{'study':1,'external':1},'bank':{'and':3,'or':1,'.':1},'bread':{'of':1},'1.00':{'7918':1},'rocky':{'shore-pool':1,'peninsula':1,'slopes':1},'oxygen':{'and':1,'available':1,'form':2,'of':1,'.':3,'to':1,'dissolved':1,'at':1,'which':1,'in':1,'taken':1,'than':1},'respiration.':{'illustration':1},'reasonably':{'that':1,'interpreted':1},'classified':{'.':1},'backgrounds':{'such':1},'l':{'bearing':1,'.':3},'rocks':{'and':4,'on':1,'since':1,'like':1,'may':1,'of':1,'is':2,'there':1,'according':1,'but':1,'.':1,'to':1,'were':1,'so':1,'are':1,'have':1,'which':1},'--':{'fig':1,'moon':1},'reasonable':{'objection':1,'to':1,'compass':1,'fee':1,'view':1},'heaved':{'off':1},'feeds':{'on':1,'are':1,'.':1},'associative':{'cell':1,'or':2,'learning.':1},'lifted':{'into':1,'off':1},'shows.':{'sec':1},'voyages':{'discovering':1},'prawn':{'hippolyte':1,'s':1,'takes':1,'.':1},'12.--jupiter':{'showing':1},'webbed':{'fingers':1},'pigments':{'enable':1,'compounded':1},'network':{'of':4},'forty':{'seconds':1,'inches.':1,'minutes':1,'inches':1},'fellows':{'can':1},'strangers':{'it':1},'vulgalis':{'1':1},'moisture':{'and':1,'heat':1,'about':1,'in':1},'medicine':{'but':1},'forth':{'and':1,'on':1,'.':1,'their':1,'in':8,';':1,'its':2,'the':1},'swamped':{'by':1},'disputed':{'whether':1,'and':1,'that':1},'nowadays':{'called':1,'an':1},'built.':{'illustration':1},'tops':{'of':1},'monkeys--activity':{'both':1,'for':1},'sunning':{'her':2},'admits':{'of':1},'forcibly':{'ejected':1},'detecting':{'a':2,'this':1,'the':1,'by':1,'its':1},'nebulae':{'and':1,'we':1,'from':1,'like':1,'would':1,'may':1,'is':1,'there':1,'it':1,'.':1,'as':1,'promise':1,'fig':1,'besides':1,'such':1,'are':5},'rarity':{'of':3},'created':{'to':1,'from':2,'or':2,'nor':1,'in':1},'appendages':{'and':1,'the':1},'shunted':{'.':1},'creates':{'a':1},'baltic':{'to':1,'.':1,'must':1},'clouding':{'after':1},'18.--a':{'diagram':1},'render':{'the':1},'synonymous':{'with':1},'another':{'remarkable':1,'feature':1,'aspect':1,'cuts':1,'glimpse':1,'source':1,'factor':1,'save':1,'very':1,'specimen':1,'they':1,'sowing':1,'lost':1,'solution':1,'truth':1,'works':1,'side':3,'fascinating':1,'series':1,'mighty':1,'are':1,'flower':1,'plays':1,'for':1,'though':1,'expressed':1,'experiment':1,'new':1,';':1,'method':2,'note--that':1,'fourteen':1,'on':1,'of':2,'distinguished':2,'thing':1,'s':1,'tack':1,'place':2,'consequence':1,'or':1,'inducing':1,'ring':1,'quality':1,'from':2,'one--of':1,'there':2,'.':10,'way':6,'was':1,'that':1,'four-toed':1,'but':1,'part':4,'solar':1,'with':1,'flightless':2,'kind':2,'has':1,'word':1,'example':2,'acquisition':2,'and':8,'is':1,'modern':1,'it':1,'deep':1,'high':1,'as':1,'in':2,'turn':1,'possibility.':1,'till':2,'amoeba':1,'star':3,'trundles':1,'molecule':1,'effect':1,'offshoot':1,'important':1,'interval':1,'portion':1,'time':2,'the':1,'having':1,'lying':1},'twig-like':{'angle':1},'thick':{'for':1,'as':1,'but':1,'.':1,'enough':1,'treacly':1,'in':1,'mist':1,'or':1,'vapours':1},'tangle':{'of':1},'electronic':{'constitution':1,'cyclones':1,'work':11,'works.':1,'activity':1,'works':15},'illustrate':{'a':1,'evolution':1,'natural':1,'we':1,'.':1,'the':6},'power.':{'the':1},'approximately':{'and':1,'equally':1,'22':1,'calculated':1,'twenty-seven':1,'to':3,'278':1},'youthfulness':{'a':1},'colossal':{'expenditure':1,'family':1,'reservoir':1},'accretion':{'may':1,'of':1},'compromise':{'is':1},'observations':{'bearing':1,'showing':1,'he':1,'furnish':1,'of':1},'inflate':{'their':1},'john':{'and':1,'dalton':1,'the':1,'murray':3,'dewey':1},'dogs':{'are':1,'do':1,'for':1,'have':1,'elephants':1},'kiwi':{'another':2},'intestine':{'with':1},'happily':{'included':1},'diversified':{'ooze':1},'rejected':{';':1},'nurse-frog':{'alytes':1},'scorpions':{'and':2},'cereal':{'.':2},'corresponded':{'to':1},'flightless':{'and':1,'toothed':2,'bird':2,'wings':1},'greater.':{'and':1},'guile':{'illustration':1},'magnet':{'and':1,'a':1,'is':4,'there':1,'.':4,'to':1,'62':1,'279':1,'the':2,'282':1,'lifting':1},'air.':{'the':1,'iv':1},'preformed':{'weak':1,'bandage':1},'damage.':{'1.f.3':1,'it':1},'unmistakably':{'to':1},'iron':{'and':2,'copper':2,'last.':1,'an':1,'are':1,'in':1,'further':1,'blue':1,'for':1,'behaves':1,'should':1,'to':1,'which':1,'you':1,'has':1,'until':1,'filings':2,'but':1,'would':1,'age':1,'will':1,'or':2,'attracting':1},'tackled':{'a':1},'contrasted':{'with':3},'powers':{'156':1,'of':1,'is':1,'.':1,'note':1,'hitherto':1},'encumbered':{'with':1,'by':1},'regulus':{'98.8':1},'respecting':{'the':1},'lull':{'and':2,'organic':1,'calls':1,'to':1,'s':1,'describes':1,'the':1,'r':1,'points':1},'vigorous':{'and':2,'palaeolithic':1,'as':1,'but':1,'race--many':1,'race':1,'animal':1,'the':1},'contents':{'introduction':1,'is':1},'forced':{'to':1,'the':1,'molten':1},'strength':{'and':1,'enormous':1,'prompted':1,'unabated':1,'of':1,'able':1,'to':1,'in':1,'the':1},'prehensile':{'suckers':1,'tail':2},'convenient':{'to':1,'unit':1},'latter':{'will':1,'is':2,'there':1,'we':1,'part':2},'half-brutish':{'prehistoric':1},'little.':{'illustration':1},'foam-bells':{'on':1},'subjects':{'with':1},'forces':{'of':7,'animals':1},'transmit':{'vibrations.':1},'swims':{'on':1,'about':1,'right':1,'well':1,'actively':1,'in':1,'with':1},'explanation':{'even':1,'we':1,'that':1,'of':3,'what':1,'.':1,'to':1,'offers':1,'once':1},'circles':{'without':1,'round':3},'benefactress':{'while':1},'ebook':{'outline':2,'for':1,'of':2,'is':2,'complying':1,'20417':1,'or':2},'anatomy':{'physiology':1,'.':1},'extending':{'below':1},'echoes':{'of':1},'phase':{'amid':1,'adapted':1,'of':1},'nutritive':{'reproductive':1,'chains':3,'material':2,'yolk':1,'sea-dust':1,'contributions':1},'grave':{'difficulties':1,'error':1},'nostrils':{'very':1,'on':1},'calculated':{'and':1,'to':1,'that':3,'using':1,'.':1},'inferred':{'from':3},'swamp':{'and':2,'our':1,'.':1},'accounted':{'for':3,'for--may':1},'deeply':{'saturating':1,'being':1,'into':4,'here':1,'buried':1,'with':1},'eel.':{'illustration':1},'notion':{'of':3},'fitted':{'a':1,'to':1},'reserve':{'.':1},'spectroscopic':{'point':1},'eminent':{'astronomers':3,'physicists':1},'sea-anemone':{'a':1,'may':1,'is':2,'gripped':1,'s':1,'72':1,'which':1,'sixty':1,'with':1,'can':1},'subtle':{'processes':1,'that':1,'inter-relations':2,'chemical':1,'cleaver':1,'inter-relations--the':1},'enjoyed':{'about':1},'sharks':{'the':1},'resemblance':{'142':1,'to':7,'being':1,'of':1,'is':2,'in':2,'camouflage':1,'lies':1,'so':1,'between':3,';':1,'hawk':1,'tells':1},'vaporised':{'by':1},'guidance':{'of':1},'appended':{'to':1},'entities--matter':{'ether':1},'geologist':{'utilises':1,'is':1},'deepest':{'sense.':1},'clefts':{'openings':1,'are':1},'pursuing':{'food':1,'what':1},'adequate':{'idea':1,'for':1,'lasting':1},'dynamo--magnetism--ether':{'and':1},'position--it':{'is':1},'fathoms':{'and':1,'though':1,'it':1,'five':1,'have':1,'so':1,';':1},'predecessor':{'.':1},'do':{'and':2,'nothing':2,'in':3,'.':5,'copyright':1,'when':2,'actually':1,'stories':1,'we':7,'that':1,'very':2,'they':2,'not':56,'with':9,'man':1,'occur.':1,'keeping':1,'practically':1,'this':4,'still.':1,'so':2,'the':2,'or':1,'otherwise':1},'leisure':{'to':1,'time--wherein':1,';':1},'yielded':{'to':1,'two':1},'space--ether':{'pervades':1},'watson':{'showed':1},'haunted':{'the':1},'roundabout':{'road':1},'conservator':{'of':1},'vividly':{'what':1,'interprets':1},'du':{'temps':1},'dr':{'.':18},'runs':{'through':1,'totteringly':1,'so':1,'for':1,'in':1},'tantalising':{'dream':1},'sky.':{'the':1},'web-footed':{'bird':1},'irregularities':{'of':1},'iron--and':{'is':1},'rung':{'on':1,'or':1},'voice--surely':{'one':1},'analytical':{'work':1},'freshwater':{'animals':5,'snail':1,'basins':2,'mammals':1,'fish':1,'polyp':1,'mussels.':1,'but':1,'.':1,'hydra':2,'race':1,'floods':1,'mussel':2},'steam':{'and':2,'or':2,'which':1},'captures':{'its':1},'venatici':{'is':1},'observer':{'the':1,'through':1},'condensed':{'and':2,'matter':1,'the':1,'to':1,'in':1},'observed':{'that':4,'phenomena':2,'had':1,'however':1,'one':1,'through':1,'in':1,'the':1,'.':1,'with':1,'by':1,'more':1},'tree-sloth':{'of':1},'arthropods':{'and':1,'such':1,'like':1,'which':1},'donations.':{'to':1},'torrents':{'of':1},'cattle':{';':1,'the':1},'miserable':{'specimen':1},'disappear.':{'illustration':1},'draws':{'for':1},'1917.':{'a':1,'this':1,'glass':1},'away':{'and':2,'the':3,'into':2,'back':1,'an':2,'down':1,'in':5,'from':10,'beneath':1,'when':2,'.':8,'chewing':1,'under':1,'is':1,'trillions':1,'altogether':1,'immediately':1,'by':3,'e.g':1,'many':1,'leaving':1,'entirely':1,'or':3},'sites':{'of':1},'unable':{'to':3},'drawn':{'on':2,'across':1,'into':3,'approximately':3,'.':1,'to':1,'in':4,'engraved':2,'by':2,'out':1},'previous':{'chapter':4,'energy':1,'experience':1,'one--the':1,'article':1,'line':1,'page':1,'day--a':1},'encounters':{'occur':1},'hatching.':{'reflex':1},'co.':{'harpy-eagle':1,'penguins':1},'circle--which':{'means':1},'we':{'forget':1,'soon':1,'discovered':1,'not':1,'go':3,'follow':1,'find':18,'discern':1,'had':2,'should':18,'to':2,'include':1,'might':3,'hope':2,'then':2,'get':18,'read':1,'watch':2,'cannot':29,'know':50,'presume':1,'mentioned.':1,'judge':1,'now':6,'dare':2,'arrange':1,'easily':1,'ever':1,'conceive':1,'leave':1,'continue':1,'lose':1,'found':2,'hasten':1,'mean':6,'often':1,'ascend':1,'briefly':1,'see':36,'are':47,'pass':2,'fail':1,'penetrated':1,'will':5,'detect':1,'confess':1,'may':41,'state':1,'learned':1,'approach':1,'exercise':1,'refer':1,'notice':1,'knew':1,'learn':1,'ascribed':1,'here':1,'imagine':1,'put':2,'come':3,'obtained':1,'received':1,'study':2,'owe':6,'agree':1,'turn':4,'usually':2,'think':6,'already':1,'can':39,'feel':1,'lengthen':1,'actually':1,'miss':2,'speak':6,'stare':1,'use':3,'described':1,'spoke':1,'would':3,'next':1,'start':1,'live':1,'call':26,'breathe':1,'wish':1,'understand':2,'gain':1,'believe':4,'must':42,'count':1,'look':4,'recall':1,'handle.':1,'aim':1,'suppose':1,'ought':1,'were':3,'could':13,'expect':1,'control':1,'compare':1,'have':124,'do':24,'almost':1,'describe':1,'moved':1,'consider':4,'say':6,'want':1,'need':4,'seem':3,'saw':13,'thought':1,'no':1,'belong':1,'take':4,'behold':1,'picture':1,'draw':2,'repeat':1,'connect':1,'utilise':1,'shall':23,'confined':1,'stop':1,'await':1,'reach':4,'reflect':2,'admire':1,'lay':1,'recognise':1,'remember':1,'emphasise':1,'reproduce':1,'allow':2,'hear':1},'rudimentary':{'gills':1},'terms':{'imposed':1,'of':21,'will':1,'experimenting':1,'from':1,'than':1},'discussion.':{'some':1},'wm':{'.':1},'bipeds--we':{'must':1},'enters':{'a':1,'the':3},'travellers':{'which':1},'clues':{'which':1,'in':1},'caledonia':{'which':1},'stricter':{'sense':1},'linkage':{'of':1,'between':1},'kitchen':{'.':1},'received':{'opinion':1,'the':4,'from':1,'written':1,'less':1},'climate':{'and':4,'a':1,'calls':1,'for':1,'of':2,'is':1,'became':1,'has':2},'pelomyxa':{'sometimes':1},'cox':{'arrangement':1},'ill':{'all':1,'suited':1},'nordics':{'afghans':1},'germinates':{'after':1},'cod':{'feeding':1,'family':1},'receives':{'a':1,'160':1},'unsunned':{'.':1},'disappears':{'before':1,'from':2,'in':1},'collecting':{'into':1,'centre':1,'centres':1},'tough':{'living':1},'soap':{'made':1,'bubble':4,'which':1},'ganymede':{'a':1},'engulfs':{'its':1,'it':1},'tons':{'on':2,'.':1,'in':1,'to':1,'of':6},'866400':{'--':1},'eventful':{'life-history':1,'thing':1,'day':1,'retention':1},'merchantibility':{'or':1},'speak':{'of':12,'the':1,'picturesquely':1,'unpacked':1,'got':1},'broadening':{'still':1},'sperm-cells.':{'the':1},'engines':{'.':1},'flexible':{'mounting':1},'thrice':{'the':1},'leech':{'called':1},'spermatozoon':{'has':1,'fertilises':1,'or':1},'repelled':{'by':1},'families':{'genera':1,'like':2},'innocent':{'seaweed':1,'creatures':1},'plebeian':{'crab-apple':1},'attacked':{'by':1,'however':1},'concerning':{'life':1,'tax':1,'the':1},'overtax':{'the':1},'millionth':{'of':2},'coherent':{'vane':1,'.':1},'them--a':{'common':1},'elvers':{'come':1,'snuggle':1,'.':1},'applied':{'to':7,'the':2,'however':1},'has':{'migrated':1,'enormously':1,'just':1,'developed':1,'over':1,'discovered':2,'ceased':2,'its':10,'captured':2,'certainly':1,'much':2,'torn':1,'had':3,'laid':1,'destroyed':1,'to':14,'only':2,'suffered':1,'guided':1,'happened':1,'meant':2,'his':1,'far':1,'attained.':1,'begun.':1,'five':1,'got':1,'not':8,'sorted':1,'now':3,'continued':1,'learned':2,'four':2,'annihilated':1,'lost':2,'always':2,'solved':1,'mastered':1,'become':14,'cooled':1,'declared':1,'often':3,'ten':1,'some':1,'somehow':1,'calculated':1,'gnawed':1,'begun':1,'led':2,'penetrated':2,'even':1,'shown':3,'said':2,'for':1,'frond-like':1,'yet':1,'written':2,'various':1,'moons':1,'probably':1,';':2,'ever':3,'claws':1,'attended':1,'recently':2,'risen':1,'however':1,'disappeared':1,'broken':1,'found':2,'put':1,'dissipated':1,'come':5,'thrown':2,'received':1,'great':1,'mingled':1,'language':1,'of':3,'changed':3,'conquered':2,'consequently':1,'raised':1,'already':1,'followed':1,'slipped':2,'instruments':1,'transit':1,'two':3,'brought':2,'agreed':1,'been':136,'reached':2,'precisely':1,'spawned':1,'given':5,'from':1,'fallen':1,'harnessed':1,'remained':1,'three':1,'long':1,'screened':1,'2':1,'wonderfully':1,'therefore':1,'passed':1,'taken':5,'slowly':1,'entered':2,'.':1,'more':2,'suggested':1,'himself':1,'thus':1,'completed':1,'occurred':1,'but':1,'known':1,'worked':1,'gills':1,'arisen':1,'carried':1,'made':3,'this':1,'shrunk':1,'moulted':1,'nine':1,'many':1,'tackled':1,'called':1,'gone':5,'proved':1,'played':1,'almost':4,'likewise':1,'turned':1,'an':4,'helped':1,'in':3,'affinities':1,'occupied':1,'shown.':1,'grown':1,'influenced':1,'built':1,'no':3,'divided':3,'also':1,'absorbed':1,'adapted':1,'degenerated':1,'effected':1,'added':2,'gradually':1,'eight':1,'plenty':1,'a':20,'succeeded':3,'endeavoured':1,'moved':1,'upset':1,'implied':2,'so':3,'very':1,'the':8,'realised':1,'left':1},'conviction':{'the':1,'that':1},'comprehension.':{'illustration':1},'air':{'and':4,'all':1,'there':3,'just':2,'is':6,'reaches':1,'as':1,'through':1,'at':3,'in':3,'from':1,'acts':2,'when':1,'.':13,'to':1,'which':3,'6':1,';':2,'has':4,'was':1,'into':1,'be':1,'we':1,'over':1,'goes':1,'on':1,'but':1,'underneath':1,'262':1,'struggle':1,'waves':1,'with':2,'by':3,'must':1,'a':3,'water':5,'of':1,'35':1,'loses':1,'will':1,'the':2,'or':1},'aim':{'of':2,'at':1},'voluminous':{';':1},'abrupt':{'and':1},'applies':{'also':1,'the':1,'whatever':1,'to':3},'aid':{'of':1,'.':1},'voice':{'we':1,'rose':1,'is':1,'broadened':1,'due':1,'but':1,'.':1,'became':1,'expresses':1,'the':1,'was':2,'becoming':1},'amphibians--the':{'reptilian':1},'cavern':{'of':3,'the':2,'179':1},'cylinder':{'of':1},'plover':{'has':1,'from':1},'have':{'planetary':2,'followed.':1,'quoted':1,'migrated':1,'scattered':1,'discovered':4,'sunk':2,'mentioned':2,'its':1,'just':9,'regarded':1,'had':2,'to':14,'only':4,'spread':2,'meant':2,'then':1,'good':1,'returned':1,'very':3,'furnaces':1,'words':1,'shared':1,'not':12,'now':1,'illustrated':3,'failed':1,'lost':1,'ceased':1,'always':1,'traced':1,'prolonged':1,'watched':1,'mastered':1,'dealt':1,'served':1,'cooled':3,'dwindled':1,'tenanted':1,'often':1,'burst':1,'acquired':1,'some':2,'direct':1,'identified':1,'carefully':1,'taught':2,'safeguarded':1,'further':1,'living':1,'shown':4,'said':9,'discovered--pulling':1,'missed':1,'apparatus':1,'definite':1,'behind':1,'won':1,'emerged':1,'moons':1,'rotted':1,'got':4,'learned':1,'ever':1,'told':1,'we':1,'full':1,'originated':1,'peculiarly':1,'sprung':1,'here':1,'reason':2,'will':1,'found':7,'put':3,'proceeded':1,'come':4,'gained':2,'on':2,'great':1,'reared':1,'journeyed':1,'of':4,'changed':1,'greatly':1,'conquered':1,'fallen':1,'already':5,'gone':3,'appeared':1,'delighted':1,'visible':1,'maintained':1,'another':2,'reached':1,'risen.':1,'given':2,'described':1,'become':8,'exposed':1,'three':1,'been':88,'their':7,'recognised':1,'combined':1,'passed':1,'resulted':1,'travelled':1,'closed':1,'thrown':1,'from':1,'lived':2,'lungs':1,'both':1,'moved':1,'differences':1,'occurred':1,'but':1,'taken':2,'heat':1,'races':1,'protections':1,'known':1,'probably':1,'worked':1,'removed':1,'entered':3,'arisen':4,'partially':1,'made':6,'succeeded':2,'this':1,'neap':1,'considered':1,'evolved':2,'many':2,'more':1,'called':1,'at':1,'admired':1,'seven':1,'chlorophyll':1,'proved':4,'remained':2,'is':1,'thus':1,'an':3,'astonished':1,'heard':2,'as':1,'something':1,'planets':1,'in':9,'seen':18,'apparently':1,'any':1,'grown':1,'varied':2,'inborn':1,'no':14,'rather':1,'lit':1,'also':2,'stimulated':1,'read':1,'several':1,'used':1,'what':2,'most':1,'discredited':1,'plenty':1,'nothing':1,'such':1,'yielded':1,'revealed':1,'a':25,'profited':1,'scarcely':1,'to-day':3,'bilateral':2,'stupendous':1,'nevertheless':1,'thought':1,'implied':1,'so':1,'lamented':1,'mechanical':1,'the':5,'counted':1,'bodies':1,'left':2},'crowning':{'instance':1,'examples':1,'advantage':1},'exceptionally':{'smooth':1},'sting':{'the':1,'which':1,'.':1},'trilobites':{'crustaceans':1,'illustration':1,'were':1},'brake':{'on':1,'.':1},'blame.':{'after':1},'comparative':{'anatomy':1,'distances':1,'nearness':1,'psychology':1,'sizes':3},'undulatory':{'movement':1},'brilliantly':{'luminous':1},'m.c.':{'.':1},'descent':{'of':6,'that':1,'from':1,'to':1},'conclusions.':{'the':1},'patent':{'and':1},'demonstration':{'of':1},'centre.':{'as':1},'punctuation':{'of':1},'varies':{'as':1,'.':1,'greatly':1,'periodically':1},'parasitism':{'it':1},'diplodocus':{'as':1},'sheltered':{'may':1,'life':1},'accumulating':{'a':1,'and':1,'age':1,'.':1},'monarch':{'of':1},'lithium':{'three':1},'crevices':{'among':1},'wheel':{'be':1,'rapidly':1,'that':1,'when':1,'is':1,'turned':1,'will':1,'as':3,'animalcule':1,'was':1},'independent':{'methods--one':1,'of':1,'orbits':1,'stellar':1,'lives':1,'existence':1},'86500':{'9':1},'hang':{'on':1},'evil':{'associations':1},'hand':{'feed':1,'and':8,'holds':1,'is':1,'some':1,'gregariousness':1,'as':2,'in':2,'miss':1,'from':1,'there':1,'when':3,'.':1,'till':1,';':1,'was':2,'thus':1,'it':1,'with':1,'made':1,'of':8,'sometimes':1,'so':1,'the':2,'where':1},'kinnaman':{'taught':1},'patagonia':{'there':1,'.':1},'nip':{';':1},'centred':{'in':1},'kept':{'lizzie':1,'from':2,'by':1,'for':1},'whereby':{'new':1,'the':1,'distinctively':1,'energy':1},'likes--and':{'the':1},'engrained':{'instinctive':1,'enregistered.':1},'wisps':{'of':1},'contact':{'information':1,'sy':2,'links':1,'information:':1,'.':1,'the':1,'with':2},'elongated':{'and':1,'palm-bones':1,'mobile':1,'outermost':3,'oval':1,'bodies':1},'furneaux':{'life':1},'centres':{'of':7,'drawing':1},'the':{'limited':1,'practicability':1,'psycho-analyst':1,'magnetic':5,'comparatively':1,'dynamic':1,'four':3,'chameleons':1,'aegir':4,'controversial':1,'oldest':6,'muzzle':1,'brackish':1,'physiological':3,'similarity':2,'sunlit':1,'fine-grained':1,'thinnest':2,'under':3,'humerus':1,'risk':5,'arboreal':5,'aurora':5,'oceans':1,'pigment':1,'smack':1,'coal-measures':1,'gratification':1,'east.':1,'fingers.':1,'conception':2,'bringing':1,'monkeys':2,'vast':9,'internally':1,'prize':1,'parrot':1,'present.':1,'correct':1,'danger-signal':1,'succession':2,'jumna':1,'jungle-fowl':1,'breast-bone':3,'cave-lion':1,'achievements':2,'force':3,'monotonous':1,'faintest':1,'excited':1,'feathers':6,'seas.':2,'nail':2,'surrounding':9,'second':18,'street':2,'infiltration':1,'inanimate':1,'blue':6,'change.':1,'unborn':3,'beaten':1,'consequent':1,'rest.':1,'reconstruction':2,'chromosphere':4,'new':21,'net':1,'protozoon':1,'surface--the':1,'evolving':1,'lithosphere':1,'men':6,'residual':1,'atoms':26,'seven-weeks-old':1,'protection':2,'ploughed':1,'aid':1,'active':4,'evolutionist':2,'cardboard':1,'contraction':2,'dry':19,'connaissance':1,'surface-atoms':1,'frog-hopper':1,'light.':1,'credit':3,'changes':5,'skull-cap':3,'diameter':3,'stray':1,'straw':1,'highly':1,'skull-walls':1,'visible':2,'medium':5,'total':6,'unit':2,'answers-back':1,'remainder':1,'arms':6,'dog-toothed':1,'mightiest':1,'calm':1,'water-spider':2,'type':2,'pistil':1,'females':3,'lungs':1,'wary':1,'horsetail':1,'whirling':1,'glass':6,'warm':2,'adult':3,'continual':1,'organic':1,'midst':1,'circumstances':1,'abundance':3,'word':10,'mimickers':4,'accomplishment':1,'eclipse':1,'worm':3,'roof':3,'theories':2,'mammalian':1,'era':2,'appendage':1,'animal.':1,'clock-work':1,'mud-fishes':1,'phrase':7,'alternating':1,'allantois':2,'serpent':1,'climax':3,'shore.':1,'powerfulness':1,'caution':1,'oil-sheet':1,'present-day':4,'advancing':3,'absolute':2,'end':22,'thing':2,'song':1,'nuts':2,'very':19,'hot':1,'significance':3,'answer':9,'ordinary':12,'ancestor':1,'massive':2,'poker':4,'rise':2,'minority':1,'mouths':2,'ptarmigan':2,'abdomen':1,'diagram':9,'dinosaurs':1,'wrong':2,'pearl-bearing':1,'vase':1,'domed':2,'types':1,'amoeboid':1,'leplay':1,'third':11,'spout':1,'headquarters':1,'greek':7,'green':8,'ultimate':4,'things':1,'sun.':13,'order':9,'wind':9,'blind':1,'interpretation':3,'alternation':1,'sheltering':1,'orang':7,'underside':1,'fore-limbs':4,'thesis':1,'ancients':2,'spontaneous':2,'famille':1,'breeding-place':2,'fit':1,'crew':1,'better':2,'woolly-haired':1,'production':3,'hidden':1,'gateways':1,'sea-water':3,'swim-bladder':1,'combination':2,'tree-stems':1,'young.':1,'revelations':1,'giraffe':1,'effects':2,'monarch':1,'stars;':1,'bank':2,'bread':1,'shadows':1,'dingo':2,'rocks':9,'good':4,'fertilised':8,'victory':1,'arrow':2,'side':4,'associative':1,'telescope.':1,'development':10,'telescope':10,'series':2,'principles':3,'solution':4,'contracting':1,'wave-lengths':1,'laboratory':3,'dawn':9,'ring':2,'pigments':1,'gibbon':5,'quality':5,'ice-sheets':1,'method':9,'reader':6,'heavenly':2,'revolving':1,'newly':4,'size':25,'langur':1,'foundation':12,'perception':1,'carcass':1,'wave-length.':1,'eternal':1,'strata':1,'free':4,'standard':1,'sensory':3,'skin.':1,'ancient':6,'formation':5,'struggle':15,'estimate':1,'heat':11,'ultra-violet':1,'publication':1,'enormous':5,'grasses':1,'days':1,'adjustment':1,'baltic':2,'purpose':2,'arrows':1,'wasp':2,'unlit':1,'peculiarity':1,'scissors':1,'thick':1,'ditch':2,'electronic':2,'mercury':1,'pelagic':1,'top':11,'neck':4,'heights':1,'legs':2,'genesis':1,'vapoury':1,'kiwi':2,'fiery':1,'instreaming':1,'fibrous':1,'diversified':1,'sciences.':1,'bell.':1,'floor.':1,'wisdom':1,'nurse-frog':1,'glumes':1,'somewhat':2,'evil':1,'peculiar':2,'flightless':1,'distance':13,'yerkes':7,'tree':2,'atom.':1,'final':5,'project':31,'matter':7,'flame':1,'historical':2,'shore-waters':1,'feeling':1,'acquisition':1,'groaning':1,'pliocene':5,'mind':18,'spectrum':9,'raw':4,'seed':1,'manner':1,'nervures':1,'rock-pool':1,'relatively':8,'strength':1,'prehensile':1,'thoroughly':1,'latter':7,'potentialities':1,'snow':3,'sound':3,'toothed':1,'subjects':1,'doors':2,'beta-rays':1,'shallow':2,'permian':8,'multicellular':1,'king-crab':1,'centres':1,'changefulness':1,'vermiform':2,'mouth':10,'letter':2,'echoes':1,'coil':4,'nutritive':1,'refractor':2,'ultramicroscope':1,'photosphere.':1,'episode':1,'professor':1,'metal':3,'dog':5,'orderly':1,'points':2,'principle':5,'sun':188,'nineteenth':8,'notion':2,'marvel':1,'pollen':1,'spikelets':1,'insects':2,'sea-anemone':4,'attempts':1,'subtle':1,'availability':1,'lessons':1,'ear.':1,'resemblance':5,'quaint':2,'pleistocene':2,'sentence':1,'geologist':2,'fifty-foot':2,'rich':1,'gods':1,'population':3,'plate':4,'mixture':2,'above':11,'fluid':2,'foremost':1,'bat':3,'covering':1,'bay':1,'discs':1,'contrast':2,'freshwater':6,'ears':1,'lettering':1,'observer':1,'habit':5,'radium':4,'outgoing':1,'zones':1,'tree-sloth':1,'full':14,'radius':1,'result':15,'disturbing':1,'rarity':2,'best':4,'subject':4,'pebbles':1,'capacity':2,'palaeolithic':2,'rings':1,'artificial':1,'paternal':1,'mud':7,'score':2,'toad':3,'simplest':9,'approach':1,'hatching.':1,'discovery':23,'terms':12,'nature':23,'confusion':1,'weak':1,'physicist':5,'sand-crab':1,'lurching':1,'larynx':1,'aquarium':1,'extent':2,'carbon':1,'flowering':1,'debt':1,'well-lighted':1,'kitchen':1,'tyranny':3,'behaviour':16,'climate':3,'outcome':13,'sperm-producer':1,'triggers':1,'earth.':7,'heating':1,'feathering':1,'cod':2,'distinction':2,'genus':1,'fore-leg':2,'repertory':1,'discolorations':1,'inquisitive':1,'purling':1,'path':5,'grazing':1,'sperm-cells.':1,'basis':3,'union':3,'three':6,'tiny':3,'trigger':6,'interest':1,'fry':2,'exactness':1,'spermatozoon':3,'life':7,'beach.':1,'deeper':2,'plebeian':1,'eastern':1,'abyssal':1,'conifers':1,'millionth':2,'mazy':1,'child':6,'elvers':1,'centrosome':1,'ether.':1,'exception':1,'adaptations':1,'air':39,'aim':1,'neat':1,'fainter':1,'property':1,'study':6,'natives':1,'seven':3,'crowning':1,'equator':5,'photographer.':1,'player':1,'comparative':3,'undulatory':1,'mouse':1,'descent':2,'belle':1,'punctuation':1,'daughter-units':2,'siamang':1,'complex':1,'peopling':3,'belly':1,'reptilian':2,'vegetable':1,'snow-line':1,'several':1,'european':2,'wheel':7,'independent':1,'georgics':1,'milky':13,'tops':1,'rain':1,'hand':9,'characters':1,'tune':1,'tassel':3,'stimuli':1,'ocean':5,'materials':1,'greatest':13,'arrow-worms':1,'claims':1,'marsupials':1,'musical':1,'left':5,'sea-skimmers':1,'just':1,'planetesimals':1,'vaporisation':1,'sporting':1,'mending':1,'disguise':2,'neanderthalers':1,'human':25,'facts':15,'yes':1,'emergence':7,'previous':3,'thyroid':3,'terrific':1,'hills':2,'infinitely':1,'old-fashioned':1,'royal':1,'salmon--forming':1,'evidences':3,'thickening':1,'long-lost':1,'board':1,'gaboon':2,'east':1,'eocene':2,'laying':1,'elevation':1,'advances':1,'survival':1,'sussex':1,'vulture':1,'possible':3,'forester':1,'photosphere':9,'birth':2,'partridge':1,'shadow':2,'rough-and-tumble':1,'shoulder':1,'war.':2,'insurgent':1,'precise':3,'sand-hoppers':2,'autumn.':1,'x-rays.':1,'enregistered':2,'mosquito':2,'night':1,'amoebae':1,'portuguese':2,'right':12,'old':13,'people':2,'crown':2,'dead':1,'clawed':1,'winds':1,'inorganic':2,'rill':1,'intellect':1,'orchid':1,'dense':1,'rhine':1,'bottom':6,'ear':7,'opposite':5,'fox':2,'distrust':1,'ice':3,'flounder':2,'loins':1,'tertiary':1,'seals.':1,'colour-cells':2,'beating':2,'monkey-ape-man':1,'palatable':1,'energy':36,'illustration':5,'cork':1,'shifting':1,'capacious':1,'flinty-shelled':1,'blackest':1,'properties':2,'chapter':1,'skin-twitching':1,'limitation':1,'boiling':1,'cloudlets':1,'ribs':1,'o':1,'wave-length':1,'horizon':1,'herring-gull':1,'efforts':1,'ores':1,'lamprey':1,'primitive':3,'cloud-screen.':1,'dilemma':1,'variations':1,'scantier':1,'peppered':1,'son':1,'contrasts':1,'bricks.':1,'doctrine':1,'spores':1,'palaeozoic':4,'indispensable':1,'flying':9,'sunlight':7,'class':2,'conservation':1,'physicists':2,'fraction':1,'dorsal':1,'war':4,'lowest':5,'head':8,'marten':1,'form':10,'fully-formed':1,'becoming':1,'differences':2,'peninsula':1,'quiet-flowing':1,'same.':1,'solar':35,'minuteness':2,'true':5,'otter':3,'continuance':3,'reproductive':2,'ancestral':1,'bounds':1,'centipede':1,'economic':1,'bird-dropping':1,'egg-eating':1,'palm':1,'cosmos':1,'stages':1,'temper':1,'passenger':1,'juvenile':2,'strengthening':1,'hotter':1,'heidelberg':4,'seeds--and':1,'mirror':2,'palm;':1,'evidence':2,'candle':1,'ship':3,'physical':4,'mediterranean':3,'solicitation':1,'inborn':3,'floor':8,'font-de-gaume':2,'negatively-electrified':1,'tip':4,'reality':3,'successful':2,'nestling':1,'setting':2,'papers':1,'superfluous':1,'robber-crab':5,'picture':7,'ordovician':2,'palms':1,'teats':1,'braking':1,'diet':1,'genealogical':2,'irs.':1,'dullest':1,'discharge':2,'thorax':1,'immemorial':1,'stamens':2,'bullet':2,'daily':1,'collared':1,'gorilla':4,'reception':1,'time':19,'skull-cap.':1,'serious':1,'nuclei':1,'tigris':1,'breadth':1,'irrigation':1,'concept':1,'chain':1,'limbless':1,'colour-change':1,'varying':3,'brownian':4,'focus':1,'hind-legs':2,'nerve-cord.':1,'skin':14,'jointed-footed':1,'primeval':4,'retention':1,'layers':2,'inverse':1,'essentials':1,'father':5,'passage':4,'environment':4,'unpleasant':1,'reptiles':2,'walking-fish':2,'ulna':1,'division':1,'protective':2,'month.':1,'advantage':2,'rotifer--we':1,'liability':1,'aesop':3,'first-known':1,'nesting':1,'exact':2,'minute':3,'cool':1,'dim':1,'level':4,'sedimentary':3,'gum':1,'magnet':4,'crustacean':1,'backboneless':2,'speculation':1,'accumulation':1,'upper':23,'work':19,'occurrence':3,'findings':1,'full-grown':2,'piltdown':5,'hair.':1,'trent':4,'bacteria':2,'spectral':1,'leaf-butterfly':1,'constitution':4,'assistance':1,'axes':1,'stomach.':1,'current':6,'supporting':2,'coccyx':1,'honour':1,'hairs':3,'evolution-idea':4,'anvil.':1,'whiteness':1,'water':49,'guise':1,'cave-bear':1,'twentieth':1,'address':1,'dwindling':2,'teacher':1,'change':5,'pearly':8,'brilliant':1,'shift':2,'dublin':1,'trial':2,'stomachs':1,'suggestion':3,'weird':1,'copper.':1,'mimicked':4,'elect':1,'seashore':8,'littoral':2,'cuttlefishes':3,'working':2,'sake':1,'positive':2,'anatomical':2,'prey':2,'flaunting':1,'negroes':1,'australian':6,'angels':1,'fish-eating':1,'diurnal':1,'water-ouzel':1,'apparent':3,'malay':1,'minnows':2,'appendix':1,'virtue':1,'cases':1,'easiest':1,'opossums':2,'sum-total':1,'sea-anemones':2,'cat':1,'hardest':2,'jetsam':1,'mortality':1,'following':6,'making':7,'fauna':6,'coral':3,'stimulating':1,'streak':1,'heart':6,'portals':1,'wrist-bones':1,'reflector':2,'figure':5,'frogs':1,'bulkiest':1,'stroke':1,'chin':1,'octopus.':1,'rays':15,'requirements':1,'winter':5,'comb-bearers':1,'inheritance':1,'dispositions':1,'means':4,'species':3,'chemical':6,'vital':5,'candle.':1,'fourth':4,'elephant':4,'dominance':1,'economy':1,'burrowing':1,'southern':3,'date':2,'behaviour--experimenting':1,'man':6,'branches':10,'outline':9,'liquid':4,'unimportant':1,'corona':3,'darkened':1,'african':2,'basket':1,'bolometer':1,'outflowing':2,'shield':1,'gradual':6,'pointed':1,'years':1,'brain':23,'experiments':6,'statements':1,'cold':4,'insurgence':2,'birds':3,'tendency':5,'nucleus.':2,'solitary':1,'limbs':1,'ice-fields':2,'thumb':5,'rhizopods':2,'interesting':3,'presence':4,'flesh-and-blood':1,'aquitania':1,'attraction':1,'creations':1,'spacious':1,'main':28,'meridian':2,'bird.':1,'evolution':45,'records':3,'archaeozoic':1,'tails':1,'water-shrew.':1,'not':1,'widespread':1,'halo':1,'term':2,'name':4,'seaweed-growing':1,'advent':1,'gill-slits':1,'careless':1,'jellyfish':2,'rock':9,'turtle':2,'sugary':2,'square':3,'reeds':1,'torch':1,'treacherous':3,'challenger':1,'fires':1,'year':6,'monitors':1,'neighbourhood':1,'living':18,'factors':6,'amnion':2,'greeks':3,'increase':2,'miles':1,'ladder':1,'overflowing':1,'ascendant':1,'theory':14,'soap-bubble':1,'divergence':3,'possibility':12,'quite':1,'quart':2,'intruding':1,'advantages':2,'sunlight.':1,'fuller':1,'obligation':1,'marine':2,'inevitable':1,'card':2,'care':1,'advance':2,'language':1,'selections':1,'transition':5,'british':5,'ostrich':1,'motion':2,'disguises':1,'place':8,'invalidity':1,'deep-sea':4,'close-set':1,'star':6,'frequent':2,'first':71,'origin':14,'one':21,'long':15,'conifer':1,'message':6,'open':29,'millions':3,'sheep':3,'little':5,'law':3,'silent':1,'spiral.':1,'bite':1,'callous':1,'plastic':1,'stimulation':1,'plains':2,'cooling':2,'2':1,'pockets.':1,'moisture':1,'white':11,'lingering':1,'vapours':1,'gravelly':1,'eyes':8,'way':18,'starfish':1,'brains':2,'canine':1,'seat':3,'photographic':9,'splendid':1,'pterodactyls':2,'cracks':1,'effective':1,'three-spined':1,'crowded':1,'coco-palm':1,'future':11,'fertilisation':1,'cards':2,'gigantic':1,'mariner':1,'photosynthesis':1,'sublime':3,'coconut':1,'rooks':1,'spectroscope:':1,'ant':3,'spectroscope.':1,'lens-shaped':2,'buried':1,'maximum':1,'zoo':1,'snout':2,'sciences':1,'potential':1,'fracture':1,'online':2,'interior':7,'performance':2,'jungle':5,'closer':1,'sure':1,'chromosomes':1,'normal':4,'azores':1,'indelible':2,'price':1,'molecule':1,'falls':2,'visitors':1,'beta':5,'successive':5,'pair':1,'thigh-bone':1,'average':7,'freshwaters':9,'hungry':1,'bustard':1,'tooth':1,'idea.':1,'quiescent':2,'salt':1,'laws':4,'detective':1,'walking':1,'discoverer':1,'merit':1,'gill-cover.':1,'bright':3,'threshold':1,'line':7,'ground':23,'slot':2,'nemesis':2,'ratio':2,'gulf':1,'germ-cell':1,'treasure':1,'proportion':2,'only':13,'down-breaking':1,'black':5,'uppermost':1,'down-rushing':1,'lighted':1,'supra-renal':2,'bittern':1,'freezing':1,'midriff':1,'truly':1,'duckmole':4,'remoter':1,'mud-flats':1,'negative':4,'lighter':2,'primates':4,'clearest':1,'pollen-nucleus':1,'fanciful':1,'parasitic':1,'morning':2,'naked':2,'penguins':1,'sea--the':2,'london':1,'pituitary':1,'vision':1,'kernel':1,'oven':1,'seas':6,'lancelets':1,'silurian':4,'stars--or':1,'relative':4,'1921':1,'stigma':1,'concentric':1,'wonder':2,'ways':5,'subsequent':1,'sites':1,'under-skin':2,'colours':4,'outside':4,'chimpanzees':1,'moons':2,'man.':2,'volvox':1,'notice':1,'parent':10,'eye':20,'screen':7,'rapidly':1,'big-brain':4,'sea.':5,'proterozoic':1,'article':2,'cities':1,'dates':1,'successes':1,'many':1,'region':2,'sodium':1,'quiet':1,'altamira':4,'man-ape':2,'flipper':3,'wheels':1,'expression':4,'surface.':2,'moon;':1,'generalisation':1,'brightly':1,'color':1,'colony':3,'period':7,'spinthariscope':1,'learning':1,'boar':1,'constant':1,'pod':1,'skeletons':2,'sun-spots':1,'fitful':2,'late':5,'west':3,'shortening':2,'combined':1,'reflex':1,'exhaustion':1,'fiftieth':1,'direction':9,'gist':2,'circumference':2,'haunt':1,'sea-horses':1,'external':3,'infusorians':1,'careful':2,'spirit':2,'robber':1,'case':37,'breast.':1,'caucasians':1,'developing':4,'co-ordination':1,'mount':4,'prominence':1,'dints':1,'situation':2,'margin':3,'moon.':1,'coolest':2,'characteristics':2,'nautical':2,'middle':5,'regularity':1,'sudden':3,'tse-tse':1,'eras':1,'unsounded':1,'beaver':5,'jackdaw':1,'floating':6,'movements':9,'rungs':2,'helmet':1,'different':8,'alphabet':1,'same':99,'eggs--up':1,'food':10,'inquiry':2,'agitated':1,'grain':1,'status':1,'oyster-catcher':1,'oil':1,'vestigial':2,'arctic':1,'director':1,'running':1,'edges':5,'delicate':3,'equatorials':1,'changing':2,'perennial':1,'constitutional':1,'severe':2,'frontispiece':1,'bottle':1,'model':1,'otherwise':1,'bodies':1,'overcrowding':2,'summer':3,'money':1,'armour':1,'egg-cell':1,'rest':6,'down-drifting':1,'rule.':1,'potentiality':1,'differentiation':1,'speed':16,'captured':1,'death':2,'widest':3,'hint':1,'bricks':3,'golden':1,'geological':6,'meteorite':1,'hind':2,'dovecot':1,'heavier':3,'skies':1,'real':2,'bitterling':3,'spectacular':1,'rules':1,'outermost':1,'non-digitate':1,'tissues':2,'early':13,'water-measurers':1,'vacuum':1,'cavern':3,'world':46,'part':7,'left-hand':3,'sensational':1,'fossils':2,'oxygen':3,'exquisitely':1,'velocities':1,'multifarious':1,'sieves':1,'benefit':1,'downward':1,'sharp':1,'twelve':1,'night-light':1,'exposed':1,'splash':1,'cathode':1,'pacific':2,'astronomer':6,'duration':1,'pasture':1,'racial':1,'ascent':6,'extinct':3,'gross':1,'calculating':1,'prolific':2,'intricacy':1,'memories':2,'tube':11,'moon':76,'pioneer':3,'critical':2,'lunar':2,'particles':12,'others--the':1,'welcome':1,'wheat':2,'buckling':1,'power':16,'sixth':2,'nails':1,'stereotyped':2,'substratum':1,'broken':1,'alps':1,'resurrection':1,'comparison':1,'stone':1,'ear-trumpet':2,'central':9,'piety':1,'insect':9,'shrimp':1,'addition':1,'wolf':3,'act':3,'pre-human':1,'amber':1,'freeing':1,'lands':2,'fertile':2,'sea-grass':1,'burning':1,'instruments':1,'spreading':1,'surinam':1,'spinal':4,'sneering':1,'rising':1,'elementary':1,'mark':1,'shrinking':2,'shells':1,'bristles':1,'literal':1,'dispersion':1,'strict':3,'world--weighs':1,'low':1,'stars':39,'house':2,'macaques':1,'hen':1,'bubble':4,'fish':6,'continents':3,'mammals':4,'prawn':1,'manipulative':2,'strenuous':1,'elimination':1,'parasites':2,'hottest':1,'land.':1,'wild.':1,'pull':1,'largest':9,'circulation':2,'stoneless':1,'multiplicity':1,'electroscope':1,'nearest':7,'pre-cambrian':1,'grasp':1,'shell.':1,'grass':3,'mimicked.':1,'moles':2,'vedda':1,'dangerous':1,'sinking':1,'lingula':1,'deep':10,'general':23,'imagination':3,'sun--measuring':1,'at':1,'planets':19,'cathedral':1,'corresponding':3,'film':3,'tedious':1,'beds':2,'inflated':1,'shore-haunt':6,'field':4,'prism':3,'polar':8,'vocabulary':1,'bacillus':1,'shelter':2,'planet.':1,'carnegie':2,'important':5,'nucleus':12,'marshes':1,'environing':1,'queensland':1,'sun--a':1,'pool':3,'network':1,'building':1,'condensation':2,'remote':1,'difficulties':7,'mimic':2,'tree-tops':1,'ovary':1,'starting':1,'original':13,'pheasant':1,'skeleton':2,'founder':1,'peacock':1,'lack':1,'muscle-fibres':1,'milt':1,'month':9,'light-waves':1,'upkeep':1,'welfare':2,'plodding':1,'causes':1,'synthetic':2,'stored-up':1,'number':14,'remarkable':2,'inexhaustible':2,'former':1,'tail':10,'boiling-point':1,'friction':1,'safety':3,'presentation':1,'activities':1,'turnips':1,'worse':1,'devonian':8,'chameleon':2,'far':9,'coloured':5,'worm.':1,'psychologist':1,'verb':1,'fan':1,'sandstones':1,'fall':3,'difference':2,'forking':1,'accompanying':1,'stimulus':2,'ceaseless':1,'list':1,'applicable':1,'caucasian':1,'large':9,'sand':1,'three-millionth':3,'small':11,'mammal':6,'locomotive':2,'trumpeting':1,'still':2,'fringing':1,'cannonade':1,'197':1,'reins':2,'past':16,'intricate':1,'rate':10,'invention':1,'double-slide':2,'creatures':1,'lung-fishes':1,'swampy':1,'darkness':2,'consumers':1,'clock':3,'deeply':1,'crust':2,'emotions':1,'thickness':3,'public':3,'multitude':1,'movement':2,'creature.':1,'toes':1,'malaria':2,'martians':1,'compilation':1,'loose':3,'component':1,'answers':3,'hours':1,'threads':2,'trunk':1,'directions':1,'strong':2,'transformation':2,'search':2,'teeth':5,'difficulty':1,'riviera':1,'experimenting':3,'unproved':1,'amount':3,'social':3,'action':4,'slope':2,'narrow':2,'elongated':2,'cataract':1,'tides.':1,'family':1,'spawning':3,'utilisation':2,'chalk':1,'globes':2,'vertebrae':2,'extinction':1,'herring':1,'life-histories':2,'taker':1,'eye--we':1,'two':30,'almost':4,'cultivation':1,'soil':3,'mysterious':4,'jurassic.':1,'ovules':2,'minor':1,'more':18,'scotia':1,'door':2,'substances':1,'text.':3,'emission':1,'chimpanzee':5,'instrumental':1,'stick':3,'particular':9,'foundations':1,'straight-haired':1,'weathering':3,'presumed':1,'fleece':1,'primate':2,'science':3,'centrifugal':1,'moisture-laden':1,'lung-fish':1,'lamp-shell':2,'male':18,'radiations':1,'history':14,'beautiful':6,'shark':1,'nautilus':1,'brown':8,'wave.':1,'brain-mind':1,'autumn':2,'sphere':1,'sense':10,'pond':3,'dress':1,'offspring':2,'salts':3,'axis':1,'terrestrial':4,'huge':3,'upbuilding':1,'starting-point':2,'breaking':1,'milk':1,'oligocene':2,'everyday':2,'glowing':2,'friction.':1,'sacred':1,'freezing-point':3,'daughter-cells':1,'creature':17,'simplicity':1,'plant':5,'salt.':1,'paloloworm':1,'trial-and-error':1,'triumphs':2,'plane':1,'pupae':1,'adventure':1,'polynesian':1,'waves':20,'invasion':4,'inconceivable':1,'a':1,'short':4,'dispersion--that':1,'coat':1,'spectra':1,'buns':1,'coal':1,'shore':34,'tentacles':2,'fundamental':8,'egg':4,'triassic.':1,'bustle':1,'pans':1,'infant':1,'earthworm':3,'help':1,'copper':1,'winged':1,'much-disputed':1,'mission':1,'cross':2,'attitude':1,'scientist':1,'lanugo':1,'existence':5,'kinetic':1,'visceral':1,'roots':2,'thirtieth':2,'arteries':1,'thrilling':1,'systema':1,'tickings':1,'lateral':1,'conjugation':1,'actually':2,'bell-animalcules':1,'absence':4,'parts':4,'microscopic':4,'founders':1,'mammal--instinctive':1,'partitions':1,'sheaves':1,'lowell':1,'evening':1,'reappearance':1,'motley':1,'males':2,'primary':5,'framework':2,'walls':5,'iridescent':1,'foot':2,'linking':1,'adventurous':1,'association':2,'cambrian':8,'mystery':2,'slipper':3,'mathematician':3,'ashes':1,'positions':1,'neanderthalers--the':1,'cavendish':1,'physiologically':1,'heavy':3,'reactions':1,'mental':4,'weight':1,'wall-like':1,'colder':1,'hare':3,'notochord':3,'ripple':1,'balance':3,'event':1,'croaking':2,'really':1,'mottled':1,'neanderthal':12,'pigeon':3,'abysses':3,'nautiloids':1,'fountain':1,'dying':1,'issue':1,'prominences':1,'meteoric':1,'foreground':1,'belief':1,'protruding':1,'story':19,'extraordinary':4,'reason':8,'base':6,'brightest':1,'members':7,'heads':2,'earliest':7,'beginning':39,'revolutionary':1,'producers':2,'albatross':1,'american':1,'fruit':1,'circuit':2,'expedient':1,'mangrove-trees':2,'solidly':1,'knots':2,'flood':1,'reversing':1,'moorhen':2,'probability':5,'radical':1,'bullies':1,'song-thrush':2,'antiquity':2,'well-known':3,'dust':2,'scots':1,'warty':3,'soapy':1,'earthworms':2,'idea':10,'horse':10,'tadpoles':2,'temperature':16,'introduction':2,'leading':1,'light-gatherer':1,'least':5,'assumption':1,'statement':2,'scheme':1,'danger-call':1,'muscles':3,'storm':2,'glow':1,'tides--another':1,'immediate':3,'basal':1,'treasures':1,'parr':1,'rifle':1,'prodigious':1,'selenium-cell':1,'modes':1,'kind':5,'observatory':1,'tunic':1,'kindly':1,'parent--little':1,'double':2,'vocal':1,'recording':1,'contrary':1,'risks':5,'egg-cells':1,'head.':1,'playing':3,'anthropoid':10,'stickleback':3,'outstanding':1,'heaviest':3,'ages':8,'well-developed':1,'colour-resemblance':1,'elaboration':1,'egg.':3,'hare--with':1,'organs':1,'gathering':1,'mountain':5,'dancing':3,'speculative':1,'cave':1,'peculiarities':1,'majority':3,'internal':4,'lip':1,'useless':1,'day.':1,'play':3,'electric':13,'capillaries':1,'eggs':21,'measures':1,'salmon':17,'depths':5,'most':67,'alpha':2,'extremely':2,'approved':1,'head-end':1,'equatorial':2,'whalebone':1,'prolongation':2,'clear':1,'instrument':6,'transmissibility':1,'seething':1,'electrons':15,'artistic':1,'velocity':5,'notch':1,'organism':6,'stones':5,'far-flung':1,'open-minded.':1,'gold':1,'fins':1,'wayside':1,'relation':2,'heavens':18,'fine':7,'find':1,'impact':2,'giant':1,'copyright':6,'spineless':1,'nervous':1,'earth-moon':1,'experiment':3,'quadrupedal':1,'circle':1,'indifference':1,'cromagnards':1,'hip':1,'dominant':1,'gains':3,'permission':2,'adventurers':1,'sunny':1,'shore-pools':3,'germ-cells':6,'earth--as':1,'actions':1,'compass':1,'journey.':1,'eye-piece':3,'chick':1,'sleeve':1,'body.':1,'alteration':1,'underlying':1,'common':9,'liver-fluke':1,'river':6,'californian':1,'rhodesian':4,'bars':1,'estuaries':1,'intelligence':3,'touch':2,'individual':15,'migration':1,'long-fingered':1,'walking-stick':1,'close':1,'precursors':1,'arm':3,'spirited':1,'probable':1,'distinctive':1,'taming':1,'smallest':8,'various':13,'conditions':7,'aeons':1,'supposed':1,'beetling':3,'iron':5,'unconscious':2,'web':1,'sole':2,'jaws.':1,'craters':1,'spectroscopic':1,'eustachian':2,'incident':1,'invisible':7,'inertia':1,'colonisation':1,'prospects':1,'last':16,'reverse':1,'distinctively':1,'annual':1,'harpy':1,'sensitive':1,'connection':2,'amoeba':1,'picture.':1,'earth--an':1,'cloud-like':1,'whole':42,'experimental':1,'sloth':1,'point':6,'simple':7,'others':1,'proton':1,'newborn':2,'unicellular':1,'puzzle-boxes':1,'incandescent':1,'unsuccessful':1,'lamprey--a':1,'startling':1,'moon--the':1,'java':8,'miocene':3,'originators':2,'crocodiles':1,'damp':1,'vertebrate':1,'intricacies':1,'secret':6,'maintenance':1,'widening':1,'yolk-laden':1,'empty':4,'modern':25,'flight':1,'squirrel':2,'fire':2,'gas':2,'amphibians':4,'gap':1,'races':1,'formless':1,'indivisible':1,'plants':5,'top--the':1,'solid':5,'straight':1,'bill':1,'routes':1,'pace':1,'error':1,'robin':1,'underground':2,'fore-limb':3,'century':1,'moth':2,'obstacle':2,'cerebrum':1,'simian':3,'atom--the':1,'currents':1,'twofold':1,'forewing':1,'undersides':1,'beune':2,'shorter':1,'stimulated':1,'shad':1,'ray':3,'yucca':6,'composition':2,'higher':14,'unwary':1,'used':1,'optic':1,'u.s.':1,'moving':6,'user':1,'dark':9,'lower':16,'older':1,'spectrum.':1,'people.':1,'consistence':1,'obviously':1,'person':4,'edge':5,'meridian.':1,'scouring':1,'distances':4,'endeavour':1,'migratory':1,'matter.':1,'isolated':1,'shape':7,'atomic':2,'questions':1,'useful':2,'praying':2,'continent':2,'spinners':1,'profitable':3,'superficial':1,'conclusions':1,'scales':3,'humanoid':3,'source':8,'parents':3,'remaining':3,'silken':2,'overhanging':1,'forces':6,'big':11,'sensatory':1,'game':1,'necessary':1,'bit':1,'earth--making':2,'wings':11,'vapour':1,'ponds':1,'photosphere--the':1,'tail.':2,'neanderthaler':1,'shapes':1,'bootlace':1,'well-poised':1,'individuals':1,'popular':3,'disorder':1,'essential':9,'gibbon.':1,'methods':3,'course':24,'spring':3,'last.':1,'back':15,'yolk':1,'diamond.':1,'martian':1,'mighty':1,'sight':1,'steam-engine':1,'curious':1,'gradually':1,'scale':6,'microbes':1,'flux':1,'fifty-millionth':1,'bushy-tailed':1,'pounding':1,'comet':5,'egg-shell':2,'scaly':1,'life-history':3,'object':3,'universe.':3,'protrusible':1,'nasal':1,'agreement':1,'forming':1,'stem':1,'step':1,'more-pork':1,'race--there':1,'nerves':1,'tidal':1,'intense':1,'analysing':1,'web-wing':1,'tortuous':1,'ear-bones':1,'range':2,'gamma':1,'conquest':5,'appropriate':2,'chalk-forming':2,'deep-violet':1,'question':12,'gases':1,'frog':4,'mimicry':2,'mountains':4,'glamour':1,'moon--meteors':1,'atlantic':5,'legs.':1,'atom':27,'adults':1,'coldest':1,'crane':2,'dull':1,'drifters':1,'skull':5,'characteristic':2,'spectroscope':32,'sifting':4,'stalking':1,'planet':17,'exploration':1,'mature':1,'diameter.':1,'sea-urchin':1,'x-ray':1,'non-living':1,'aerial':1,'protrusive':1,'flow':5,'paving-stones':1,'influence':2,'entrance':3,'metals':1,'char':1,'problem.':1,'single':1,'diving':1,'kidney':1,'cotton':1,'rainbow':4,'intrepid':1,'puzzling':1,'prerogative':1,'uranium':2,'occasional':1,'reputation':1,'electrical':1,'amphibian':2,'milk-glands':1,'elements':4,'small-brained':1,'energetic':1,'beginnings':3,'crouching':1,'backbone':8,'problems':1,'lens':2,'meaning':9,'restoration':7,'fruit-fly':1,'fishes':8,'stoppages':1,'sides':4,'structure':8,'land':7,'age':8,'orbit':2,'unhatched':2,'big-brained':2,'once':3,'hampton':2,'saying':1,'results':9,'mantle':2,'aristocrat':1,'conservative':1,'disintegration':2,'magnifying':1,'depletion':1,'young':42,'arid':2,'cradle':5,'blaze':1,'masculine':2,'coco-palms':1,'details':2,'gravel':1,'little-brain':5,'stupefying':1,'breathing':2,'club-moss':1,'wave':1,'electron':19,'entire':7,'archaeopteryx':2,'stiff':1,'fur':1,'button':1,'anxious':1,'race':10,'verdict':1,'sedentary':3,'poles.':1,'blood-fluid':1,'elk':1,'smaller':5,'booty':1,'lightest':3,'procession':3,'euphrates':1,'rivers':9,'noise':1,'munitions':1,'sifting-out':1,'makers':1,'scientific':9,'south':10,'zest':1,'opaque':1,'waning':1,'paddle':1,'hereditary':1,'ape-man':1,'indian':3,'poles':4,'flowing':1,'bird':18,'body':50,'hypothesis':3,'degree':3,'leg':4,'kangaroo':1,'outlying':1,'youngest':2,'growing':1,'river.':1,'boot.':1,'separation':2,'frilled':1,'consideration':1,'physiology':1,'little-brained':1,'extreme':1,'stellar':4,'great':80,'northern':1,'wandering':1,'larger':5,'haunts':3,'resulting':1,'mussel':1,'guidance':1,'apple':1,'danger':1,'round-mouths':1,'wit':3,'motor':5,'oval':2,'precursor':1,'singing':1,'ape':2,'nest':13,'use':9,'fee':2,'adaptation':2,'stream':8,'remains':9,'cretaceous':3,'next':14,'few':1,'contractile':1,'crab':9,'vehicle':2,'eagles':1,'doubling':1,'simpler':2,'mammoth':2,'sort':1,'grandest':3,'clever':1,'inclined':4,'rarest':1,'bodily':2,'rabbit':1,'baby':1,'gambian':2,'harvest':2,'sea-floor':2,'animals':11,'embryos':5,'lapse':1,'recession':1,'obvious':1,'thin':1,'closing':3,'interlinked':1,'proof':1,'control':3,'weaker':1,'corpuscular':1,'process':10,'purposes':1,'pieces':1,'high':5,'electro-magnet':1,'non-radiant':1,'water.':1,'bones':2,'wonderful':7,'voice':8,'class.':1,'united':13,'varied':2,'defective':1,'shasta':1,'nearness':2,'arrangement':4,'cycads':1,'need':2,'seeds':4,'forest':7,'animal':43,'hormones':1,'mysteries':1,'intelligent':2,'stock':1,'cave-men':1,'maternal':1,'yolk-sac':1,'gill-clefts':1,'waters':7,'thunderstorm':2,'collection':2,'tack':1,'wrist':2,'trees':7,'multiplication':4,'venation':1,'famous':2,'snail':3,'light':39,'lines':6,'interrupted':1,'element':3,'chief':9,'okapi':2,'alloy':1,'locomotor':2,'mud-minnows':1,'immensity':1,'longest':7,'spider':8,'evolutionary':4,'thigh':1,'unpalatable':1,'minnow':1,'egg-laying':1,'nerve-cord':1,'earth':193,'triassic':6,'polished':1,'brittle':1,'bunch':1,'industries':1,'1':2,'outer':7,'exclusion':1,'positively-electrified':1,'coral-reefs':2,'hermit-crab':7,'meantime':1,'beginning--whatever':1,'permanent':1,'duckweed':1,'molten':1,'world.':2,'image':1,'originator':2,'epoch-making':1,'junction':1,'future.':1,'orthodox':1,'dam':1,'material':9,'innermost':1,'cock-paidle':1,'phagocytes':1,'snake':1,'hands':2,'front':6,'rotation':5,'cage':1,'day':15,'articles':1,'crumb-of-bread':1,'mastery':2,'establishment':9,'university':2,'sky.':1,'concave':1,'blazing':1,'vibrations':1,'trap':1,'truth':1,'pools':3,'cocoon':1,'paler':1,'traces':1,'erratic':1,'female':12,'tension':1,'scanty':3,'globe':6,'cultivated':1,'mollusc':1,'frequency':1,'sands':2,'irregularities':1,'special':1,'ebooks':1,'suctorial':2,'cerebral':1,'knickerbocker':1,'inch':1,'gossamer':1,'protoplasm':1,'cross-fertilisation':1,'oriental':1,'pendent':1,'adaptive':1,'cause':2,'red':9,'harvest-mouse':1,'thrush':6,'spot':2,'withering':1,'activity':3,'incalculable':1,'body-cavity':1,'usual':7,'qui':1,'primus':1,'sitting':1,'shortest':3,'young--a':1,'allies':1,'g':1,'route':1,'area':4,'times':2,'length':9,'keel':1,'modernising':1,'barriers':1,'empire.':1,'gamekeeper':1,'embryo':6,'finest':3,'baleen':1,'powerful':1,'scene':2,'bonnet':1,'improvements':1,'placental':1,'owner':4,'scent':1,'two.':1,'salient':1,'monkey':2,'system':4,'ripples':1,'nebular':8,'accretion':1,'caterpillars':2,'under-water':1,'nut':2,'inner':7,'shell':12,'x-rays':8,'explanation':4,'secretion':1,'natural':12,'waist':1,'plumage':1,'photograph':5,'glow-worm':1,'quietness':1,'isolation':1,'well-established':1,'discriminating':1,'heavens.':1,'dynamo':3,'stricter':1,'steep':2,'spurs':1,'ingenious':1,'imaginative':2,'sea':46,'lightly':1,'wood-cock':1,'partnership':1,'poisons':1,'variable':2,'mongolian':1,'throat':1,'apparently':2,'bark':1,'seed-box':2,'complete':3,'pollen-tubes':1,'eye-hole':1,'outward':1,'pectoral':1,'ungirt':1,'tree-frogs':1,'centre':8,'digestive':1,'eight':2,'roadside':1,'flat-fish':1,'emancipation':2,'cleverest':2,'food-canals':1,'profoundest':1,'ancestors':5,'so-called':6,'inexorable':1,'consequences':2,'deccan':1,'ovum-producer':1,'face':3,'animal--perhaps':1,'mechanical':1,'occasion':3,'fact':31,'impression':4,'atmosphere':9,'selection':1,'best-defined':1,'chances':1,'text':4,'woolly':1,'pinhead':1,'sabre-toothed':1,'seaweed':3,'rough':1,'darkest':1,'photograph.':1,'principal':1,'water-vapour':2,'knowledge':1,'jaw':4,'mid-europe':1,'jar':1,'surroundings':3,'insectivores':1,'molecules':17,'inherited':1,'b':1,'local':1,'hope':2,'photographs':2,'handle':2,'exceptional':1,'familiar':2,'background':3,'words':2,'striped':1,'emmer':1,'areas':1,'processes':1,'belts':1,'numerous':4,'cells':1,'taxes':1,'insectivorous':1,'coco-nut':1,'stuff':3,'inter-relation':1,'limpet':1,'making.':1,'embryonic':1,'generations':1,'view':4,'spotted':1,'interstices':1,'universe--the':2,'packet':1,'distantly':1,'intensity':3,'legacy':1,'cenozoic':3,'violet':1,'cleverer':2,'luminous':2,'carboniferous':13,'humblest':2,'nebulae':1,'wire':5,'pedigree':1,'jurassic':5,'pattern':1,'nebula':5,'genius':1,'state':5,'quickest':1,'carapace':2,'hebrides':1,'routine':3,'progress':3,'open-sea':2,'kidneys':3,'attention':3,'explosive':1,'ability':1,'rotating':1,'importance':4,'hurrying':1,'seaweeds':2,'kea':2,'efficiency':1,'wingless':1,'hoatzin':2,'acquisitions':2,'key':3,'eyes.':1,'precious':2,'swift':1,'problem':14,'sediments':1,'limits':5,'cranial':1,'minds':2,'pulp':1,'figures':1,'sexes':2,'plankton':1,'chest':2,'conflagration':1,'wall':2,'wavy-to':1,'mid-rib':2,'animalcule':1,'table':1,'zinc':4,'provinces':1,'palm-bones':1,'tremendous':1,'discrimination':2,'trademark':3,'dazzling':1,'immense':4,'reindeer':2,'squatting':1,'slowly':1,'curtain':1,'feather':1,'waste':1,'senses':3,'controlled':1,'received':1,'coherence':1,'sub-aquatic':1,'bulk':1,'environment.':1,'angler':3,'food-canal':5,'present':15,'associated':1,'crowds':1,'appearance':5,'will':1,'country':1,'wild':8,'discoveries':2,'supply':2,'comets':1,'spectrum--should':1,'food-debris':1,'streams':2,'chaotic':1,'blood':20,'bumbling':1,'surface':50,'raison':1,'bugbear':1,'greater':1,'watchful':1,'jaws':1,'pit':1,'carbohydrates':1,'richness':1,'radiation':2,'forceps':2,'fashioning':1,'romance':5,'strange':1,'exuberance':1,'flower':2,'geographical':1,'ante-natal':2,'well-grown':1,'firmament':1,'neolithic':3,'ball':1,'dusk':2,'appearances':2,'effect':6,'experimenter':1,'colouring':1,'student':2,'fierce':2,'frequently':1,'whale':3,'wonder-world':1,'colour':12,'banded':1,'larvae':1,'ear-passage':2,'english':2,'position':1,'wreckage':1,'drawing':1,'latest':2,'reefs':1,'enormously':4,'flesh':2,'wren':1,'faunal':1,'domestic':1,'flywheel':2,'satellites':1,'ermine':2,'stored':1,'distant':3,'inturned':1,'cuckoo-spit':2,'protecting':1,'glue':1,'wrens--to':1,'grappling':1,'rapid':2,'ovum':3,'work.':1,'antarctic':2,'bell':5,'sky':7,'deposits':2,'transparent':3,'reasons':3,'wet':2,'usage':1,'ought':1,'characteristically':1,'meteor':1,'fate':2,'disappearance':1,'biologists':1,'smithsonian':10,'originative':1,'prominent':2,'loss':1,'backboned':1,'like':11,'success':1,'safest':1,'parasite':2,'colonising':1,'leaves':2,'works':2,'soft':4,'radiant':1,'heel':2,'wonders':3,'glare':2,'ages--evolution':1,'thymus':1,'phenomena':4,'mosquitoes':1,'eventfulness':1,'growth':3,'warmer':1,'past.':1,'proper':2,'trammels':1,'employment':1,'mother':12,'recognition':1,'possibilities':1,'leaf':6,'broad':4,'separate':1,'ether':27,'tadpole':3,'magnitude':2,'board.':1,'fruition':1,'biology':1,'scapula':1,'butterfish':1,'decline':1,'tenability':1,'paper':4,'pressure':3,'host':5,'instinct':2,'germination':1,'brain-box':1,'dredge':1,'transformations':1,'actual':8,'extension':2,'electron--the':1,'universe':37,'certainty':1,'preen':1,'andes':1,'carrier':1,'dominion':1,'rock-record':1,'flattened':1,'tongue':3,'contending':1,'letters':1,'fresh':2,'primal':1,'chemists':1,'wearisome':1,'promise':1,'erect':3,'times.':1,'registration':1,'protozoa':3,'swimmers':1,'mere':4,'endeavours':1,'parentage':1,'sticklebacks':2,'additional':2,'zoologist':1,'slow-worm':1,'museum':2,'larval':3,'spiral':3,'spots':4,'continental':1,'much':4,'invisibility':1,'cell.':1,'biggest':2,'maze':1,'breeding':4,'mouth.':3,'function':1,'funnel':1,'north':11,'gait':1,'repeated':1,'construction':1,'highest':8,'bug':1,'bud':1,'eel':2,'tactics':2,'cohesion':1,'places':2,'volplaning':1,'gravitational':3,'official':2,'smooth':1,'triumphant':1,'poker.':1,'record':1,'projecting':1,'lynx':2,'static':1,'distribution':1,'piece':4,'stirring':1,'supreme':1,'mesozoic':7,'universal':5,'penny':2,'whelk':2,'persistent':1,'water-vole':1,'ten-millionth':1,'elaborate':1,'tide.':1,'education':1,'domesticated':1,'atom--that':1,'mutual':2,'variety':4,'deadly':1,'fore-arm':3,'forests':2,'other':65,'boom':1,'branch':3,'mass':8,'wing':5,'chemist':1,'conclusion':6,'sunshine':2,'kinds':1,'tides':17,'variation':1,'enlargement':2,'astronomy':1,'exposure':1,'ranks':2,'space':1,'pigment-cells':1,'rule':4,'forest.':1,'eighties.':1,'inset':1,'half-second':1,'meteoritic':1,'sun--the':2},'marsupials':{'insectivorous':1,'on':1,'where':1},'musical':{'genius':2},'kinship':{'would':1},'deep-red':{'light':1,'waves':1},'unified':{'by':1},'macaque':{'second':1,'genus':1},'indigo':{'and':1,'to':1,'salicylic':1,'for':1,'in':1},'kale':{'and':1},'quoted':{'tells':1},'photo':{'press':1,':':164,'press.':1},'newton':{'because':1,'for':4,'except':1,'s':1,'taught':1,'worked':1,'was':1},'wasps':{'exhibit':1,';':1,'are':1,'.':1},'cap.':{'illustration':1},'thanks':{'to':2},'victim':{'to':1,'unawares.':1,'.':1},'upturned':{'side':1},'triticum':{'hermonis':1},'electronically':{'the':1,'in':1},'thyroid':{'and':1,'the':1,'.':1},'fearful':{'crime':1},'hills':{'and':2,'the':1},'evidences':{'perhaps':1,'of':5},'passive':{'the':1,'drifters':1,'in':1},'alchemy':{'but':1},'belongs':{'to':1,'was':1,'illustrates':1},'transformed':{'for':1,'descendants':1,'into':2,'directly':1,'guise':1,'by':1,'descendant':1},'board':{'a':1,'nail':1,'ship':1,'with':1,'in':1},'marginal':{'tentacles':1},'industrious':{'but':1},'openings':{'from':1},'photographed':{'from':1,'in':2},'boxed':{'in':1},'them--as':{'a':1},'required.':{'it':1},'caps':{'may':1,'on':1},'it--for':{'several':1},'fusion':{'of':3},'god.':{'nevertheless':1},'argonauta':{'an':2},'cape':{'colony':1},'rough-and-tumble':{'conditions':2},'retreat':{'but':1,'.':1},'hairless':{'whale':1},'utilisation':{'of':2,'was':1},'insurgent':{'nature':1},'cooler':{'vapours--the':1,'than':1,'they':1},'lapsed':{'intelligence':1},'sand-hoppers':{'and':1,'when':1},'evidence.':{'experiments':1},'homing':{'pigeons':1,'pigeon':2},'night':{'and':5,'means':1,'of':1,'is':2,'between':1,'when':2,'algol':1,'.':3,'to':2,'year':1,'the':1,'with':1,'or':1},'security':{'not':1,'that':1},'amoebae':{'and':2,'in':1},'cooled':{'down':2,'and':1,'so':1,'at':1},'dentition':{'but':2},'webb':{'celestial':1},'portuguese':{'man-of-war':2,'men-of-war':1},'bricks.':{'in':1},'lashes':{'or':1},'sends':{'to':1,'on':1},'3030':{'0':1},'1909':{'showing':1,'23':1},'fully-formed':{'creature.':1,'eel.':1,'young':1},'odours':{'a':1},'minnow--the':{'mind':1},'lashed':{'cells':1},'waves--which':{'are':1},'vertebrae':{'forming':1,'of':1,'as':1,'which':1,'.':2},'rill':{'of':1},'orchid':{'perched':1},'signifying':{'particular':1},'asking':{'the':1,'an':1},'lassoes':{'on':1},'month.':{'surprising':1},'colour-cells':{'chromatophores':1,'in':1},'beating':{'seconds':1,'heart':1,'of':1},'columbus':{'voyages':1,'.':1},'states.':{'1.e':1},'view':{'and':2,'that':6,'of':17,'is':3,'primary':1,'.':1,'will':1,'their':1,'maintained':1,'does':1,'which':1,'instinctive':1},'confer':{'upon':1},'illustration':{'24':1,'and':2,'144':2,':':233,'20':1,'that':1,'may':1,'158':1,'showing':2,'indicates':1,'74':1,'168':1,'of':10,'252':1,'280':1,'92':1,'172':1,'is':3,'shows':3},'constructive':{'chemical':1,'possibilities':1},'--these':{'also':1},'six.':{'beyond':1,'it':1},'peer':{'of':1},'taker':{'of':1},'post':{'shows':1},'properties':{'and':1,'of':1,'utterly':1,'attributed':1},'takes':{'stones':1,'on':1,'in':1,'up':1,'approximately':2,'air':1,'to':4,'place':1,'a':3,'time':2,'fresh':1,'the':1,'place.':1,'its':1,'at':1},'chaff':{'separated':1},'theirs':{'certainly':1},'coral':{'and':1,'islands':2,'built':2,'have':1},'months':{'and':1,'within':1,'old':2,'of':3,'after':1,'in':2,'from':1,'the':1,'before':1,'more':1},'constituting':{'that':1},'gentler':{'hills':1},'self-preserving':{'and':1},'horizon':{'the':1},'octopus':{'attacking':2},'serviss':{'curiosities':1},'considerations':{'there':1},'dilemma':{'of':1},'scantier':{'light':1},'pays':{'an':1},'crittur':{'on':1},'float':{'idly':1,'apart':1},'bound':{'to':3,'into':1,'up':1,'by':3},'gearing':{'it':1},'loin':{'and':1},'capped':{'with':1},'magnified.':{'is':1,'the':2,'illustration':1},'formidable':{'forelegs':1,'teeth.':1},'palaeozoic':{'the':1,'nine':1,'mesozoic':1,'era':4},'tint.':{'thus':1},'strangely':{'limited':1,'regular':1},'fight':{'but':1},'conservation':{'of':1},'way':{'and':6,'rooks':1,'specially':1,'remarkable':1,'acquired':1,'into':1,'we':5,'see':1,'through':2,'are':1,'in':10,'offshore.':1,'herring-gulls':1,'from':3,'for':2,'how':1,'there':1,'.':14,'note':1,'to':7,'which':4,'14':1,'out':1,'was':1,'over':1,'gave':1,'round.':1,'begins':1,'comparable':1,'arises':1,'aspects':2,'extend':1,'that':3,'ancestral.':1,'however':1,'but':1,'it':1,'never':1,'along':1,'with':4,'by':1,'he':1,'a':1,'like':1,'of':24,'as':2,'so':1,'back':1,'each':1,'the':7},'wax':{'from':1},'editions':{'will':2,'all':1,'means':1},'dorsal':{'vertebrae':2},'was':{'all':1,'just':2,'less':2,'caused':1,'able':1,'satisfied':1,'discovered':8,'astonished':2,'taken--the':1,'stored':1,'through':1,'still':2,'nearer':1,'certainly':1,'vigorously':1,'also':3,'thinking':1,'much':1,'regarded':1,'exercising':1,'actually':1,'to':3,'finally':1,'spread':1,'bridged':1,'hidden':1,'foster-parent':1,'sent':1,'brown':1,'watching':1,'prevented':2,'replaced':1,'possible':1,'possibly':1,'five':1,'altogether':1,'not':16,'during':2,'associated':2,'now':2,'continued':2,'killed':1,'forty-five':1,'wont':1,'rotating':2,'like':2,'shaped':2,'heaved':1,'joined':1,'twice':1,'found':6,'entirely':1,'spotted':1,'the':49,'set':2,'often':1,'hinted':1,'achieved':1,'absolutely':2,'hard':1,'some':1,'somehow':1,'dead':1,'observed':1,'born':1,'semi-tropical':1,'taught':1,'enhanced':1,'further':1,'extended':1,'perfected':1,'out':1,'established':1,'ultimately':1,'said':1,'imported':1,'placed':2,'unable':1,'probably':8,'neither':1,'ever':1,'filled':1,'freed':1,'condensed':1,'felt':2,'never':2,'quite':1,'by':3,'following':1,'protection':1,'practically':1,'sixty':1,'drawn':1,'joule':1,'promptly':1,'beginning':1,'implicit':1,'suggested':1,'on':1,'about':2,'grist':1,'created':1,'of':1,'barely':1,'later':1,'accomplished':1,'conveyed':1,'unknown':1,'asked':1,'first':1,'composed':1,'raised':1,'already':1,'followed':1,'merely':1,'marked':2,'one':5,'brought':2,'soaring':1,'because':1,'done':1,'cultivated':1,'elementary':1,'proved':2,'noticed':3,'repopulation':1,'doubtless':2,'once':5,'given':3,'invented':2,'from':1,'twenty':1,'due':2,'long':1,'quickly':1,'going':1,'punished':1,'too':4,'taken':2,'formed':1,'laboriously':1,'until':1,'opposed':1,'only':3,'that':4,'happily':1,'mind':2,'offered':1,'continuous':1,'but':2,'direct':1,'repeated':1,'part':2,'known':3,'trying':1,'true':1,'travelling':1,'he':2,'applied':2,'made':4,'this':1,'crossed':1,'originally':3,'immaterial':1,'premature':1,'sometimes':1,'cast':1,'near':1,'accustomed':1,'believed':1,'making':1,'called':2,'at':3,'150':1,'discovered.':1,'constant':1,'then':2,'almost':1,'thus':1,'it':2,'slowing':1,'an':5,'something':1,'in':9,'distinguishable':1,'any':3,'constructed':1,'effected':1,'dimly':1,'no':7,'perhaps':2,'when':1,'isolated':1,'evidently':1,'shorter':1,'.':2,'ordinary':1,'first--began':1,'fairly':1,'used':1,'tried':1,'emotionally':1,'living':1,'conceived':1,'upon':1,'most':2,'moving':1,'destined':2,'propagated':1,'aware':1,'subsequently':1,'a':40,'off':1,'happening':1,'largely':1,'broadened':1,'stronger':1,'or':1,'exceedingly':1,'implied':1,'so':4,'persistently':2,'very':4,'underrated':1,'swimming':1,'sounded':1,'refused':1,'repeopled':1},'war':{'would':1,'mr':1,'museum.':4,'note':1,'to':1,'in':1,'was':1,'254':1},'lowest':{'mammals':1,'pleistocene':1,'there':1,'.':1,'tide':1,'human':1,'arm':1,'first':1},'gaseous':{'state':1,'nebula':3,'nebulae':2,'ring':1,'.':1},'wheatfields':{'were':1},'afresh':{'and':1,'to':1},'fish-eater':{';':1},'becoming':{'longer.':1,'a':2,'longer':1,'suddenly':1,'of':1,'stereotyped':1,'.':2,'almost':1,'complicated':1,'either':1,'in':2,'linking':1,'adapted':1,'more':1},'converse':{'process--a':1},'peninsula':{'of':1,'it':1},'mysterious':{'phases':1,'rays':3,'force':1,'sailing':1,'universe':1,'as':1,'manifestations':2,'forces':1,'cold':1},'quiet-flowing':{'stretches':1},'needles':{'and':1,';':1},'same.':{'a':1},'astonished':{'to':2,'euclid':1},'true':{'flier':2,'is':1,'sense':2,'multicellular':1,'as':2,'in':4,'even':1,'to':1,'ventral':2,'nature':2,'when':1,'.':4,'also':1,'water-spider':1,'circle':1,'bird.':1,'we':1,'flight':1,'that':6,'men':1,'but':1,'fishes':1,'lids':1,'of':6,'mimicry.':1,'the':1,'or':1},'absent':{'of':1,'from':1},'edition.':{'most':1},'reproductive':{'and':1,'cells':1,'organs':3},'ancestral':{'forms':2,'home':1,'stocks':1},'maximum':{'abundance':1,'as':1,'sparseness':1,'in':1,'disclaimer':1},'arc-lamp':{'is':1},'generosity':{'which':1},'emotional':{'art':1,'halo':1},'emit':{'light':2,'but':1},'hotter':{'and':1,'than':1,'.':2,'at':1,'the':1,'until':1},'frederick':{'matter':1,'soddy':1},'muscular':{'appendages':1,'arrangements':1,'system':1},'evidence':{'for':2,'e.g':1,'of':12,'is':1,'there':1,'1':1,'to':1,'that':3,'are':1,'in':2,'suggesting':1,'the':1,';':1},'guessed':{'at':1},'juice.':{'illustration':1},'promised':{'land':2},'prayer':{';':1},'20':{'of':1,'000':1,'reproduced':1,'ounces':1},'life--story':{'of':1},'archive':{'foundation':12,'foundation.':1},'physical':{'and':2,'strength':1,'laboratory.':2,'constitution':1,'basis':1,'universe':1,'environment':1,'renaissance':1,'peculiarities':1,'medium':2,'fact':1,'type':1,'laboratory':1,'conditions':1,'change':1},'curiosities':{'of':1},'dimly':{'guessed':1,'unveiled':1,'aware':1},'dying':{'a':1,'--the':1,'suns':2,'of':1,'sec':1,'sun':1},'40-inch':{'refracting':2,'refractor':2},'reality':{'even':1,'of':3,'one':1,'by':1,'.':3},'pickering':{'thinks':1,'another':1},'holding':{'a':2,'firm':1,'them':2,'her':1,'on':1,'up':1,'fast':3,'their':1},'test':{'the':1,'variations':1,'what':1},'shrink':{'amazingly':1,'into':1,'by':1,'in':1},'robber-crab':{'birgus':2,'as':1,'with':1,'which':2,'for':1},'ordovician':{'the':1,'period':3},'brothers':{'may':1,'.':1},'welcome':{'realisation':1},'convincing':{'impression':1,'enough':1,'quality':1,'though':1},'anatomist':{'sir':1},'walton':{'the':1},'scores':{'of':3},'dissipation':{'of':1},'ours.':{'sec':1},'promise.':{'each':1},'kelts':{'after':1},'interval':{'of':1},'together':{'and':5,'as':5,'result':1,'in':4,'again':2,'by':3,'make':1,'.':3,'to':2,'you':1,'ever':1,'do':1,'again.':1,'but':1,'they':1,'with':2,';':1,'a':3,'of':1,'loosely':1,'so':3,'the':1},'brocklehurst.':{'a':2,'the':2},'beds':{'of':5,'which':1,'were':1},'reception':{'that':1},'sporozoa':{'like':1},'marinus':{'120':1,'which':1},'tigris':{'and':1},'concept':{'and':1,'of':1,'man':1},'impulse':{'to':2,'or':2},'phosphorescence':{'.':1},'aptitudes--power':{'of':1},'dance':{'but':1},'fulcrum':{'for':1},'brownian':{'movement':5},'contingencies--the':{'risk':1},'dalton':{'who':1,'.':1},'tenable':{'now.':1},'layers':{'that':2,'of':4,'into':1,'envelop':1,'.':1,'below':1},'certainly':{'they':1,'scanty':1,'serve':1,'due':1,'been':1,'one':2,'deserves':1,'is--but':1,'not':1,'white':1,'an':1,'was':1,'tells':1},'zone':{'on':1,'there':1,'was':1,'between':1},'shrinkage':{'of':2,'.':1},'hump':{'would':1},'flash':{'from':1,'across':1,'lasts':1},'absorbing':{'dry':1,'matter':1,'some':1},'fog':{'as':1},'permanently':{'like':1},'rhythm':{'which':1},'division':{'of':7,'or':2},'protective':{'resemblance':9,'significance--called':1,'capacity':1,'coloration':6},'sockets':{'along':1},'diminish':{'to':1},'particles.':{'the':1,'they':1},'liability':{'to':2,'costs':1,'breach':1},'aesop':{'prawn':3},'corals.':{'the':1},'mendelism':{'and':1},'trouble':{'than':1},'maternal':{'chromosomes.':1,'call':1,'virtue':1,'care.':1,'origin.':1,'affection':1,'care':1},'brows':{'and':1},'feeble':{'and':1,'current':1,'life':1},'rotating':{'on':1,'about':1,'quicker':1,'faster':2,'very':1,'flywheel':2,'disc':4,'earth':1,'immensely':1,'with':1,'round':3},'perceived':{'the':1,'.':2,'what':1,'either':1},'respiratory':{'system':1,'surface':1},'scandinavia':{'showing':2,'138':1,'141':1},'presented':{'alternately':1,'them':1,'simultaneously':1},'altering':{'the':1},'turns':{'on':2,'always':1,'upon':1,'to':1,'the':1,'round':1},'gun':{'that':1},'gum':{'is':1},'ox':{'and':1},'p':{'.':10},'means--resides':{'in':1},'revolutionised':{'physics':1},'gut':{'is':1,'which':1},'sloths':{'and':1},'woven':{'somehow':1},'upper':{'side.':1,'atmosphere':1,'eyelid':1,'fish':1,'pliocene':1,'reaches':3,'corner':1,'arm':1,'or':2,'pleistocene':2,'cretaceous':1,'regions':1,'parts':2,'lip':3,';':1,'hand':1,'diagram':1,'part':2,'surface':4,'cambrian':1,'photograph':1,'air':1,'side':1},'revolution':{'of':1,'diameter':1,'in':3},'full-grown':{'fish':1,'salmon':1,'shore-crab':1,'individual':1,'the':1,'creature':1},'penetrates':{'the':1},'spoonbill':{'s':2},'d':{'etre':1,'.':1},'niggardly':{'for':1},'affiliation':{'to':1,'with':1},'semi-tropical':{'for':1},'cost':{'and':2,'fee':1,'when':1,'but':1},'change-provoking':{'cross-fertilisation.':1},'helpless':{'that':1},'penetrated':{'further':1,'into':3},'cargo':{'that':1},'appear':{'and':1,'a':1,'it':1,'.':1,'to':9,'as':1,'much':1,'denser':1,'prominently':1,'white':1},'assistance':{'they':1},'burrowers':{'and':1,'like':1},'uniform':{'and':2,'set':1,'temperature':9,'teeth':1},'wave-motion':{'in':1},'eight-armed':{'cuttlefish':2},'illustrations':{'facing':1,'of':2,'all':1,'are':1,'among':1},'shared':{'the':1,'with':1,'equally':1,'by':1},'flame.':{'perhaps':1},'sea-cucumbers':{'lamp-shells':1},'institutions--all':{'must':1},'alertness':{'and':1,'of':1,'along':1,'is':1},'safety.':{'we':1},'supporting':{'and':1,'axis':3},'anvil.':{'as':1},'whiteness':{'may':1,'makes':1,'.':1},'disclaim':{'all':1},'suckers':{'which':1},'sieve':{'incalculable':1},'teacher':{'and':1,'always':1,'the':1,'between':1},'change':{'whose':1,'by':1,'abundant':1,'from':1,'of':9,'into':1,'in':6,'but':1,'.':2,'produced':1,'till':1,'every':1,'they':1,'reorganisation':1,'need':1,'the':1,':':1,'its':2,';':2,'is':1},'sending':{'a':1,'out':1},'illustration.':{'such':1},'flames':{'are':1,'rose':1,'from':1,'peeping':1,'of':1},'impatiently':{'postulated':1},'precursor':{'of':1},'twenty-seven':{'of':1},'vibrating':{'or':1},'trial':{'and':5,'of':1,'the':1,'was':1},'pictorial':{'diagram':1,'representation':3},'usually':{'about':1,'formed':1,'in':3,'longer':1,'produces':1,'very':1,'regarded':2,'work':1,'credited':1,'back':1,'rank':1,'less':1,'multiplies':1,'coming':1,'got':1,'given':1,'disappears':1,'creep':1,'mean':1},'locomotion':{'and':1,'becomes':1,'it':1,'192':1,'which':2,'the':1},'432':{'times':1},'inference':{'we':1,'when':1,'but':1,'.':1,'reason':1,'in':1,'not':1,'or':1},'saunders':{'with':1,'hit':1,'so':1},'stimulus.':{'2':1},'keenness':{'of':1},'sign':{'of':2},'marked':{'a':1,'on':1,'superficial':1,'off':2,'and':1,'d.p.':1,'h':1,'differences':1,'up':1,'vm':1,'by':8,'rotting':1,'fusion':1,'5':1,'in':3,'the':2,'changes':1,'than':1,'as':1},'outfly':{'a':1},'italians':{'punics':1},'seashore':{'and':2,'animals':1,'into':1,'.':1,'sponge':1,'to':1,'through':1,'struggle':1,'in':1,'birds':1},'comets--millions':{'of':1},'capacious':{'and':1,'mouth':1},'illumination':{'is':1,'or':1,'would':1},'rarely':{'seen':1,'over':1,'hinted':1,'dying':1},'pressure--2-1':{'2':1},'stingy':{'for':1},'cuttlefishes':{'which':1,'are':1,'have':1,'in':1,'the':1,'where':1,'by':1},'terminal':{'chamber':1},'breed.':{'there':1},'stereoscopic':{'vision':1},'primrose':{'among':1},'prove':{'to':1,'the':3,'his':1,'that':2},'time-table':{'the':1},'territories':{'of':1},'live':{'a':1,'on':4,'equally':1,'for':1,'independent':1,'far':1,'is':1,'there':2,'among':1,'much':1,'in':5,'the':1,'comfortably':1},'spontaneity':{'on':1},'wonderfully':{'supplemented':1,'rapid':1,'complete':1,'energetic':1},'bluffing':{'on':1},'1.e.8.':{'1.b':1},'angels':{'crowned':1},'entrance':{'and':1,'to':2},'water-ouzel':{'or':1},'cluck':{'when':1},'regrowing':{'them':2},'envelope':{'immediately':1,'or':1,'stops':1,'of':1},'planarian':{'worms':1},'clue':{'to':2},'grilse':{'and':1,'stage':1},'envelops':{'our':1,'the':1},'clumps':{'of':1},'duck-ponds':{'or':1},'migrants':{'from':1},'haddington':{'of':1},'nature--on':{'which':1},'theory--spiral':{'nebulae--the':1},'wolf-dog':{'226':1,'an':1},'cat':{'a':1,'could':1,'has':1,'or':2},'hardest':{'solid':1,'steel':1},'gathers':{'on':1,'more':1},'can':{'control':1,'now':2,'think':1,'divide':1,'be':63,'almost':1,'move':1,'notice':1,'sting':2,'replenish':1,'outfly':1,'say':5,'harness':1,'exist':1,'expect':1,'have':1,'re-utilise':1,'go':1,'dissolve':1,'to-day':1,'discern':1,'glimpse':1,'detect':2,'from':1,'calculate':1,'no':1,'always':1,'transfer':1,'make':4,'offer':1,'help':1,'only':5,'continually':1,'also':2,'live':1,'call':2,'therefore':1,'transmit':1,'survive':5,'hardly':4,'tell':3,'hope':1,'take':2,'breathe':1,'do':4,'we':1,'trace':1,'get':2,'afford':1,'never':1,'use':1,'discover':1,'observe':1,'unfurl':1,'recognise':1,'imagine':4,'distinguish':1,'affect':1,'copy':1,'fly':1,'reveal':1,'extend':1,'in':2,'apprehend.':1,'receive':1,'ever':1,'conceive':1,'work':1,'well':1,'see':4,'retain':1,'grind':1,'credit':1,'remain':1,'succeed':1,'form':1,'confidently':1,'easily':4,'become':1,'weigh':1,'the':1,'assign':1,'travel':1},'thirty-five':{'seconds':1,'minutes':1},'metamorphosis':{'the':1,'.':1},'stimulating':{'and':1,'conditions':1,'change':1},'http:':{'www.pgdp.net':2,'www.pglaf.org.':1,'www.gutenberg.org':2,'gutenberg.org':1,'pglaf.org':4},'heart':{'a':1,'for':1,'of':5,'there':1,'it':1,'.':1,'true':1,'or':1},'pauses':{'in':1},'expanding':{'during':1,'fan':1},'apartness':{'there':1,'from':1},'heard':{'not':1,'of':2,'the':1,'felt':1,'than':1},'chin':{'and':1,'process':1,'.':3},'clothing':{'and':1,'with':1},'occur':{'and':2,'only':1,'also':1,'near':1,'in':4,':':1},'candle;':{'the':1},'infantile':{'call':1,'mortality':3},'dispositions':{'of':1},'discussion':{'of':1,'there':1},'starch':{'and':1,'molecule':1,'.':1},'sandstone':{'was':1,'or':1},'condensation.':{'spiral':1},'offspring':{'and':1,'for':1,'of':1,'is':2,'.':2,'mate':1,'at':1},'nowhere':{'do':1},'despair':{'returned':1},'candle.':{'it':1},'actual':{'photographs':1,'distance':1,'solution...':1,'constitution':1,'temperature':2,'centre':1,'photograph':1,'entity':1,'direct':1,'observations':1,'historical':1,'mechanical':1,'precipitate':1,'dimensions':1},'future.':{'4':1},'familiar':{'case':1,'hum':1,'is':1,'in':2,'type':1,'with':3,'example':1,'fact':1},'over-population':{'and':1,'in':1},'brine-shrimp':{'artemia':1},'dominance':{'of':1},'economy':{'of':2},'gonads':{'only':1},'product':{'which':1},'burrowing':{'mammals':1,'reptiles':1,'parrot':1,'amphibians':1,'birds':1},'southern':{'europe':1,'india':1,'asia':1,'hemisphere':1,'representative':1,'sea':2},'unobtrusive':{'appearance':1},'disgusted':{'next':1},'significance.':{'it':1,'they':1},'produce':{'a':3,'what':1,'very':1,'light':1,'tides':1,'seeds':1,'in':1,'our':1,'the':2,'helium':1},'flourish':{'sometimes':1,'alongside':1},'mentality':{'and':1,'cannot':1,'.':1},'lifting':{'scrap':1,'handling':1},'upbuilding':{'constructive':1},'visitors':{'and':2,'.':1,'are':1,'have':1,'threw':1},'remember':{'how':1,'the':3,'that':3,'sally':1,'their':1},'whenever':{'the':2,'there':1,'any':1},'corona':{'of':2,'is':1,'stretching':1,'which':1,'that':1},'rather':{'a':1,'we':1,'ferocious.':1,'grouselike':1,'longer':1,'that':1,'humdrum':1,'more':2,'than':9,'to':1,'far-fetched':1,'excitedly':1,'in':4,'paltry':1,'eventful':1,'nondescript':1,'simpler':1,'with':1,'the':1,'trout-like':1,'like':1},'conquests':{'of':1},'punting':{'when':1,'sculling':1},'typical':{'plants':1,'spectra':1,'craters':1,'districts':1,'expression':1,'assemblage':1},'no.':{'bred':1},'serving':{'as':1,'the':1},'iii.':{'trial-and-error':1},'indeed':{'what':2,'climate':1,'made':1,'beyond':1,'that':1,'many':1,'no':1,'we':1,'unsurpassable':1,'will':1,'.':1,'safety':1,'they':1,'always':1,'our':1,'the':1,'believe':1,'if':1},'beak':{'and':1,'is':1,'.':1,'under':1},'well-illumined':{'seaweed-growing':1},'playful':{'such':1,'creature':1},'brain':{'and':9,'weighs':1,'is':7,'as':2,'are':1,'should':1,'from':2,'.':2,'does':3,'which':4,'instead':1,';':2,'has':1,'was':2,'shows':1,'development':2,'than':1,'receiving':1,'of':3,'could':1,'inferred':1,'cast':1},'stile':{'which':1},'hairs--an':{'alga':1},'nitrogen':{'of':1},'cold':{'and':1,'on':2,'poker':1,'outer':1,'for':2,'light':1,'.':1,'water':1,'to':1,'weather':1,'iron':2,'of':3,'dark':1,'absorbs':1,'luminosity':1,'yet':1,'came':1},'still':{'and':1,'atmosphere':1,'smaller':3,'being':2,'progressing.':1,'some':1,'it':1,'probing':1,'say':1,'exist':1,'farther':1,'in':3,'further':3,'nearer':1,'bears':2,'unknown':1,'.':3,'shorter':3,'to':1,'going':1,'goes':1,'persist':1,'molten':1,'was':1,'unstereotyped':1,'more':3,'we':1,'himself':1,'very':3,'continuing':1,'plays--the':1,'but':1,'particular':1,'not':1,'with':1,'the':2,'possess':1,'a':1,'made':1,'uncertain':1,'flourished':1,'room':1,'at':1,'tower':1,'feeling':1,'soft':1,'are':1},'birds':{'and':23,'feed':1,'because':1,'often':1,'show':1,'being':1,'is':3,'191':1,'it':1,'as':2,'are':4,'sight':1,'in':1,'carry':1,'seem':1,'its':1,'little':1,'squat':1,'for':1,'how':1,'make':2,'there':1,'.':2,'to':1,'find':1,';':1,'was':1,'evolved':2,'reaching':1,'may':1,'pick':1,'illustration':1,'like':7,'bolt':1,'such':1,'than':1,'must':1,'a':1,'that':4,'of':2,'turn':1,'have':2,'learn':1,'the':1,'where':1,'came':1},'statuettes':{'representing':1},'nucleus.':{'the':1,'illustration':1},'culmination':{'of':1},'tending':{'on':1,'toward':1,'to':3},'curly':{'greens':1},'rhizopods':{'such':1,'with':1},'willow':{'fertile':1,'grouse':2},'forms':{'and':6,'e.g.':1,'almost':1,'over':1,'it':2,'are':1,'arise':1,'kinetic':1,'again':1,'from':2,'.':2,'which':1,'tends':1,';':1,'we':1,'may':1,'daughter-buds':1,'a':7,'like':2,'of':22,'possessed':1,'so':1,'the':1,'or':1},'immortality':{'of':1},'suffocate':{'.':1},'spacious':{'bountiful':1,'cranial':1},'physics--research':{'and':1},'bird.':{'experiments':1,'illustration':2},'pruned':{'off':1},'speeding':{'toward':1},'inter-relations':{'such':1,'.':2,'where':1,'between':1,'simpler':1},'introduce':{'domesticated':1,'us':1,'an':1},'archaeozoic':{'and':1,'ages':1},'tails':{'of':1,'can':1,'.':1},'half':{'a':7,'old':1,'that':1,'of':3,'days':1,'an':3,'hours':2,'to':1,'tons':1,'miles':1,'mile':1,'the':4,'years':1,'out':1},'not':{'represent':1,'all':4,'clog':1,'help':1,'limited':2,'being':1,'indeed':2,'armour':1,'fall':1,'held':1,'through':1,'go':2,'follow':3,'yet':5,'also':1,'convinced':1,'less':5,'young':1,'mathematically':1,'to':11,'only':16,'stand':1,'touched':1,'easy':1,'attained':1,'include':1,'then':2,'unfitting':1,'closed':1,'knock':1,'very':9,'void':1,'material':2,'stop':1,'possible':2,'possibly':1,'open.':1,'know':13,'altogether':1,'accumulate':1,'affect':2,'one':2,'discuss':1,'easily':3,'practise':1,'necessary':1,'like':1,'tear':1,'fully':2,'try':1,'pursue':1,'feel':1,'stopped':1,'always':3,'small':1,'become':1,'entirely':1,'fixed':1,'mean':1,'exceed':1,'related':1,'certain':1,'know.':1,'likely':1,'sure':1,'exist.':2,'functioning':1,'packed':1,'even':3,'appear':2,'for':2,'uniform':1,'liberated':1,'radiated':1,'suggesting':1,'got':2,'be':20,'we':1,'disputed':1,'intelligent.':1,'cellulose':1,'however':1,'hundreds':1,'met':1,'necessarily':3,'attend':1,'backed':1,'quite':4,'come':1,'by':5,'momentous':1,'wait':1,'suggested':1,'on':2,'essentially':1,'indivisible':2,'many':1,'emit':1,'amount':1,'sweat':1,'permit':2,'undergo':1,'think':1,'burning':1,'gone':1,'previously':1,'requiring':1,'merely':2,'bound':1,'highly':1,'visible':1,'been':3,'carry':1,'impossible':1,'want.':1,'readily':3,'given':1,'wanted':1,'from':1,'droop':1,'prove':2,'assumed':1,'there':1,'self-luminous':1,'citing':1,'long':1,'throw':1,'cooling':1,'change':1,'strong':1,'suit':1,'show':2,'survive':1,'themselves':1,'molecular':1,'depreciate':1,'too':1,'a':16,'solicit':2,'received':1,'with':2,'ascribe':1,'but':1,'taken':1,'understand':1,'dwell':1,'catch':1,'copy':1,'true':1,'save':1,'unlike':1,'solid':1,'require':3,'imply':1,'will':1,'greatly':1,'how':1,'of':2,'more':6,'agree':3,'say':1,'and':1,'claim':1,'troublesome':1,'fit.':1,'give':1,'judge':1,'salmo':1,'arise':1,'share':1,'it':1,'an':3,'involve':1,'as':4,'exist':1,'at':2,'have':5,'in':5,'seen':1,'seem':4,'occupied':1,'any':2,'instinctively':1,'terrestrial':1,'conspicuous':1,'want':1,'perhaps':1,'sprawl.':1,'travel':1,'get':1,'able':1,'till':2,'interested':1,'take':2,'cling':1,'contain':1,'wanting':1,'shirk':1,'difficult':1,'used':1,'intended':1,'see':1,'dive':1,'after':1,'charge':2,'produce':2,'moving':1,'uncommon':1,'recognise':1,'revolve':1,'unlink':1,'nipped':1,'known':2,'pure-bred':1,'lead':3,'surprising':3,'clear':1,'lose':1,'flow':1,'asked':1,'without':1,'so':10,'allow':1,'far':1,'hear':1,'the':16,'make':3,'talk':1,'nearly':3},'ritchie':{'a':1,'s':1,'well':1},'courtship':{'or':1},'now':{'and':4,'studying.':1,'who':1,'exists':1,'be':2,'is':4,'successfully':1,'it':6,'an':2,'observed':1,'known':4,'as':1,'at':1,'a':1,'in':2,'our':1,'disappear':1,'if':1,'extinct--taking':1,'what':3,'based':1,'just':1,'to':3,'much':1,'there':3,'able':1,'send':1,'.':2,'extinct.':1,'that':1,'recognised':1,'pretty':1,'mars':1,'taken':1,'announce':1,'occurs':1,'crookes':1,'do':1,'we':4,'used':1,'complete':1,'slight':1,'evolving':1,'lights':1,'regard':1,'but':1,'permanent':1,'moving':1,'know':4,'accompanied':1,'represented':1,'one':1,'between':1,'unavailable':1,'concentrated':1,'high':1,'made':1,'this':5,'going':2,'other':1,'these':1,'suppose':1,'can':1,'believed':2,'let':2,'the':9,'assume':1,'called':1},'provision':{'of':1},'left--to':{'snap':1},'nor':{'do':1,'certainty':1,'like':1,'would':1,'hibernates':1,'very':1,'indeed':1,'is':1,'knew':1,'surface':1,'destroyed':1,'to':1,'explain':1,'does':1,'in':3,'of':2,'has':1,'any':1},'nos':{'.':2},'lineage':{'for':1},'it--a':{'natural':1,'mind':1},'sea-butterflies':{'on':1},'seaweed-growing':{'shelf':2,'area':1},'drop':{'of':2,'inwards':1,'out':1},'form.':{'it':1},'cagcombe':{'co.':2},'intrigued':{'at':1},'bursts':{'through':1},'luminosity':{'a':1,'indefinitely':1,'we':1,'due':1},'cusps':{'on':1},'entirely':{'different':3,'marine.':1,'dependent':1,'absent;':1,'random':1,'fluid':1,'unsolved.':1,'electrical':1,'in':1,'new':1,'dissipated':1,'with':1,'out':1},'cliffs':{'of':1,'there':1},'last':{'and':1,'twelve':1,'ten':1,'century':1,'is':1,'haunt':1,'indefinitely.':1,'questions':1,'one':1,'for':1,'twenty':1,'doubt':1,'it':1,'glacial':1,'has':1,'two.':1,'hit':1,'period':1,'arose':3,'dwindling':1,'with':1,'great':2,'chamber':1},'side-view':{'of':5},'domain':{'and':1,'to':1,'does':1,'in':3,'print':1,'works':1,'ebooks':1},'fired':{'it':1},'advantage.':{'perhaps':1},'green-flies':{'which':1},'sugars':{'and':1},'dagoes':{'he':1},'challenger':{'expedition':1},'fires':{'of':1},'year':{'and':4,'old':1,'grouse':1,'this':1,'energy':1,'there':1,'but':1,'one':2,'to':1,'out':2,'are':1,'they':1,'in':3,'followed':1,'the':1,'.':4,'encased':1,'before':1},'happen':{'as':1,'when':1,'if':1},'avoided':{'the':1},'monitors':{'are':1},'wheat--changes':{'in':1},'shown':{'a':1,'and':1,'faint':1,'that':7,'also':1,'there':1,'an':1,'to':1,'greatly':1,'at':2,'opposite':1,'in':11,'the':1,'.':1,'arno':1,'clearly':1,'remaining':1},'rude':{'stone':1},'space':{'and':5,'on':1,'that':1,'with':1,'straight':1,'in':2,'it':1,'can':1,'.':8,'yet':1,'are':1,'above':1,'between':1,'at':1,'during':1,'the':1,'shows':1,'where':1,'by':1,'is':3,'circular':1},'amnion':{'and':1,'which':1},'furthermore':{'there':1,'they':1},'inconceivably':{'small':3,'distant':1,'greater':1},'equatorially':{';':1},'hastily':{'referred':1},'increase':{'to':1,'rather':1,'of':6,'their':1,'in':3,'our':1},'kingdom.':{'on':1,'j':1},'rational':{'device':1,'conduct':3},'receiving':{'no':1,'stimuli':1,'tidings':1,'olfactory':1,'it':1,'contributions':1},'shows':{'a':3,'the':17,'great':1,'that':6,'any':1,'many':1,'some':1,'two':1,'an':1,'how':1,'definitely':1,'certain':1,'affinities':1,'clearly':1,'positively':1},'inevitably':{'lead':1},'e.':{'rutherford':1},'eighty-eight':{'of':1},'glass--the':{'stopper':1},'divergence':{'arboreal':1,'of':3},'animals.':{'the':1,'senses':1,'sec':1},'quart':{'.':2},'intruding':{'fishes':1,'bacteria':1,'parasites':1},'directions.':{'this':1,'so':1},'advantages':{'being':1,'of':1,'.':1},'taxed':{'no':1},'animals;':{'of':1,'it':1},'marine':{'animals':3,'family':1,'organisms':1,'lampreys':2,'fish':4,'but':1,'.':1,'leech':1},'inevitable':{'stoppage':1,'processes':1},'card':{'says':1,'tea':1,'is':1,'donations.':1,'in':1,'prof':1,'was':1},'care':{'and':3,'on':1,'associated':2,'in':1,'mammals':1,'is':1,'there':1,'it':1,'.':3,'as':2,'so':1,'which':1,'of':2,'exhibited':1},'vestige':{'and':1,'of':3,'in':1},'reflect':{'the':4,'that':2},'rearrangements':{';':1},'fixed':{'paths':1,'angle':1,'like':1,'for':1,'faith':1,'to':1,'distances':1,'limits':1,'vegetation--a':1,'in':3,'stage':1},'stage.':{'the':1},'selections':{'made':1},'transition':{'to':2,'.':1,'from':2,'which':1,'stage':1},'british':{'columbia.':2,'nightjar':1,'starfish':2,'guiana':2,'salterns':1,'museum':14,'coasts':1,'sailor':1,'average':1,'association':2},'invitation':{'to':1},'lighting':{'on':2},'domed':{'and':1,'web':1,'cranial':1,'than':1},'hesperornis':{'100':1,'after':1},'suffice':{'to':1,'of':1},'sprawling':{'blotch':1},'flying':{'and':2,'phalanger':1,'fish':2,'dragons':5,'past':1,'debris':1,'bats':1,'in':1,'birds':2,'frog':2,'reptiles':1,'under':1,'bird':1,'dragons--the':1,'squirrel':2,'crouching':1,'mammals':1,'jumps':1,'tree-toad':1,'fishes':2,'squirrels':1,'creatures.':2,'dragon':4,'matter':1,'lizard':1,'reptiles.':1,'lemurs':1,'phalangers':2,'round':1},'striking':{'and':1,'confirmation':1,'resemblance':2,'novelties':1,'of':1,'is':1,'illustration':1,'.':1,'instances':1,'as':1,'fact':1,'devices':1,'are':2,'feature.':1,'the':3,'difference':1,'coloration':1,'proof':1},'omitted':{'the':2},'comprised':{'only':1,'in':1},'brain.':{'the':1},'directly':{'and':1,'towards':1,'into':1,'important':1,'between':3,'pitted':1,'the':1,'or':3,'apart':1},'comprises':{'a':1,'the':1},'impossible':{'even':1,'on':1,'we':2,'because':1,'for':1,'but':1,'.':3,'to':7,'in':1},'ring':{'and':2,'a':1,'getting':1,'of':3,'into':1,'up':1,'.':1,'which':1},'drove':{'our':1},'size':{'and':6,'is':1,'it':1,'shape':1,'are':1,'in':1,'compared':1,'from':1,'possible.':1,'except':1,'.':4,'only':1,'has':1,'though':1,'after':1,'but':1,'101':1,'with':2,'covering':1,'of':22,'as':2,'mass':1,'the':1},'sheep':{'horses':1,'contrasted':1,'.':3,'in':1,'tearing':1,'or':1},'cerebration':{'at':1},'sheer':{'dexterity':2,'intelligence.':1,'quickness':1},'air-sacs':{'in':1},'checked':{'in':1},'silent':{'laboratories':1,'monotonous':1},'apple.':{'of':1},'caught':{'and':2,'a':1,'its':1,'on':1},'breed':{'.':1},'callous':{'rough-and-tumble':1},'longitudinally.':{'the':1},'wing-span':{'of':1},'flint':{'and':1,'implements':1,'implement.':1},'joseph':{'evolution':1},'melanocetus':{'indicus':1,'murrayi':1},'friend':{'the':1,'or':1},'nutrition':{'and':1},'x.':{'this':1},'rock-dove':{'just':1},'mostly':{'confined':1,'on':1,'caught':1,'white':1,'in':1},'that':{'all':14,'spiders':1,'go':2,'causes':1,'physiological':1,'suits':2,'to':2,'reptiles':1,'under':1,'degeneration':1,'case':1,'coloured':1,'every':10,'fall':1,'affect':1,'monkeys':1,'minute':1,'did':2,'herbert':1,'small':1,'round':1,'full-grown':1,'crop':1,'further':1,'creatures':1,'even':4,'pale-white':1,'apparatus':1,'assisted':1,'asia':2,'goes':2,'new':1,'body':1,'sinks':1,'climbs':3,'here':1,'atoms':1,'along':1,'change':1,'convert':1,'substance':2,'ichneumon':1,'wherever':1,'experience':1,'electricity':1,'locomotion':1,'makes':2,'followed':1,'trained':1,'bloweth':1,'from':1,'would':2,'prove':2,'remains':2,'live':3,'therefore':1,'mysterious':1,'substances':1,'marks':1,'particular':1,'90':1,'93':1,'must':1,'account':1,'animals':4,'this':20,'science':2,'piltdown':1,'can':5,'meet':1,'indicated':1,'frogs':2,'allowed':1,'high':1,'arise':1,'evidently':1,'viviparity':1,'end':1,'damage':1,'seeds':2,'movements':1,'intelligent':1,'swayed':1,'may':3,'after':3,'curiosity':1,'man':16,'a':32,'light':6,'sun-spots':1,'life':2,'green':1,'unsteady':1,'over':1,'produced':1,'experiments':1,'during':1,'carnivores':1,'existence':1,'rewarded':2,'birds':5,'before':1,'group':1,'forms':1,'vast':1,'covered':2,'might':3,'pays.':1,'evolution':6,'they':70,'not':1,'each':2,'went':3,'energy':4,'constitute':1,'our':8,'out':1,'living':3,'percepts':1,'flowed':1,'supports':1,'given':1,'put':1,'could':3,'length':1,'throws':1,'already':2,'number':1,'one':4,'long':1,'size':1,'little':1,'toy':1,'leading':1,'system':1,'hangs':1,'their':6,'gives':1,'eyes':1,'that':1,'took':1,'part':1,'flowers':1,'distance':4,'kind':1,'require':1,'tree':1,'matter':1,'were':2,'enables':1,'and':1,'ages':1,'have':11,'wallowed':1,'any':1,'-':1,'ideas':1,'cropped':1,'build':2,'which':7,'mammals':2,'play':1,'unless':1,'though':1,'object':1,'what':1,'falls':2,'most':2,'letter':1,'device':1,'extremely':1,'manifested':1,'gather':1,'steady':1,'electrons':2,'came':1,'gold':1,'insects':1,'means--resides':1,'only':2,'molecules':2,'8':1,'inhabit':1,'he':8,'local':1,'meant':1,'his':2,'sense':1,'skims':1,'means':1,'nearly':1,'instinctive':1,'dr':1,'runs':1,'she':2,'contain':1,'where':1,'aspect':1,'intelligence':1,'radium':2,'depends':2,'individual':2,'are':7,'tender':1,'definite':1,'its':2,'halves':1,'outside':1,'various':1,'between':3,'neither':1,'we':42,'nature':1,'originated':1,'multiplies':1,'come':2,'both':4,'many':6,'s':1,'figures':1,'expended':1,'comes':1,'otherwise':1,'among':2,'point':1,'whatever':1,'height':1,'regulated':1,'ether':1,'.':2,'interest':1,'mars':1,'empty':1,'direction':1,'flight':1,'amphibians':1,'engage':1,'lives':2,'sound':1,'these':12,'will':2,'while':8,'intercepts':1,'discoveries':1,'century':1,'light.':1,'is':51,'it':73,'experts':1,'in':27,'if':11,'different':1,'develop':1,'make':4,'grows':1,'neolithic':1,'used':1,'moment':1,'necessity':1,'supposing':1,'recent':1,'dark':1,'no':5,'sound-waves':1,'the':305,'bodies':1,'left':2,'just':2,'when':13,'distant':1,'questions':1,'speed':1,'death':1,'field':1,'had':6,'has':13,'gave':1,'increased':1,'early':2,'elapses':1,'like':1,'often':1,'ascend':1,'lingers':1,'happens':1,'provided':1,'leaf':1,'for':3,'does':2,'although':2,'instinct':2,'littoral':1,'by':2,'on':3,'about':1,'central':1,'of':52,'wave-length':1,'primitive':1,'within':1,'promise':1,'spores':1,'sticklebacks':1,'her':1,'there':47,'gases':1,'was':8,'opens':1,'form':1,'some':15,'amongst':1,'atom':1,'remote':1,'with':1,'partially':1,'made':1,'flit':1,'variations':1,'planet':1,'below':1,'attaches':1,'universal':1,'body-making':1,'deep':1,'an':6,'as':7,'exist':1,'at':7,'walks':1,'again':1,'variety':1,'uranium':1,'slumbers':1,'other':1,'you':4,'star':1,'visits':1,'develops':1,'fishes':2,'implies':1,'lead':1,'age':1,'depth':1,'time':1,'once':2},'brains':{'a':1,'and':2,'about':1,'from':1,'of':2,'is':1,'.':1,'occupying':1,'more':1},'kangaroo-like':{'fashion':1},'bees.':{'sheer':1},'eliminated':{'while':1,'in':1},'flowers':{'and':5,'yet':1,'in':1},'than':{'all':2,'uranium':1,'fifty':1,'light-waves':2,'birds':1,'before':1,'25':1,'to':5,'self-fertilisation':1,'ours':1,'seen.':1,'evolution--but':1,'very':1,'five':1,'occasional':1,'they':4,'half':1,'one':3,'55':1,'twice':1,'she':1,'science':1,'seventeen':1,'violet-light':1,'are':1,'our':1,'parachuting':1,'what':1,'its':1,'across':1,'we':3,'full':1,'300':1,'men':1,'efficiency':1,'others':2,'might':1,'100':2,'by':2,'anything':1,'of':1,'himself.':1,'34':1,'bricks':1,'two':4,'decrease':1,'learning':1,'one-millionth':1,'reflective--which':1,'from':1,'her':1,'twenty':1,'support':1,'there':1,'three':3,'cats':1,'500':1,'life':1,'that':7,'understand':1,'with':1,'those':4,'women':1,'sound':1,'non-existence':1,'thirty':1,'this':3,'plain':1,'replaced':1,'many':1,'my':1,'collecting':1,'seven':1,'guesses':1,'is':9,'radial':1,'it':3,'an':7,'as':1,'itself':1,'three-chambered.':1,'at':1,'fumbling':1,'in':15,'any':4,'tentative':1,'when':2,'regions':1,'arboreal':1,'another':1,'142':1,'eighty':2,'variation':1,'eight':1,'a':23,'elusive':1,'counterbalances':1,'-200':1,'the':52},'rugged':{'.':1},'artificer':{'fashioning':1},'accordance':{'with':3},'three-spined':{'and':1,'stickleback':2},'shunting':{'waggons':1},'dawn.':{'in':1},'apples':{'and':1},'fruits':{'and':1,'the':1,'191':1},'accessed':{'displayed':1},'photosynthesis':{'carbon':1,'that':1,'.':1,'i.e':1},'sublime':{'process':2,'device':1,'indifference':1,'movement':1},'dipnoan':{'which':1},'troublesome':{'as':1},'chlorophyll':{';':1,'that':1,'or':2,'which':1,'in':1},'angel':{'in':1},'remained':{'naked':1,'flat':1,'unchanged':1,'plastic--a':1,'at':1},'caterpillars.':{'of':1},'interpretation':{'of':6,'is':1},'lens-shaped':{'middle':1,'portion':1,'formation':1,'system':1},'anger':{'and':1},'wallowed':{'in':1},'recover':{'itself':1},'slab':{'of':1},'lumps':{'of':1},'erectus.':{'3':1},'overcoming':{'the':1},'shark':{'and':1,'his':1},'snout':{'the':1,'was':1,'region':1},'equipment':{'is':1,'including':1,'especially':1,'.':2},'mr.':{'waterhouse':1},'repeatedly':{'pruned':1,'changed':1,'shot':1,'against':1},'online':{'distributed':2,'at':3,'payments':1},'mediterraneans':{'semites':1},'hornbill':{'s':2},'begin':{'to':10,'with':6,'at':1,'afresh':1},'price':{'essence':1,'paid':1},'evaporate':{'altogether':1},'ultramicroscope':{'have':1},'men--conspicuous':{'amongst':1},'america':{'and':3,'a':1,'introductory':1,'africa':1,'.':2,'the':2,'by':1,'is':1},'greyish':{'jelly':1,'zone':1},'forever':{'unseen':1},'music.':{'illustration':1},'dream':{'that':1,'.':1},'freshwaters':{'and':1,'afforded':1,'form':1,'is':1,'.':2,'including':1,'4':1,'the':1},'steady':{'flow':1,'rhythmical':1,'renewal':1},'tooth':{'and':3,'is':1,'catches':1},'sunset':{'mean':1},'hurled':{'against':1,'out':1},'pattern':{'to':1,'is':1,'of':1,'.':1},'dust--that':{'it':1},'honour.':{'what':1},'discoverer':{'of':2},'fifty':{'thousandths':1,'eggs':1,'years':3,'feet':1,'miles':4,'fathoms':1},'discovered':{'and':3,'a':2,'about':1,'or':1,'star':1,'that':2,'it':1,'whatever':1,'an':1,'near':1,'until':1,'then':1,'in':12,'new':2,'the':4,'.':5,'by':2},'227':{'photo':1,'from':1},'226':{'photo':1},'fifth':{'printing':1},'crashing':{'along':1},'gnaw':{'the':1,'through':1},'ratio':{'of':1,'for':2,'to':1},'darwinism.':{'iii':1},'title':{':':1},'proportion':{'shown':1,'that':1,'of':1,'to':2,'as':1,'at':1},'jolt':{'that':1},'only':{'and':1,'exposed':1,'certain':1,'is':1,'coming':1,'competition':1,'one':13,'beginning':1,'as':3,'animals':1,'are':1,'planets':1,'in':4,'globes':1,'happen':1,'large':1,'differ':1,'from':2,'for':2,'shifts':1,'twenty':1,'make':1,'though':1,'when':2,'two':1,'been':1,'inferred':1,'to':6,'that':3,'without':1,'extravagant':1,'4':1,'way':1,'gradually':1,'mean':1,'profiting':1,'infer':1,'plants':1,'return':1,'206':1,'pours':1,'liberated':1,'apparent':1,'dimly':1,'but':1,'possible':2,'approaches':1,'a':28,'waves':1,'method.':1,'during':2,'shadow':1,'an':3,'with':1,'by':3,'minute':1,'fly':1,'on':1,'about':1,'luminescence':1,'backboned':1,'working':1,'thirty':1,'be':1,'of':4,'supporting':1,'required':2,'half':1,'different':1,'travels':1,'matter':1,'maintain':1,'were':1,'found':1,'the':5,'say':1,'or':1,'meaning':1,'once':4},'self-forgetful':{'and':1},'essence':{'of':1},'thompson':{'silvanus':1},'orthoptera':{'have':1},'220':{'the':1},'seen.':{'the':1,'illustration':1},'continuance':{'of':5},'shepherding':{';':1},'15.--mars':{'1':1},'warm-blooded':{'.':1,'creature':1},'cannot':{'and':1,'all':1,'give':2,'indeed':1,'in':1,'discover':1,'replace':1,'go':3,'see':1,'expect':1,'have':2,'enumerate':1,'fail':1,'follow':1,'even':1,'guess':1,'make':1,'continue':2,'survive':1,'tell':1,'swim':1,'be':26,'shut':1,'dispense':1,'however':1,'here':1,'possibly':1,'succeed':1,'put':1,'now':1,'come':1,'positively':2,'of':1,'conceive':1,'say':4,'evade':1,'think':2,'leave':2,'settle':1,'avoid':2,'travel':1},'genealogy':{'which':1},'appreciatively':{'in':1},'exactitude':{'and':1},'seldom':{'coincides':1,'spends':1,'if':1},'girdled':{'about':1},'baits':{'of':1},'prevents':{'bleeding':1},'sea--the':{'fresh':1,'shallow':1,'open':1,'deep':1},'girdles':{'of':1},'pituitary':{'and':1},'burst':{'into':2},'physically':{'far':1},'lancelets':{'and':1},'famine':{'or':1},'namely':{'portions':1,'that':1,'air':1,'in':1,'the':6,'sexual':1,'experimental':1},'actively':{'and':1,'hunts':1,'from':1},'sticklebacks.':{'after':1},'successive':{'ages--the':1,'series':1,'rings':1,'strata':2,'steps':1,'periods':1,'sets':1,'stages':1,'conquests':1,'incarnations':2},'sport':{'and':1,'for':1},'key--a':{'way':1},'concern':{'the':1,'for':1},'sprawl.':{'they':1},'justifies':{'itself':1},'colours':{'and':4,'then':1,'from':2,'which':2,'apart':1,'sometimes':1,'correspond':1,'.':11,'observed':1,'will':2,'are':1,'produced':1,'in':1,'alone':1,'283':1,'coloured':1,'with':1,'the':2,'red':1,'gives':1},'3':{'and':4,'below.':1,'1908':2,'educational':1,'rapid':1,'from':1,'hillock':1,'.':11,'3':1,'4':1,'we':1,'inches':1,'000':1,'letter':1,'variable':1,'now':1,'with':1,'by':1,'man':1,'evolution':1,'i':1,'of':2,'making':1,'the':11,'minutes':1,'drawing':1},'between':{'stones':1,'summer':1,'ten':1,'intelligence':1,'modern':1,'mind':1,'worms':1,'one':1,'tide':1,'our':1,'its':1,'tide-marks':1,'different':1,'flowers':2,'two':5,'physiology':1,'certain':1,'raising':1,'stars':1,'mars':1,'red':2,'a':3,'them':5,'that':1,'atoms':1,'it':1,'members':1,'shadow':1,'water-weeds':1,'fifteen':1,'day':1,'minute':1,'man':3,'plants':2,'loss':1,'one-seventh':1,'this':2,'hungry':1,'us':4,'these':3,'those':1,'common':2,'mother':2,'the':32,'male':1},'kneads':{'it':1},'justified':{'his':1,'by':1},'whipped':{'egg':1},'notice':{'what':1,'that':5,'this':1,'of':2,'is':2,'in':5,'how':1,'therefore':1,'another':1,'certain':1,'the':6,':':1,';':1,'indicating':1},'article':{'on':2,'is':1,'dealing':1},'profitless':{'stimuli':1},'stages':{'still':1,'e.g':1,'of':5,'when':1,'it':1,'through':1,'at':1,'which':1,'in':9,':':1,'until':1},'strides':{'associated':1},'cycad':{'flora':1},'systema':{'naturae':2},'altamira':{'cave':4},'enabling':{'the':1},'sparseness':{'in':1},'comet':{'and':1,'october':1,'for':1,'that':1,'september':1,'of':1,'is':1,'s':1,'.':1,'fig.':1,'approaches':1,'the':1,'dashes':1},'wheels':{'go':1},'already.':{'among':1},'comes':{'a':3,'and':1,'about':1,'from':1,'into':1,'within':2,'back':1,'.':1,'to':3,'through':1,'directly':1,'close':1,'the':1,'out':2},'mites':{'many':1},'passenger':{'pigeon':1},'jeans':{'says':1},'juvenile':{'stages':2},'learning':{'a':1,'by':7,'from':1,'intelligently.':1,'to':5,'thinking':1,'tricks':1,'there':1,'but':1,'.':1,'trial':1,'at':1,'the':1,'or':1},'moreover':{'even':1,'climate':1,'that':3,'meteorites':1,'there':2,'their':1,'as':2,'every':1,'they':1,'the':2,'if':1},'actually':{'standing':1,'do':2,'fly.':1,'longer':1,'dividing':1,'consort':1,'settled':1,'caught':1,'observed':2,'implied':1,'lives':1,'stuffed':1,'in':1,'observing':1},'sun-spots':{'appear':1,'that':1,'is':2,'rise':1,'it':1,'.':1,'are':1,'where':1},'oliver':{'lodge':2,'electrons':1},'cares':{'.':1},'mimicry--the':{'subject':1},'markedly':{'contrasted':1,'from':1,'in':1},'jerks':{'a':1,'itself':1,'its':1},'punished':{'by':1},'rotting':{'or':1,'.':1},'dangers':{'.':1,'e.g':1},'exhaustion':{'of':1},'gill-breathing':{'and':1},'angles--that':{'is':1},'observers':{'who':1,'that':1},'stephen':{'cribb.':2},'textbook':{'organic':1},'rubs':{'it':1},'stems':{'of':1,'gave':1},'suspected':{'that':1,'.':1},'water-animals':{'.':1},'realities':{'in':1,'.':1},'prehistoric':{'skulls':1,'brothers':1,'human':2,'metallurgists':1},'developing':{'organs':1,'eggs':1,'egg':1,'human':1},'these':{'flaming':1,'partial':1,'planetesimals':1,'magnetic':1,'forests':1,'four':1,'not':1,'motions':1,'facts':2,'tropisms':1,'its':1,'before':2,'layers':1,'middlemen':1,'giant':1,'daughter-buds':1,'infinitely':1,'quaint':2,'greeks':1,'masses':1,'show':1,'young':1,'forms':2,'to':1,'twig-insects':1,'spirals':1,'clusters':1,'include':1,'moorhens':1,'rodents':1,'exalted':2,'questions':2,'dark':1,'gloomy':1,'effects':2,'words':2,'radio-active':1,'instinctive':1,'fragments':2,'vast':1,'vapour':1,'shallow-water':1,'variable':1,'sources':1,'large':1,'small':1,'works':1,'embryonic':1,'mean':1,'methods':1,'are':16,'instances':1,'concern':1,'gill-slits':1,'three':4,'palaeolithic':1,'organisms':1,'self-effacing':1,'shallow':1,'particles':4,'various':2,'moons':1,'open-sea':1,'illustrate':1,'encounters':1,'red':2,'mercury':1,'we':1,'men':1,'agencies':1,'atoms':2,'wingless':1,'threads':1,'represented':1,'tidal':1,'craters':1,'great':1,'last':1,'flames':1,'brilliant':1,'could':1,'haunts':1,'strange':2,'extremes':1,'streams':1,'dents':1,'efforts':1,'wonders':1,'considerations':1,'reasons':1,'instruments':3,'marvels':1,'spiral':2,'invisible':1,'gases':1,'protozoa':1,'ether':1,'technically':1,'ring-formations':1,'little':2,'ancient':1,'from':1,'entities':1,'outbreaks':1,'there':4,'two':9,'spots':1,'.':1,'stuck':1,'observations':1,'fiery':1,'reflex':1,'manufacture':1,'enable':1,'vigorous':1,'stars':2,'form':1,'that':1,'formed':1,'minute':1,'cases':1,'sleeping':1,'with':2,'must':1,'portions':1,'was':1,'cells':1,'variations':1,'will':1,'regions':1,'replaced':1,'thin':1,'were':4,'coral':1,'and':1,'seven':2,'planets':1,'is':3,'it':1,'days':1,'pieces':1,'have':5,'in':2,'need':1,'x-rays':1,'pages.':1,'paths':1,'rays':2,'requirements':1,'inborn':2,'perhaps':1,'things':3,'cave':1,'struggles':1,'astronomers':1,'sciences':1,'amazing':1,'other':1,'details':1,'which':1,'papers':1,'units':1,'green':2,'several':2,'higher':1,'play':1,'elements':1,'vestigial':2,'may':1,'long':1,'eight':1,'delicate':1,'half-brutish':1,'waves':3,'fishes':2,'types':2,'so-called':1,'enregistrations':1,'spectra':1,'lines':3,'lasted':1,'substances':2,'chemical':3,'points':2,'electrons':7,'bodies':1,'allow':1,'tentatives':1,'the':2,'molluscs':1},'danger.':{'illustration':1},'handicapped':{'by':1},'biped':{'and':1,'202':1,'when':1},'care.':{'but':1,'illustration':1},'coolest':{'and':1,'places':1},'ein':{'or':1},'ocean-basins.':{'beginnings':1},'soil':{'of':1,'the':3,'by':1,'.':1},'startling':{'results.':1,'in':1,'effect':1,'rapidity':1,'.':1},'100th':{'of':1},'eras':{'marked':1,'.':2,'eighteen':1,'passed':1,'in':1,'with':1},'beaver':{'will':1,'not':1,'the':2,'shore-frequenting':1,'220':1},'property':{'infringement':1,'of':4,'trademark':1,'common':1,'which':1},'helium':{'and':1,'from':1,'could':1,'gas':1,'by':1},'thrills':{'the':1},'generously':{'.':1},'cromagnon':{'man':2},'develop':{'and':2,'into':2,'without':1,'inside':1,'in':2},'inquire':{'how':3,'into':1,'however':1,'what':2},'intelligently':{'appreciate':1,'.':1},'epoch':{'now':1,'in':1},'inquiry':{'into':1,'was':1,'is':2,'called':1},'streams':{'and':1,'of':4,'.':1,'bring':2,'in':1,'encounter':1,'out':1},'gorging':{'itself':1},'noble':{'giants.':1,'qualities':2,'in':1},'investigated':{'to':1,'.':1},'centuries':{'astronomers':1,'to':2,'unavailable':1},'arctic':{'plants':1,'fox':2,'foxes':1,'ocean':1,'forms':1,'terns':1},'foam':{'beneath':1,'it':1},'unconvincing':{'.':1},'fruit':{'to':1,'it':1,'but':1,'.':1},'attributes':{'as':1},'solicitation':{'requirements':1},'passing':{'on':1,'from':2,'two':1,'quickly':1,'down':1,'to':1,'through':5,'stars':1,'in':1,'an':1,'cloud':1,'before':1},'traps':{'and':1},'framework':{'of':1,'in':1},'charges':{'and':1,'of':3,'within':1,'carried':1,'.':1},'constitutional':{'sometimes':1,'changes':1,'rhythm':1},'breezy':{'morning':1},'severe':{'processes':1,'winter':2,'for':1,'interglacial':1,'in':1,'cold':2,'conditions':1},'luminous':{'body':1,'and':1,'interpretation':1,'body.':1,'envelope':1,'after':1,'spot':1,'.':1,'to':1,'cloud-like':1,';':1,'organs':1,'the':1,'fact':1},'laboratories':{'of':2},'charged':{'particles':1,'with':1,'nucleus':1},'heaps':{'them':1},'three-chambered':{'heart':2},'last.':{'the':1,'there':1},'aeration':{'is':1},'transmitting':{'waves':1},'cromagnards':{'probably':1,'in':1,'.':1},'dancers':{'in':1},'valuable':{'food-plant':1,'practically':1},'electrification':{'like':1},'accumulate':{'on':1,'any':1,'.':1},'rule.':{'getting':1},'ounces':{';':1,'at':1},'touch':{'of':3,'the':1,'is':1,'came':1,'.':1},'speed':{'a':1,'we':2,'that':1,'of':15,'is':1,'though':1,'given':1,'.':3,'to':1,'as':1,'increases':1,'which':1,'in':1,'has':1,'with':1,'or':2,'round':1},'death':{'and':2,'a':2,'of':3,'is':3,'there':2,'when':1,'but':1,'.':3,'as':1,'sec':1,'are':1,'208':1,'the':1,'should':1,'similar':1,'becoming':1},'legitimately':{'inquire':1},'thinking':{'about':1,'of':3,'is':1,'.':2,';':1,'feeling':2},'darkness--an':{'eternal':1},'starlings':{'in':1},'improvement':{'where':1,'e.g':1},'journey.':{'we':1},'treatment':{'and':1,'of':1},'versa':{'some':1},'dovecot':{'to':1},'struck':{'only':1,'in':1},'real':{'wealth':1,'nature':2,'food':1,'men':1,'seeds':1,'sense':1,'progress':1},'spectacular':{'display':2,'element':1},'larva':{'about':1,'e.g':1,'called':1,'transparent':1,'that':1},'rules':{'is':1,'set':1},'outermost':{'finger':3,'moons':1},'stung':{'by':1},'epoch-making':{'step':1,'experimental':1},'discontinue':{'all':1},'absorptive':{'wall':1},'early':{'embryo':1,'summer':1,'atmosphere':1,'instruments':1,'pliocene':2,'chapters':1,'years':1,'triassic':1,'in':1,'stage.':1,'instrument':1,'reptiles':1,'ripening':1,'stage':2,'vegetation':1,'life-history':2,'neolithic':1,'waters':1,'men':1,'community':1,'man':1,'stone':2,'forking':1,'days':2,'youth':1,'greek':1,'victorian':1,'offshoot':2,'or':1},'quickness':{'of':1,'correlated':1,'.':1},'broader.':{'other':1},'decipher.':{'another':1},'using':{'a':2,'up.':1,'them':1,'and':1,'these':1,'or':1,'their':2,'electricity':1,'the':3,'any':1},'lady':{'came':1},'ruled':{'by':1},'inevitableness':{'of':1},'learnedly':{'called':1},'heat-waves':{'and':1,'.':1},'nerve-endings':{'on':1},'pounds':{'and':3,'of':4,'.':1},'smell':{'and':1,'less':1,'of':1,'that':1,'.':1,'in':2,'detecting':1,'or':1},'velocities':{'and':1,'with':1,'from':1},'streamers':{'which':1},'system.':{'the':3,'several':1,'what':1,'illustration':1,'in':1},'benefit':{'is':1,'in':1},'t':{'our':1,'.':3,'of':1},'fully':{'formed':1,'into':1,'explained':1,'appreciate':1,'aware':1,'absorbed':1,'in':1,'.':1},'downward':{'current':1,'currents':1},'twelve':{'hours':1,'different':1},'exposed':{'on':1,'it':1,'rocks':1,'to':3,'at':1,'the':1},'coal--a':{'chemical':1},'cathode':{'gave':1},'chronology':{'do':1},'astronomer':{'simon':1,'takes':1,'calls':2,'means':1,'h':1,'seldom':1,'.':1,'offers':1,'said':1,'has':1,'despairing':1},'shore-pool':{'and':1},'1859':{'made':1,'.':1},'salicylic':{'acid':1},'unlocked':{'.':1},'1850':{'.':1},'recorded':{'.':1,'in':1},'1856':{'in':1},'conservative':{'and':1,'animals':1,'type':1,'anatomist':1},'clear-cut':{'perceptual':1,'ideas':1,'.':1},'iron-forming':{'bacteria':1},'wheat':{'and':3,'a':1,'in':2,'which':1,'on':1,'of':1,'is':2,'that':1,'it':1,'1919':1,'emerged':1,'were':1,'harvest':1,'with':1,'called':1,'before':1},'business':{'office':1,'that':1,'of':1,'.':1,'pglaf.org':1,'in':1},'sixth':{'printing':1,'day':1,'month':1},'equivalent':{'to':1},'uneasy':{'and':1,'restlessness':1},'sixty':{'millions.':1,'miles':2,'years':1},'exciting':{'chapter':1,'race':1},'throw':{'off':1,'light':1,'it':1,'much':1,'dust':1,'prickly':1},'comparison':{'of':1,'the':1,'.':1,'with':3,'should':1},'ear-trumpet':{'or':1,'man':1},'central':{'and':1,'body':2,'stomach':1,'sun':1,'region':1,'java.':1,'europe':1,'fire.':1,'portion':1,'part':1,'nucleus':2,'africa':1,'biological':1,'lens-shaped':2,'mass':1,'fact':1},'piety':{'of':1},'tentatives':{'have':1,'.':1},'wolf':{'a':1,'the':1,'.':2},'greatly':{'increased.':1,'and':1,'economised':1,'from':1,'increased':2,'for':1,'restricted':1,'enlarged':1,'according':1,'by':1,'misjudge':1,'increases':1,'magnified.':2,'in':1,'affect':1,'reduced':1,'elongated':1,'encouraged':1},'bright-green':{'hue':1},'predatory':{'creatures':1,'animal':1,'cuttlefishes':1},'freeing':{'of':1},'outlook':{'on':1},'whole.':{'geologists':1},'kapp':{'gisbert':1},'goethe':{'s':1},'skunks':{'magpies':1},'rolling':{'stone':1},'heated':{'.':1},'elementary':{'exposition':1,'can':1,'fact':1},'shrinking':{'the':1,'mass':1},'your':{'poker':1,'possession.':1,'written':1,'country':1,'equipment.':1,'use':1,'applicable':1,'pocket':1,'state':1,'periodic':1,'nerves':1,'cold':1,'hand':1,'efforts':1},'stare':{'at':1},'risen.':{'one':1},'fast':{'and':1,'line--are':1,'that':2,'bound':1,'.':1,'to':1},'log':{'ready':1},'prepare':{'or':1,'your':1},'area':{'and':2,'of':5,'varies':1,'.':1,'as':1,'are':1,'which':2,'by':1},'stoppage':{'of':1},'start':{'a':2,'of':1,'at':1,'the':1,':':1,'with':1},'cats':{'and':2},'low':{'and':2,'flat':1,'temperatures':1,'temperature':1,'form':1,'level':3,'nest-building':1,'grounds':1,'when':1,'forests':1,'gap':1,'chemical':1,'to':1,'quiet-looking':1,'retreating':1,'psychical':1,'the':1,'on':1,'type':1,'order':1,'degree':1},'lot':{'of':2},'colder':{'water':1,'.':1},'jones':{'has':1},'philosophers':{'but':1},'posterior':{'claspers':1},'manipulative':{'intelligence':1,'skill':1,'expertness':1},'1871--a':{'book':1},'body-cells':{';':1},'two-thirds':{'of':2},'water-vapour':{'gathers':1,'which':1,'in':1},'hottest':{'.':1},'playsomest':{'crittur':1},'sea-level':{'.':1},'circulation':{'of':2},'species.':{'sec':1,'it':1},'star.':{'this':1},'phosphorescent':{'things':1,'animals;':1,'at':1},'waltzing':{'mouse':1},'embedded':{'in':2},'waste-product':{'called':1},'beliefs':{'concerning':1},'euplectella':{'a':2},'vedda':{'of':1},'600':{'a':2,'miles':1,'000':1},'describe':{'this':1,'even':1,'the':1,'it':1,'as':1},'moved':{'slightly':1,'still':1,'slowly':1,'forwards':1,'weigh':1},'sheath':{'which':1},'moves':{'and':1,'only':1},'extinct--taking':{'us':1},'innings':{'.':1},'plants--the':{'first':2},'alligator-like':{'forms':1},'thither':{'rather':1,'somewhat':1},'you':{'already':1,'give':1,'within':1,'distribute':1,'share':1,'begin':2,'press':1,'are':4,'have':6,'in':1,'carefully':1,'follow':1,'will':1,'derive':1,'from':1,'for':2,'provide':3,'pay':1,'indicate':1,'charge':1,'take':1,'do':4,'notice':1,'cause.':1,'may':9,'beat':1,'as-is':1,'pick':1,'paid':3,'discover':1,'produce':1,'put':2,'hold':1,'with':1,'comply':2,'must':6,'a':1,'received':3,'prepare':1,'receive':1,'wish':1,'like':1,'cannot':1,'can':9,'learn':1,'agree':4},'forcing':{'us':1},'poor':{'.':1,'endowment':1,'in':2},'polar':{'bear':5,'ocean':1,'cap.':1,'snow-caps':1,'caps':2,'areas':1},'466':{'sirius':1},'bacillus':{'of':1},'drift':{'across':1,'but':1,'which':1},'carpenter':{'who':1},'flattened':{'shape':1,'tips':1,'sacs':1},'suited':{'to':3,'for':9,'certain':1},'queensland':{'one':1,'mudfish':1},'pool':{'on':1,'almost':1,'of':1,'is':1,'.':1,'swamp':1,'in':1},'ramsay':{'discovered':1,'and':1},'building':{'of':2,'material':1,'up':7},'bulk':{'of':4,'under':1},'condensation':{'of':1,'would':1,'they':1,'.':1},'sperm-cells':{'distinct':2,'.':1},'controlled':{'and':2,'activities':1,'life':1,'then':1,'movements':1,'more':1},'profits':{'you':1,'by':1},'doubted':{'even':1},'signalling':{'to':1},'strings':{'round':1},'since':{'lessons':1,'then':1,'we':2,'sheep-ranches':1,'many':2,'noon':1,'there':1,'it':4,'rain':1,'matter':1,'disappeared.':1,'all':1,'man':1,'the':8,'darwin':1,'extinct':2,'if':1},'contemporaneously':{'with':2},'skeleton':{'and':1,'remains':1,'musculature':1,'of':4,'tend':1,'in':1,'or':2},'pointing':{'out':1},'breadth':{'of':1},'splitting':{'the':1,'into':1,'up':2},'month':{'and':2,'because':1,'old':1,'increased':1,'of':2,'began':1,'but':1,'.':1,'became':1},'ceased':{'to':5,'it':1},'thoughtful':{'men.':1},'re-utilise':{'.':1},'revealed':{'down':1,'to':1,'themselves':1,'itself':1},'asterias':{'forreri':2},'carpet':{'of':2},'keith':{'and':1,'pithecanthropus':1,'pictures':1,'arthur':1,';':1,'m.d':2,'says:':1},'referring':{'it':1},'cliff':{'.':1},'unenforceability':{'of':1},'wyoming':{'u.s.a.':1},'talkativeness':{'.':1},'deep-rooted':{'corresponding':1},'boiling-point':{'of':1,'while':1},'solicit':{'donations':1,'contributions':1},'sustain':{'it':1},'thomson.':{'i':1},'divisions':{'of':1},'very':{'precise':1,'permeable':1,'hooky':1,'remarkable':5,'distant':1,'carefully':1,'tough':1,'uniform':1,'fine':4,'profitable':1,'rapid':2,'rapidly':1,'educable':2,'interesting':11,'young':2,'peculiar':1,'passive':1,'deep-rooted':1,'masculine':1,'inconspicuous':4,'good':2,'dust':1,'far':4,'discrepant':1,'early':1,'nearly':1,'closely':1,'vividly':1,'highly':1,'feeble':1,'minute':2,'brightly':1,'dim':1,'like':4,'profound':1,'numerous':3,'imperious':1,'large':4,'common':3,'liable':1,'quick':1,'antique':1,'dilute':1,'old':1,'often':3,'innocent':1,'unprofitable':1,'changeful':1,'likely':1,'convincingly':1,'miserable':1,'heavy':1,'gradually':1,'dense':1,'prolific':2,'poisonous':2,'definite':1,'near':1,'conservative':1,'simplest':1,'crude':1,'sluggish':1,'palatable':1,'intimate':1,'notable':1,'weak':1,'voracious':1,'small':9,'completely':1,'slow':2,'active':3,'eventful':1,'strong':3,'beginning':2,'momentous':1,'great':3,'instant':1,'reverse':1,'many':1,'distinctively':1,'inexpensive':1,'practical':1,'sensitive':4,'greatly':2,'slightly':1,'hearty--we':1,'puny':1,'first':1,'favoured':1,'primitive':1,'useful':3,'striking':4,'simple':4,'image':1,'powerful':1,'apt':1,'obscure--sometimes':1,'forcibly':1,'finely':1,'complex':2,'readily':2,'sensible':1,'little':4,'ancient':2,'basis':1,'distinct':1,'own.':1,'faint':2,'markedly':1,'long':6,'plastic':1,'marked.':1,'literal':1,'much':9,'slowly':2,'low':5,'perfectly':1,'protuberant':1,'easy':2,'successful':3,'shallow':1,'feminine':1,'representative':2,'considerable':1,'gradually.':1,'uncertain':2,'instructive':2,'characteristic':1,'largely':1,'intimately':1,'suggestive':1,'obvious':2,'thin':1,'promising':1,'beautiful':3,'heart':1,'aerial':1,'compact':1,'violently':1,'slim':1,'few':1,'high':2,'effectively':1,'variable':2,'close':1,'tranquil':1,'different':9,'keen':2,'unsuitable':1,'eloquent':1,'utilitarian':1,'hot':4,'vital':1,'grand':1,'unpromising':1,'ordinary':1,'difficult':4,'fairly':1,'opposite':1,'convincing':1,'alert':1,'important':7,'sagacious':1,'fierce':1,'frequently':1,'conspicuous':1,'dark':1,'short':2,'advantageous':1,'effective':1,'crowded':1,'mobile':1,'vigorously':1,'well':2,'severe':1,'serious':2,'incomplete':1},'indubitable':{'multicellular':1,'dynamical':1,'.':1},'bombarded':{'by':2},'coloured':{'and':1,'on':1,'reproductive':1,'lights':1,'illustration':13,'cloth':1,'flowers--attractive':1,'discs':1,'objects':1,'tree-frogs':1,'cardboard':1,'disc':1,'frontispiece':1},'oncorhynchus':{'not':1},'balancing':{'and':1,'on':2,'themselves':1,'not':1,'the':1},'minded':{'of':1},'decide':{'upon':1},'10.--solar':{'prominences':1},'cross-striped':{'quickly':1},'generalised':{'not':1,'percept':1,'humanoid':2,'members':1},'obvious':{'limitation':1,'advantage':1,'that':1,'when':1,'.':1,'advantages':1,'therefore':1,'factor':1,'fact':1},'deficient':{'in':1},'louis':{'agassiz':1,'robinson':1},'ceaseless':{'sifting.':1,'process':1},'elusiveness.':{'v':1},'retrogressions':{'in':1},'mile':{'a':1,'all':2,'towards':1,'would':1,'away':1,'per':1,'.':1,'high.':1},'plain':{'and':1,'story':2,'that':4,'is':1,'account':1,'enough':1,'vanilla':2},'locomotive':{'publishing':2},'trumpeting':{'with':1},'brittle-star':{'and':1},'salterns':{'has':1},'torpedo-net.':{'they':1},'disintegration.':{'there':1},'4557':{'melan':1},'casual':{'and':1},'bass':{'which':1},'inspire.':{'subsequent':1},'darkness':{'and':1,'of':2,'.':1,'was':1,'in':2},'consumers':{'.':1},'witnessed':{'.':1},'emotions':{'ideas':1,'but':1,'.':1,'in':1,'such':1,'beyond':1},'thickness':{'would':1,'of':8,'is':2,'.':1,';':1,'he':1},'him.':{'instantaneously':1,'illustration':1},'argyroneta':{'natans':1},'learned':{'for':2,'to':9,'that':2,'.':1,'their':1,'in':2,';':1,'its':1},'elsewhere.':{'the':1,'as':1},'edited':{'by':1},'loose':{'and':4,'spiral.':1,'sort':1,'behind.':1,'network':1},'answers':{'back':2,'.':1,'to':1,'are':1,'the':1,'must':1,'come':1,'first':1},'elmhirst':{'r':1},'11.86':{'86500':1},'trunk':{'till':1,'it':1},'lull.':{'1':1,'what':1},'i.e':{'.':14},'strong':{'desire':1,'pectoral':1,'vigorous':1,'shoulders.':1,'power':1,'that':1,'reasons':1,'jaws':1,'magnetic':1,'radiation':1,'tendency':2,'evidence':2,'feet':1,'enough':2,'artistic':2,'currents':1,'the':1,'.':2,'carapace':1,'man':1},'interposed':{'a':1},'creeps':{'close':1},'ahead':{'of':1,'in':1,'.':1},'disclaimers':{'of':1},'vegetarian':{'the':1,'scooping':1,'or':1,'triassic':2},'whine':{'about':1},'experimenting':{'and':3,'mood':1,'of':1,'.':1,'as':1,'which':1,'in':1,'rises':1,'with':3,'or':1,'more':1},'unproved':{'hypothesis':1},'soldier':{'wounded':2},'amount':{'generation':1,'of':18,'.':1,'to':2,'which':1,'proportional':1},'successors':{'whatsoever':1,'would':1},'helps':{'to':4,'the':1,'us':1},'tides.':{'illustration':1},'family':{'and':2,'spawn':1,'cares':1,'of':4,'is':1,'perceive':1,'relations':1,'.':2,'124':1,'are':1,'life.':1,'one':1,'affection':1,'swimming':1},'requiring':{'to':1,'no':1},'ask':{'the':1,'.':1},'trained':{'police':1,'animals':1,'to':1},'globes':{'and':1,'of':2,'in':2},'spawned':{'or':1},'conventional':{'modes':1},'ash':{'by':1},'flaws':{'in':1},'discriminative':{'absorption':1},'0':{'earth':1,'venus':1,'4':1},'revelation':{'of':1},'eye--we':{'have':1},'contains':{'about':1,'several':1,'an':1,'no':1,'billions':1,'.001':1,'.':1,'as':1,'ingested':1},'bask':{'on':1},'almost':{'all':5,'constant':1,'suddenly':1,'certain':3,'universal':1,'bound':1,'noisy':1,'confined':1,'see':1,'grazing':1,'at':1,'invisible.':1,'impossible':1,'wholly':1,'uncatchable':1,'as':3,'incredible':1,'cylindrical.':1,'exclusively':1,'surpassed':1,'to':1,'black':1,'girdling':1,'automatic.':1,'circular':1,'complete':1,'any':1,'formed':1,'completely':1,'sagacious':1,'nothing':1,'unique':2,'hairless':1,'a':2,'perfectly':1,'wise':1,'instantaneously':2,'perceptible':1,'no':3,'equal':1,'daily':1,'conquered':1,'ready-made':1,'invisible':2,'squirrel-like':1,'say':1},'unpleasant':{'expressions':1},'vi':{'evolution':1,'.':3},'taken':{'a':1,'by':5,'from':1,'generously':1,'for':1,'that':1,'into':2,'as':1,'.':1,'to':3,'charge':1,'at':7,'in':5,'the':2,'more':1,'any':1,'nearly':1,'out':1},'injury':{'or':1},'temps':{'would':1},'polyps':{'whose':1,'each':2},'stock--an':{'anthropoid':1},'lichens':{'and':1,'on':1},'globe.':{'for':1},'ejected':{'in':1},'site':{'and':1,'www.gutenberg.org':1,'of':2,'includes':1,'which':1,'often':1},'instrumental':{'music':2},'tapeworm':{'certainly':1},'moistened':{'finger-tip':1},'broke':{'up':1},'mounted':{'on':1,'equatorially':1,'batteries':1,'that':1},'producing':{'a':1,'visible':1,'x-rays':1,'an':1},'weathering':{'of':2,'now':1,'have':1},'cremated':{'every':1},'helped':{'by':2,'success':1,'us':1},'rotifer--we':{'are':1},'wafts':{'into':1},'sweeps':{'this':1},'egg-shell':{'and':1,'just':1},'moisture-laden':{'air':1},'nine':{'and':2,'thousand':1,'months':2,'to':1,'moons':1,'cases':1,'hundred':2},'propounded':{'to':1},'spontaneous':{'generation':1,'breaking':1,'above':1,'change':1},'history':{'an':1,'for':1,'no':1,'of':25,'museum':4,'museum.':2,'back':1,'behind':2,'which':1,'in':1,'.':13,'called':1},'f3':{'.':1},'pushes':{'itself':1},'gas.':{'but':1,'illustration':1},'stinging':{'animals':1,'cells':2,'tentacles':1,'lassoes':1},'eclipsed.':{'illustration':1},'pushed':{'will':1,'along':1,'it':1,'out':1},'sun-spot':{'of':2,'is':1},'phrase':{'and':1,'project':4,'has':1,'.':1},'lacks':{'both':1},'species':{'and':1,'1859':2,'use':2,'waddle':1,'off':1,'descent':1,'e.g':1,'perhaps':2,'of':4,'is':1,'there':1,'discover':1,'.':2,'in':1,'represented':1,'what':1,';':2,'hitherto':1,'the':2},'firmly':{'and':1,'established':1,'on':1,'that':1,'.':1,'to':1},'viviparity':{'is':1,'.':1,'the':1,'naturally':1},'starting-point':{'of':1,'the':1,'they':1},'lithographic':{'stones':1},'surpassed':{'only':1,'expectations':1},'friction.':{'but':1},'freezing-point':{'of':1,'or':1,'.':2},'surpasses':{'that':1,'in':1},'daughter-cells':{'into':1},'millikan':{'s':2},'ft':{'.':2},'tried':{'a':1,'and':1,'for':1,'one':1,'to':1,'as':1},'fv':{'contains':1},'communicating':{'cells':1,'nerve-cell':1},'derived':{'energy':1,'from':3,'infinitely':2},'sneak':{'upon':2},'gestation':{'is':1},'triumphs':{'of':5},'consequence':{'of':2,'the':1,'has':1,'enormously':1},'tries':{'to':2},'invasion':{'of':3,'was':1,'due':2,'which':2},'horizontal':{'bar':1,'except':1},'inconceivable':{'distances':1,'ages':1,'.':1,'to':1,'numbers':2,'velocity':1},'a':{'limited':1,'hampton':1,'code':1,'partial':1,'skeleton':2,'remarkable':9,'defenceless':1,'magnetic':7,'varying':1,'focus':2,'month':1,'sequoia':1,'mild':3,'mile':4,'higher':12,'zinc':1,'sweep':1,'dish':1,'golf':2,'conservative':1,'carpet':2,'compact':1,'glimpse':5,'preformed':2,'chain':2,'physiological':3,'pouch':3,'young':4,'passage':1,'granular':1,'tail':2,'cradle':1,'microscopist':1,'stable':1,'fountain':1,'friendly':1,'trilobite':2,'descendant--the':1,'brown':4,'string':1,'deeper':1,'chameleon':4,'very':59,'sun-spot':1,'wave':2,'soapy':1,'smack':1,'graphic':1,'fan':1,'leisurely':1,'microbe':1,'tank':1,'difference':2,'continued':1,'feeble':1,'minute':4,'cool':1,'generalised':3,'sea-anemone':3,'speed':5,'respiratory':1,'beginning':1,'parrot':1,'naturalist':1,'stimulus':1,'skeletal':1,'shock':1,'list':3,'gun':1,'cloudy':1,'large':32,'farthing--contains':1,'swirling':1,'starlit':1,'key--a':1,'succession':1,'small':24,'lever':1,'perceptual':1,'pool':1,'pterodactyl':2,'veritable':3,'bull-terrier':1,'force':1,'meadow':1,'full-grown':2,'trend':2,'crow':2,'sea-squirt':1,'sensation':3,'crop':1,'milligram':1,'past':1,'widened':1,'second':27,'burrower':1,'subtle':1,'further':2,'estimated':1,'port':1,'theory':3,'blue':4,'cargo':1,'stately':1,'clock':1,'waning':1,'fine':7,'section':1,'gatepost':2,'crust':1,'lizard':1,'thickness':2,'cell':2,'reconstruction':2,'new':31,'falling':3,'row':1,'method':2,'multitude':4,'body':19,'condensed':1,'full':3,'trypanosome':1,'degree':3,'compilation':1,'loose':2,'birthplace':1,'fifteenth':1,'drawing':2,'plant-like':2,'protection':1,'tangent':2,'free':4,'separate':6,'tremor':1,'strong':8,'four-chambered':1,'teacher':1,'light-year':1,'sensory':2,'great':39,'substance':4,'survivor':1,'brilliant':3,'study':2,'larger':4,'slave':1,'second--more':1,'soldier':2,'simultaneous':1,'survey':3,'suggestion':4,'social':2,'real':1,'narrow':5,'pathological':1,'steady':1,'diameter':4,'showing':1,'land-crab':1,'useful':4,'secure':1,'halfpenny':1,'stimulus.':1,'discontinuous':1,'fauna--the':1,'loose-limbed':1,'layer':1,'marked':1,'decrease':1,'motor':1,'limb':1,'glance':1,'total':3,'unit':1,'fee':3,'lens':5,'vivid':1,'distinct':3,'revelation':1,'faint':1,'visit':1,'charge':2,'frog':7,'distributing':1,'few':40,'sample':1,'saucerful':1,'centre':1,'knoll':1,'diving-bell':1,'stage':2,'type':3,'more':14,'sort':15,'flat':1,'clever':1,'door':1,'rich':2,'conductor':1,'successful':1,'whirling':1,'screen.':1,'chimpanzee':1,'bodily':1,'fan-like':1,'moistened':1,'surface':1,'rabbit':1,'particular':6,'baby':1,'coyote':1,'hole':2,'hold':1,'rivalry':1,'fly':2,'rebounding':1,'frequently':1,'flora':1,'word':1,'primate':1,'needle':1,'work':2,'stroke':1,'cat':3,'mammalian':1,'suggestive':1,'sudden':3,'thin':1,'universe':1,'chin':2,'fauna':2,'male':2,'history':2,'decorative':1,'continuity':1,'reflector':1,'stream':6,'process':5,'climax':3,'share':1,'parachute':3,'beautiful':3,'minimum':2,'caution':2,'sense':5,'pond':3,'story':1,'hydrogen':1,'species':1,'masterly':1,'terrestrial':2,'huge':8,'united':1,'winter':3,'defective':1,'keen':1,'rather':3,'finger-post':1,'discussion':1,'coot':1,'copious':1,'solidifying':1,'far':1,'hot':1,'pair':2,'forest':2,'fourth':4,'widespread':1,'native':1,'civilisation':1,'stock':3,'mould':1,'yellowish':1,'plant':1,'dull-red':1,'maternal':1,'scion':1,'candle;':1,'thickened':1,'tse-tse':2,'spot':1,'movable':1,'collection':1,'narrow-beaked':1,'diagram':3,'deep-sea':1,'lot':2,'lattice-work':2,'bird-dropping':3,'horizontal':1,'coloured':1,'spiral':7,'man':8,'a':1,'free-swimming':1,'short':9,'natural':2,'liquid':5,'conscious':1,'light':1,'projecting':1,'complexity':1,'green':4,'skilful':1,'deterioration':1,'basket':1,'diary':1,'coral-snake':1,'dream':1,'wing':1,'hen-pigeon':1,'wine':1,'plaice':1,'sperm-cell':1,'shield':1,'feather-wing':1,'double-breather':1,'gradual':6,'minnow':2,'billion':2,'cross':1,'brain':2,'stile':1,'paper':2,'thinning':1,'cold':1,'still':1,'tendency':4,'bunch':3,'chemical':6,'some':2,'group':4,'fit':1,'positively-electrified':1,'glowing':1,'roving':1,'better':2,'window':1,'permanent':1,'microscopic':1,'vast':6,'tubeful':1,'precipitate':1,'main':1,'puzzle':1,'finer':1,'non':1,'good':19,'return':1,'greater':6,'fragment':2,'safe':1,'hunter':1,'number':19,'band':2,'caterpillar':2,'billiard':1,'flint':1,'snake':1,'stout':1,'half':9,'foot':5,'lifelong':1,'day':2,'bank':1,'successor':1,'bony':2,'rocky':2,'profound':1,'mastery':4,'degree.':1,'male-producing':1,'potassium':1,'lifetime':1,'seashore.':1,'hundredth':1,'jellyfish':3,'promise':1,'creature':4,'meal':1,'predatory':1,'turtle':2,'week':3,'molecule.':1,'mental':1,'beginner':1,'map':1,'scanty':1,'garment':6,'fish':6,'hard':1,'spider':7,'related':1,'solution':1,'ball':1,'year':5,'laboratory':1,'first-class':1,'special':2,'magnet':7,'flower':2,'lobster':1,'truly':1,'pigeon':3,'day.':1,'time.':1,'race':2,'flattening':1,'portentous':1,'wide':2,'mammal':1,'brilliantly':1,'sluggish':1,'red':6,'common':12,'foundation':2,'fly.':1,'thrush':1,'belief':2,'many-celled':1,'zoological':1,'southern':1,'million':13,'little':31,'possibility':2,'quite':1,'paralysing':1,'backboneless':2,'reason':1,'lump':1,'hollowed-out':1,'plague':1,'region':2,'cough':1,'marine':3,'wall':3,'monkey':6,'vestige':3,'unique':3,'fixed':2,'yard':1,'hostile':1,'rule':4,'perceptible':1,'moment':6,'british':2,'thing':1,'length':1,'keel':1,'place':2,'nebula':7,'tempting':1,'consequence':1,'weakling':1,'user':2,'blind':3,'copper':3,'sheep-driving':1,'limestone':2,'surviving':1,'striking':7,'spoken':1,'wasp':1,'prehistoric':2,'powerful':4,'scene':2,'sack':1,'system':3,'well-known':1,'fertilised':1,'light-brown':1,'lighter.':1,'spanish':1,'twig-like':1,'ring':2,'tangle':1,'cogged':1,'romance':1,'hood':1,'speck':1,'sheep':1,'city':1,'given':1,'fuller':1,'temperature':1,'swarm':2,'leading':1,'brisker':1,'wing-span':1,'colossal':1,'nebular':1,'wonderful':6,'ton':3,'too':1,'storm':1,'periwinkle':1,'white':7,'compartment':1,'final':1,'friend':2,'low':7,'sex-call':2,'million.':1,'shell':4,'vigorous':1,'fraction':1,'starfish':2,'that':1,'tool':2,'shallow':1,'japanese':3,'crevice':1,'vegetarian':2,'reflecting':1,'zeppelin':1,'somewhat':1,'rifle':4,'prodigious':3,'copy':4,'photographic':3,'peculiar':5,'positively':1,'population':1,'distance':6,'bodyguard':1,'hundred':13,'third':6,'body.':1,'double':1,'tree':7,'rate':2,'medley':1,'bee':2,'youth':1,'matter':9,'legacy':1,'treasure-house':1,'recapitulation':2,'gigantic':4,'steep':1,'distinguished':1,'sublime':1,'collecting':1,'brittle-star':1,'withered':1,'modern':4,'defect':2,'glass':4,'direct':1,'rat':1,'ramifying':1,'sharp':1,'manner':2,'uganda':1,'gaseous':3,'breezy':1,'slab':1,'dozen':4,'conspicuous':1,'female--first':1,'convenient':1,'speculative':1,'shore':1,'soap-bubble':1,'silvery':3,'walk':1,'fish-eater':1,'high':8,'useless':1,'satisfactory':1,'long-drawn-out':1,'soap':4,'propitious':1,'butterfly':1,'memory':1,'continuous':2,'multiple':1,'normal':1,'coconut':1,'leaf.':1,'molecule':5,'boiling':1,'reef-building':2,'regular':1,'connected':1,'non-protrusive':1,'device':1,'coin':1,'hide-and-seek':1,'model':5,'wind.':1,'refractor':1,'known':1,'so-called':1,'piping':1,'thigh-bone':1,'surprising':1,'washerwoman':1,'mobile':2,'heartening':1,'clear':4,'later':6,'metal':1,'dog':6,'wasp-like':2,'tooth':1,'pipe':1,'short-lived':1,'reputation':2,'mammoth':2,'principle':1,'foster-mother':1,'distinctive':2,'velocity':3,'typical':1,'salt':1,'moon':1,'night.':1,'quantity':1,'refund':5,'selected':1,'particularly':1,'sparrow':3,'visitor':1,'manifestation':3,'skin-wing':1,'rotating':2,'bright':1,'shore-pool.':1,'seaweed':1,'constituent':1,'velvety':1,'corner':2,'pill-like':1,'uniform':4,'feat':1,'hustler':1,'staff':1,'current':4,'giant':4,'longer':1,'latent':1,'knowledge':1,'copyright':2,'series':6,'nervous':2,'less':2,'proportion':1,'jolt':1,'fluid':1,'considerable':12,'fox-terrier':1,'winged':1,'bush':1,'going':1,'black':1,'meteorite':1,'pretty':1,'spice':1,'female-producing':1,'ball-room':1,'plate':2,'single-chambered':1,'loss':2,'well-advanced':1,'means':5,'solution.':1,'familiar':1,'vascular':1,'sunny':1,'kind':8,'warm-blooded':1,'pocket':1,'whistle':1,'b':1,'roundabout':1,'measured':2,'silk':1,'spur':1,'live-and-let-live':1,'target':1,'flywheel':1,'bar':1,'progressive':2,'covering':1,'cry':1,'median':2,'violent':4,'doubled':1,'bird':11,'microscope':1,'groove':1,'bison':2,'troop':1,'memory-image':1,'freshwater':2,'web-wing':1,'human':5,'fascinating':1,'habit':1,'flash.':1,'nut':1,'globe':1,'canine':1,'richer':1,'relative':1,'computer':1,'result':2,'frog-like':1,'close':2,'luminous':3,'nocturnal':1,'wonder':1,'peanut':1,'shower':3,'crown':1,'wire':2,'capacity':3,'probable':1,'crooked':1,'subsequent':1,'century':1,'monstrous':1,'definite':6,'seventieth':1,'case':3,'state':10,'proof':1,'hiss':1,'promised':2,'progress':1,'mouthful':1,'perfectly':1,'lethargic':1,'crookes':2,'measurable':2,'notice':1,'recently':1,'cauliflower':1,'parental':1,'fold':1,'screen':3,'weak':2,'dome':1,'veil':1,'rapid':3,'conflagration':1,'waste-product':1,'flowering':1,'swift':2,'problem':2,'colonisation':1,'deep-water':1,'drum':2,'cliff.':1,'country':4,'pre-material':1,'strange':2,'waterfall':2,'quadruped':1,'sensitive':1,'connection':1,'grain':4,'mane':1,'retrograde':1,'lash':1,'comet':4,'passing':1,'whole':8,'humanoid':2,'photograph':9,'stony':1,'cooling':1,'dago':1,'point':3,'simple':9,'continuation':2,'colony':3,'donkey':1,'tapeworm':1,'height':8,'newborn':1,'moot':1,'written':1,'learning':2,'path':2,'greenish':1,'sea-cucumber':2,'hermit-crab':1,'grazing':2,'millimetre':2,'dwindling':3,'deep':1,'basis':2,'tremendous':3,'prelude':1,'damp':1,'tiny':5,'legend':1,'protozoon':1,'reduction':1,'much':5,'newt':1,'certain':18,'reflective':1,'feather':1,'reflex':3,'board':1,'firm':2,'box':2,'direction':1,'penny':2,'corresponding':1,'squirrel':1,'wood-snail':1,'brush':1,'thousand':15,'gas':4,'search':1,'spectrum':1,'coherent':1,'representative':2,'child':3,'laying':1,'careful':3,'land':1,'sound':3,'specialised':1,'novel':3,'conception':1,'remote':1,'solid':4,'plain':3,'straight':3,'prominence':1,'reminiscence':1,'form-resemblance.':1,'technical':1,'while':3,'teaspoonful':1,'biped':3,'voice':2,'cock':1,'guide':1,'mistake':2,'key':2,'food-signal':1,'pound':3,'project':5,'crowning':1,'moth':1,'it':1,'bipedal':1,'quiet':1,'tell-tale':1,'brake':1,'in':1,'twig':2,'simian':6,'property':1,'receptacle':1,'floating':1,'helmet':1,'different':5,'shooting':1,'descent':1,'trial':1,'domesticated':3,'roman':1,'check':1,'member':2,'motley':1,'unity':3,'complex':2,'diplodocus':1,'widely':1,'grand':1,'heavier':1,'web':1,'relatively':5,'yucca':1,'specimen':1,'difficult':2,'wheel':3,'satellite':1,'current.':1,'temporary':2,'cubic':3,'nest':8,'collie':1,'hand':2,'running':1,'dynamo.':1,'moving':1,'delicate':2,'climbing':1,'whale':4,'railway':1,'single':15,'destruction':1,'lower':7,'suitable':1,'stupendous':1,'flattish':1,'weapon':1,'disembodied':1,'tentacle':1,'skull-cap':1,'spoonful':1,'glorious':1,'partner':1,'position':3,'the':1,'reward':1,'musical':1,'left':1,'summer':2,'manifold':2,'kettle':4,'canal':1,'bristle':1,'being':1,'sporting':1,'newton':1,'morsel':1,'loaf':1,'three-chambered':2,'disguise':1,'steamer':1,'victim':1,'touch':1,'jackal':1,'rushing':1,'previous':6,'blow':1,'tailless':1,'disturbance':1,'wedge-shaped':1,'hint':2,'general':5,'bell':2,'master-key':1,'pitcher-plant':1,'silver':1,'straw':1,'spread':2,'transformed':2,'galloping':2,'ray':7,'5':1,'room--pour':1,'transformation':2,'finder':1,'kingdom':1,'puzzle-box':1,'nightjar':1,'fire':2,'format':1,'big':11,'couple':1,'knife-blade-like':1,'period':8,'dark':2,'cromagnon':2,'fusion':2,'royalty':1,'god.':1,'background':1,'vacuum':8,'text-book':1,'world':1,'part':1,'crusher':1,'vague':1,'name':1,'desire':1,'satisfaction':1,'necessary':1,'dislodged':1,'particle':2,'cock-pigeon':1,'signal':2,'performing':1,'sound--':1,'diffraction':1,'specific':2,'soup-plate':1,'vortex':1,'cotton-reel':2,'security':2,'soft':2,'replacement':3,'mathematical':1,'reaches':1,'right':2,'trained':1,'people':1,'prolonged':1,'process--a':1,'plausible':1,'wattle':1,'fully-formed':1,'library':3,'muscle-fibre':1,'sponge':1,'pack':1,'mighty':4,'second.':4,'mirror':4,'diving':1,'battalion':1,'bigger':1,'transparent':1,'saucer':1,'savage':1,'lung.':1,'dense':1,'calculating':1,'prolific':1,'curious':3,'broad':1,'tube':4,'footing':1,'fox':1,'nook':1,'favourite':1,'critical':2,'mutation':1,'changeful':1,'starch':1,'repeopling':1,'transmutation':1,'trap':1,'beetle':1,'knitting-needle':1,'thunderstorm':1,'reasonable':2,'power':2,'slight':3,'notable':4,'pupil':1,'cork':1,'life-or-death':1,'step':1,'caricature':1,'chick':1,'peer':1,'tidal':1,'revolution':3,'chapter':2,'plastic':1,'stone':5,'quarter':4,'central':1,'cigarette':1,'heat-measuring':1,'of':1,'biscuit':1,'bit':3,'slender':1,'greatly':1,'nucleus':5,'bright-green':1,'basin':1,'provisional':1,'pre-human':1,'swimming':1,'heavy':1,'primitive':2,'whole.':1,'cell-wall':1,'predominance':1,'colour':2,'variable':1,'wrack':1,'lung':2,'lively':1,'female':4,'cultivated':1,'pivot':3,'.':16,'telescope':3,'strangely':1,'minute.':1,'weight':2,'well-developed':1,'wonder-horse':1,'grave':1,'tennis':1,'question':1,'reindeer':1,'long':27,'fight':1,'continental':1,'standstill':1,'sea-spider':1,'double-armed':1,'hundred-millionth':1,'house':2,'bubble':2,'hare':1,'bud':1,'greyish':1,'medium':3,'relic':1,'complete':2,'form':2,'voracious':1,'magnificent':1,'registered':2,'converse':1,'neanderthal':1,'triangular':1,'mysterious':1,'cloud':1,'billion.':1,'game':2,'dead':7,'boon':1,'sprinkling':1,'line':9,'true':5,'dull':5,'versatile':1,'luxuriant':1,'continuance':1,'minnow--the':1,'rush':1,'partitioned':1,'genealogy':1,'flood':1,'characteristic':4,'spectroscope':1,'purpose':1,'maximum':3,'supple':1,'planet':2,'crystal':1,'growth':2,'limit':1,'centenarian':1,'mature':2,'monument':1,'soldering':1,'water-bag':1,'distribution':1,'piece':15,'similar':3,'leaf':7,'strongly':1,'stock--an':1,'constant':3,'flow':5,'universal':2,'measure':1,'brightly':1,'whelk':2,'sticky':1,'scientific':1,'diamond':4,'well-defined':1,'leptocephalus.':1,'home':5,'sheath':1,'ship':1,'horse':5,'living.':2,'curtain':1,'film':2,'physical':2,'water-filled':1,'brick':1,'variety':5,'glacier':1,'way':6,'there':1,'prerogative':1,'fruit-laden':1,'portion':1,'reality':2,'neolithic':1,'field':3,'prism':2,'setting':2,'stagnant':1,'branch':5,'most':6,'puppy':1,'superfluous':1,'sufficient':2,'10':1,'polar':1,'quintillion':1,'star':10,'phoenix':1,'living':3,'shelter':1,'flinty':1,'preceding':1,'planet.':1,'drift':1,'prepared':1,'choice':1,'scale':1,'recent':5,'fresh':2,'rolling':1,'yorkshire':1,'hair':1,'score':1,'sneeze':1,'concatenation':1,'source':2,'tree.':1,'vaseline':1,'meteor':1,'bivalve':2,'lead':1,'bullet':2,'dogma':1,'deep-seated':1,'movement-controlling':1,'yacht':1,'jelly':1,'drifting':1,'gorilla':2,'depth':1,'train':1,'mass':5,'fact':2,'time':17,'big-brained':1,'stick':1},'pithecanthropus':{'erectus':1,'erectus.':1,'.':1,'the':8,'was':1,'seem':1},'spectra':{'of':2,'six':1,'.':1,'corresponds':1,'36':1},'bugs':{'ever':1},'renewing':{'the':1},'deterioration':{'of':1,'the':1},'healthfulness':{'and':1},'egg':{'and':1,'a':1,'shed':1,'just':1,'for':1,'of':2,'is':1,'-cell':1,'should':1,'to':1,'which':1,'in':1,'depository':5,'signalling':1,'has':1},'chicks':{'peck':1,'had':1},'earthworm':{'is':1,'.':1,'1':1,'76':1,'s':2,'72':1,'half':1,'fragments':1,'or':1,'earthworms':1},'help':{'preserve':1,'them':1,'of':1,'flotation':1,'it':1,'to':2,'see':1,'produce':1,'in':2,'the':1},'reservoir':{'of':3},'hierarchy':{'of':1},'soon':{'a':1,'picked':1,'began':1,'it':1,'to':1,'as':1,'became':1,'realise':1,'learn':2,'learned':1,'has':1,'was':1,'appears':1,'partially':1},'indistinguishable':{'but':1},'held':{'closely':1,'to':1,'back':1,'together':2,'up':1,'their':1,'above':1,'by':1},'committed':{'to':1},'three-horned':{'skull':1},'kinetic':{'and':1,'energy':3},'liquefies':{'gases':1},'positively-electrified':{'body':1,'atoms':2},'tickings':{'of':1},'lateral':{'line':2},'solving':{'the':1},'teeming':{'.':1},'gentleness.':{'illustration':1},'absence':{'of':7,'or':1},'disclosed':{'by':1},'founders':{'of':1},'peanuts':{'which':1},'mammal--instinctive':{'aptitudes--power':1},'finer':{'world':1,'form':1},'evening':{'work':1,'star':1,'primrose':1},'food':{'and':10,'accentuated':1,'danger':1,'requiring':1,'into':1,'within':1,'it':1,'are':1,'in':3,'consists':1,'crisis':1,'note':1,'vacuole':1,'from':3,'for':2,'there':2,'.':2,'particles':2,'outside':1,'going':1,'was':1,'is':2,'on':1,'shelter':1,'but':1,'227':1,'with':1,'by':1,'enemy':1,'like':1,'largely':1,'many':1,'inside':1,'near':1,'without':1,'the':1,'or':3},'theory--the':{'structure':1},'pglaf':{'owns':1},'floating':{'plants':2,'and':1,'log':1,'sea-meadows':4,'dead':1,'buns':1,'seaweed':1,'in':1,'dust':1,'bacteria':1,'out':1},'anticipated':{'forty-one':1},'permissible':{'to':1},'foot':{'and':2,'flat':2,'of':2,'but':1,'high':2,'became':1,'long':1,'in':2},'feet':{'and':2,'four':2,'from':3,'just':1,'of':1,'whereas':1,'long':2,'.':5,'high':2,'deep':1,'7':1,'in':2,'or':1,'are':2},'stopper':{'of':1},'finite':{'or':1},'dulled':{'by':1},'occasions':{'we':1},'male-producing':{'egg':1},'enlarged':{'pectoral':1,'illustration':1,'in':1},'infer':{'this':1},'flowers--attractive':{'to':1},'stopped':{'until':1},'radial':{';':1,'animals':1,'canals':1},'neanderthalers--the':{'general':1},'dominating':{'the':1},'referred':{'to':3,'to.':1},'heavy':{'great':1,'blankets':1,'gas':1,'brain':2,'as':2,'complicated':1,'with':1,'ape':1},'transcribe':{'and':1},'matthew.':{'diagram':1,'1':1},'restless':{'inquisitiveness':2,'experimenting':1},'jaws':{'and':1,'shaped':1,'of':2,'.':1,'engulfing':1,'which':1,';':1},'down--the':{'day':1},'sulked':{'for':1},'energy.':{'sec':1},'ball':{'revealing':2,'and':1,'of':4,'found':1,'the':2,'or':1},'punitive':{'or':1},'trilobites--jointed-footed':{'antenna-bearing':1},'beyond':{'a':1,'even':1,'that':2,'this':1,'radium':1,'science.':1,'possibility':1,'its':1,'these':1,'which':1,'our':4,'the':6,'playing':1,'ordinary':1},'event':{'when':1,'seems':1,'than':1,'which':1},'oviparous':{';':1},'unsurpassed':{'gifts':1},'percepts':{'and':1},'crustacean':{'s':1},'surrounded':{'by':3},'abysses':{'and':1,'from':1,'of':1,'took':1,'.':1,'so':1,'are':1,'the':1},'america.':{'3':1,'2':1,'4':1,'6':1},'coincidences':{'.':1},'safety':{'on':1,'for':1,'of':3,'is':2,'within':1,'.':1,'until':1,'or':1,'first':1},'7':{'and':1,'palaeolithic':1,'inches':1,'why':1,'.':3,'000':1,'918':1,'1871':1,'250':1,'with':1,'the':2,'250000':1},'brownish':{'caterpillars':1},'sharp-eyed':{'enemies':1},'house-flies':{'and':1},'issue':{'of':2},'meteoric':{'matter':3},'metchnikoff':{'the':1},'drink':{'from':1},'inert':{'matter':2,'just':1,'in':1},'protruding':{'bag':1},'lights':{'as':1,'the':2},'schwalbe':{'has':1},'backboneless':{'stocks':1,'animals':3,'or':1,'animal':2},'reason':{'for':6,'to':9,'being':1,'of':2,'is':4,'in':1,'but':1,'.':1,'how':1,'--an':1,'i.e':1,'quite':1,'why':2},'base':{'and':1,'of':5,'an':1},'jaw.':{'illustration':1},'brightest':{'star':1},'put':{'a':2,'on':6,'her':1,'into':1,'out':2,'some':1,'it':3,'together':3,'two':1,'to':2,'together.':1,'zinc':1,'in':2,'forward':1,'our':1,'the':5,'themselves':1,'safely':1,'your':1,'evenly':1},'earliest':{'known':3,'remains':1,'inhabitants':1,'metal':1,'representatives':1},'algae':{'and':2,'symbiosis':1,'.':1},'revolutionary':{'changes':1},'capacities.':{'body':1},'perceptible':{'to':1,'impression':1},'persuading':{'some':1},'tortoises':{'to':1,'from':2},'fifty-four':{'muscles':1},'american':{'killdeer':1,'monkey':1,'forests':1,'monkeys':1,'.':1,'minnows':1,'astronomer':1,'tree-frogs':1,'continent':1},'conquered.':{'it':1},'daisy':{'are':1},'undergo':{'disintegration.':1},'zoophyte':{'called':2,'.':2},'assign':{'no':1},'most...':{'.':1},'partnerships':{'between':1},'knots':{'subsequently':1,'or':1,'smoke':1,'for':1},'probability':{'is':4,'that':1,'the':1,'in':1},'encoding':{':':1},'knocking':{'off':1},'reflected':{'rays':1,'from':3,'back':1,'to':1,'depends':1,'through':1},'antiquity':{'and':1,'of':3,'the':1,'with':1},'moorings':{'.':1},'elder':{'brothers':1},'unexpected':{'manoeuvres':1},'incubated':{'in':1},'warty':{'chameleon':3,'creature':1},'1871':{'when':1},'mist':{'that':1},'miss':{'gertrude':1,'the':1,'part':1,'frances':1},'ninth':{'printing':1},'foraminifera':{'and':1,';':1,'each':2},'utters':{'instinctively':1},'horse':{'and':7,'eohippus':1,'use':1,'merychippus':1,'orohippus':1,'of':2,'showing':2,'pliohippus':1,'running':1,'.':1,'shunting':1,'will':1,'s':1,'mesohippus':1,'a':1,'have':1,'which':1,'has':1,'beginning':2,'or':1,'is':1},'pelagica':{'this':1,'125':1},'findings':{'of':1},'interwoven':{'with':1,'that':1},'obedience':{'to':1},'483.3':{'11.86':1},'wonderful':{'instruments':1,'modern':1,'cluster':1,'devices':1,'colour-scheme':1,'fabric':1,'to':1,'system':1,'.':1,'instrument':3,'new':1,'elements':1,'intellectually':1,'revelations':1,'photograph':1,'corona':1,'manifestations':1,'mass':1,'source':1,'piece':1,'changes':1,'discoveries':1,'x-ray':2,'result':1},'gibraltar':{'professor':1,'so':1},'einstein.':{'illustration':1},'scheme':{'represents':1,'of':1},'danger-call':{'of':1},'passed':{'and':5,'perhaps':1,'down':1,'to':1,'as':1,'through':3,'the':2,'by':1,'before':2},'pure-bred':{'wheat':1},'measurable':{'.':1,'quantity':2},'basal':{'appetites':1},'1918':{'flew':1,'upwards':1},'blindly':{'and':1},'1911':{'showing':1,'23':1},'half-made':{'wing':1},'1912':{'.':1,'in':1},'1914':{'this':1,'and':1,'41':1,'an':1},'1917':{'a':1,'we':1,'upwards':1},'grew':{'to':1,'wheat':1,'by':1,'up':1},'tunic':{'of':1},'kindly':{'emotions':1},'grey':{'red':1,'in':1},'haddock':{'or':1},'intensities':{'of':1},'toward':{'the':2,'death':1,'increasing':1,'us':1},'stickleback':{'enters':2,'being':1,'of':1,'is':2,'s':1,'making':2},'fisheries':{'in':1},'withered':{'leaf':1,'herbage':1},'clerk-maxwell':{'james':1,'246':1,'one':1},'bells.':{'in':1},'alongside':{'of':3},'juice':{'has':1},'sentences':{'of':1,'were':1},'events':{'included':1},'concentration':{'than':1},'organs':{'and':1,'of':1,'pass':1,'but':1,'.':4,'in':1,'throughout':1,'or':1},'gathering':{'light':1,'some':1,'round':1,'to':1,'of':1},'atoms--the':{'energy':1,'discovery':1},'lid':{'.':1},'lie':{'on':1,'disregarded':1,'outside':1,'low':1,'in':1,';':1,'at':1},'u.s':{'.':2},'speculative':{'and':1,'picture':1,'point':1},'flaming':{'jets':1,'hydrogen':2},'scotland':{'1920':1,'s':1,'since':2,'were':1,'.':1},'camouflage':{'and':1,'a':1},'lit':{'our':1,'the':1,'by':1,'up':1},'relieved':{'of':1,'by':2},'labour':{'and':2,'becomes':1,'has':1,'set':1,'.':1},'lip':{'of':1,'the':1,'which':1,'but':1},'useless':{'vestige':1,'responses':1,'movements.':1,'halfpennies':1,'heat':1,'movements':2},'command':{'travels':2},'presently.':{'regions':1,'if':1},'embryological':{'evidence':1,'proof':1},'towards':{'a':1,'what':2,'or':1,'becoming':1,'us':2,'fruit-eating':1,'him.':1,'flesh-eating':1,'harmony':1,'nobler':1,'the':17,'increasing':1,'clothing':1,'its':2,'those':1},'figures--bison':{'reindeer':1},'quote':{'professor':1,'the':1},'literal':{'demonstration':1,'blood-relationship':1},'systems':{'comes':1},'indefinitely.':{'the':1},'eaten':{'or':1},'position':{'and':1,'would':1,'these':1,'of':3,'is':2,'.':1,'held':1,'as':1,'in':1,'invisible':1,'increasing':1,'where':1,'into':1},'alpha':{'the':2,'rays':1,'particle':1,'centauri':2},'approved':{'fashion':1},'19.--comet':{'september':1},'muscle':{'and':1,'for':1,'which':1,'blood-vessel':1},'evolution--factors':{'in':2},'prolongation':{'of':2},'mobile':{'ribs':1,'vehicle':1,'pigment-cells':1,'.':1,'water':2,'in':1,'tongue':1},'performances':{'and':1,'depended':1},'clear':{'and':2,'for':1,'that':8,'ideas':1,'illustration':1,'.':2,'water':1,'as':1,'without':1,'adaptation':1,'in':1,'passage':1,'why':2},'broadened':{'and':1,'out':1},'snapping':{'at':1},'25--giant':{'spiral':1},'electrons':{'and':7,'copper':1,'all':1,'being':1,'possessing':1,'move':1,'moving':1,'it':2,'an':2,'produced':2,'streaming':2,'as':2,'are':7,'in':6,'particles':1,'compose':1,'from':8,'would':1,'electricity':1,'flying':1,'circulating':1,'travel.':1,'.':11,'rushes':1,'to':2,'behind':1,'without':1,'therefore':1,'contained':1,'revolving':1,';':2,'has':3,'pass':1,'is':2,'do':1,'may':1,'circulated':1,'but':2,'263':1,'267':1,'revolve':1,'now':1,'spin':1,'a':1,'rush':1,'resulting':1,'receive':1,'leave':1,'into':1,'258':1,'across':1,'will':1,'continue':1,'so':1,'were':1,'become':1,'increase':1,'or':3},'foster-mother':{'hen':1},'velocity':{'for':1,'of':8,'sufficient':1,'.':2,'which':1,'beyond':1,'masses':1},'usual':{'interchange':1,'direction':1,'definite':1,'difficulty':1,'mode':1,'way':1,'shortness':1,'notion':1},'tubes':{'and':1,'.':1,'by':1,'until':1},'one-eighth':{'of':1},'phenomenon':{'of':1,'is':1,'.':1},'registers':{'the':1,'itself':1},'caries':{'hitherto':1},'velvety':{'skin':1},'stores':{'of':3,'nor':1},'heavens':{'we':1,'7':1,'being':1,'is':1,'.':5,'are':1,'constitutes':1,'which':2,'the':1,'more':1,'with':1,'along':1,'at':1},'164.78':{'34800':1},'wriggle':{'through':1,'up':1},'debts.':{'moreover':1},'with.':{'in':1},'betokens':{'a':1},'northern':{'hemisphere':1,'rhodesia':2,'spain':4,'lakes':1},'duncan':{'.':1},'series':{'of':13,'is':1,'e.g':1,'.':2},'distances;':{'the':1},'less':{'satisfactory':1,'secure':1,'striking':1,'expensively':1,'successfully':1,'powerful':1,'genial':1,'likely':1,'definite':1,'in':1,'radiation':1,'clearly':1,'protrusive':1,'prolific':1,'domed':2,'able':1,'.':2,'moist':1,'stable':2,';':1,'degree':1,'continuous':1,'accurately':1,'important':4,'strenuous':1,'known':1,'regular.':1,'than':17,'conspicuous':1,'aimless':1,'central':1,'fit':2,'brusque':1,'of':3,'steady':1,'severe':1,'promising':1,'the':1,'spontaneous':1},'darted':{'furiously':1},'orbits.':{'circling':1,'yet':1},'surveyed':{'.':1},'pretty':{'generally':1,'fluorescence':1,'pieces':1},'quadrupedal':{'fashion':1},'circle':{'this':1,'of':1,'here':1,'are':1,'round':3,'shows':1},'darwin':{'origin':1,'sir':1,'said':1,'showed':3,'charles':1,'56':1,'observed':1,'s':9,'greatest':1,'in':1,'the':3,'called':1},'ball-room':{'.':1},'dominant':{'spring':1,'reptiles':1},'meanwhile':{'the':1,'we':1,'it':1},'trees':{'a':2,'and':2,'like':1,'with':1,'of':1,'.':2,'where':2,'were':1,'the':1,'has':1,'was':1,'why':1},'famous':{'jesuit':1,'theory':1,'form':1,'of':1,'for':4,'book':1,'manchester':1},'feels':{'for':2},'combinations':{'of':1},'during':{'a':3,'her':1,'eclipses':1,'this':3,'many':1,'an':2,'these':1,'which':5,'the':19,'its':2},'molten':{'interior':1,'matter':1,'by':1},'birds.':{'during':1,'according':1,'it':1},'catches':{'a':1,'the':1},'intrude':{'on':1},'alteration':{'modification':1,'of':1},'flight.':{'illustration':1},'underlying':{'photosphere':1},'withdrawal':{'of':1},'hours--a':{'prodigious':1},'hobbled':{'with':1},'seventeen':{'and':1,'years':1},'religiosa':{'a':1,'138':1},'electro-magnet':{'and':1},'throwing':{'the':1,'off':1},'plausible':{'view':1},'culture':{'gave':1,'migrating':1,'.':1},'invisible.':{'the':2,'sec':1,'illustration':1},'close':{'and':1,'rapidly':1,'indeed':1,'enough':1,'together':1,'to':3,'resemblances':1,'contact':2,'at':1,'reproduction':1,'of':1,'resemblance':1,'by':2},'plankton.':{'hunger':1},'gravitation':{'that':1,'of':1,'is':1,'.':3,'to':1,';':1,'etc.':1},'probable':{'date':1,'age':1,'that':12,'period':1,'however':2},'plasticity':{'of':1,'.':2},'not-living':{'material':1,'materials':1},'tibet':{'indo-china':1},'seventieth':{'of':1},'educability':{'is':1,'but':1,'.':1},'won':{'most':1},'years.':{'and':1,'in':1},'probably':{'associated':1,'illustrates':1,'an':1,'not':1,'are':1,'begun':1,'in':2,'cloud':1,'profitable':1,'from':2,'adapted':1,'there':1,'when':1,'indicate':1,'much':2,'helps':1,'survive':1,'means':2,'lived':1,'that':2,'far':1,'safe':2,'clearer':1,'less':1,'connected':1,'represented':1,'during':1,'breeding':1,'intrinsically':1,'a':3,'did':1,'of':2,'taking':1,'preyed':1,'suggests':1,'points':1,'evolved':2,'the':3,'encased':1,'counted':1,'came':1},'conditions':{'and':1,'that':2,'this':1,'of':15,'when':1,'culminating':1,'.':5,'will':1,'while':1,'internal':1,'are':4,'they':1,'in':2,'reached':1,'the':1,'our':1},'aeons':{'of':1},'ps':{'.':1},'stagnation':{'.':1},'egg-cells':{'and':4},'fox-bat':{'with':1},'missing':{'an':1},'description.':{'it':1},'moults':{'three':1},'craters':{'and':1,'on':1,'indicated':1,'of':3,'.':1,'which':1},'ranked':{'amongst':1},'basalts':{'.':1},'invisible':{'and':2,'because':1,'star':1,'thread':1,'visible':2,'light':2,'gas':1,'against':1,'.':3,'particles':1,'to':1,'rays':1,'electrons':1,'but':1,'molecules':1,'waves':1,'world':1,'medium':1,'if':1},'both':{'jaws':2,'is':1,'in':1,'are':1,'paragraphs':1,'birds':1,'cases--marvellous':1,'from':1,'ways':1,'when':2,'.':1,';':1,'difficult':1,'eyes':2,'his':1,'kinds':1,'photography':1,'chimpanzee':1,'minnows':1,'adult':1,'cases':3,'with':1,'sides':2,'man':1,'on':1,'processes':1,'land':1,'these':3,'of':4,'hemispheres':1,'below':1,'time':1,'small':1,'the':2,'fertility':1,'herons':1},'humidity.':{'there':1},'gaunt':{'and':1},'greater--a':{'sudden':1},'sensitive':{'and':1,'period--the':1,'bromogelatine':1,'hairs':1,'no':1,'to':2,'that':1,'line':1,'than':3},'picture.':{'b':1,'illustration':2},'vaster':{'irregular':1},'experimental':{'plot':1,'discoverer':1,'study':1,'men':1,'character':1,'evidence':1,'behaviour':1,'initiative':1,'way':1,'embryology':1,'conditions':1,'devices.':1,'proof':1},'battery':{'consisted':1},'hewn':{'but':1},'whatever':{'be':1,'kind':1,'medium':1,'means':1,'advances':1,'colour':1,'number':1,'part':1,'way':1,'sets':1,'the':1},'chromosomes.':{'3':1,'5':1,'illustration':1,'6':1},'galileo':{'s':1,'who':1},'climbers':{'of':1,'in':1},'undulating':{'flashes':1},'revolutionising':{'our':1},'persecuted':{'.':1},'described':{'on':1,'later':1,'it':1,'one':1,'to':1,'as':3,'without':1,'stars':1,'in':4,'the':1,'.':1,'by':1},'stamp':{'of':2},'damp':{'meadow.':1,'weather.':1,'grass':1,'meadow-grass':1},'exert':{'this':1,'a':1},'geddes':{'and':1},'describes':{'the':1},'maintenance':{'of':1},'territory':{'we':1},'empty':{'available':1,'shell':2,'space':2,'of':1,'nest':2,'space--ether':1,'coco-nut':1,'infinite':1,'chambers':1,'the':1,'tubular':1},'jesuit':{'astronomer':1},'lived':{'on':1,'like':1,'for':1,'there':1,'.':1,'in':3,'100':1,'between':1},'partly':{'on':2,'because':9,'opened':1,'due':2,'accounts':1,'by':2},'success.':{'the':1},'intelligently.':{'intelligence':1},'freezing-point.':{'the':1},'exempt':{'status':2,'from':1},'permeating':{'the':1},'else':{'it':1,'soon':1,'in':2,'.':1,'seek':1,'mere':1},'lives':{'a':1,'on':2,'there.':1,'for':1,'inside':1,'together':1,'.':3,'at':1,'which':1,'in':4,'or':1},'liver':{'and':1},'magnetised':{'iron':1},'look':{'towards':1,'like':1,'for':3,'exactly':1,'.':1,'to':1,'at':4,'forward':2,'further':1,'precisely':1,'after':3,'more':1},'opportunity.':{'there':1},'ape-like':{'and':1,'eyebrow':1},'pace':{'sternly':1,'of':1},'while':{'and':1,'all':1,'contemporaneously':2,'energy':1,'some':1,'it':1,'one':1,'at':1,'zinc':1,'in':1,'our':1,'neanderthal':1,'her':1,'there':1,'two':1,'to':1,'we':1,'they':2,'others':2,'monkeys':1,'a':2,'on':1,'fleas':1,'these':1,'many':1,'this':1,'the':12,'similar':1},'ought':{'to':4,'definitely':1},'286':{'transformation':1},'mitchell':{'it':1},'guide':{'the':1,'him':1,'.':1},'pack':{'of':1},'albatros':{'fashion.':1},'forelegs':{'as':1},'selected':{'spot':1,'was':1},'dictum':{'that':1},'fed.':{'the':1},'overlooked':{'the':1},'geologists':{'to':1,'cannot':1},'reads':{'the':1,'like':1},'ready':{'to':4,'way':1},'simian':{'tribe.':1,'branch':1,'stock--physiological':1,'characters':1,'line':1,'type':1,'stock':5},'communal':{'life.':1},'predominates':{'.':1},'forewing':{'.':1},'belong':{'to':6,'as':1,'.':1},'unpromising':{'haunt':1},'shad':{'which':1},'grand':{'hardwood':1,'total':1,'.':1},'modification':{'or':1},'composition':{'of':3,'what':1,'was':1,'we':1},'clearness':{'and':1},'hind-leg':{'of':2},'used':{'on':1,'we':1,'for':6,'fire':1,'is':1,'up':2,'.':1,'to':14,'as':4,'threads':1,'in':10,'such':1,'the':1,'was':1,'by':5,'if':1},'temporary':{'and':2,'diseased':1,'nest':1},'suggestion':{'of':5,'that':2,'was':1,'.':1},'optic':{'nerve':1},'tube.':{'it':1},'u.s.':{'unless':1},'wilson':{'a':1,'observatory':2,'reflector':1,'45':1,'reflecting':1,'california':2,'observatory.':8},'000':{'and':1,'barrels':1,'miles':35,'years.':1,'pounds':3,'of':6,'times':3,'feet':1,'to':6,'000':20,'miles--eighteen':1,'are':1,'atoms.':1,'inch':2,'deg':2,'years':17,'bushels':2},'uses':{'it':1},'cleaning':{'the':1},'saucer-shaped':{'body':1},'assortment':{'of':1},'brussels':{'sprouts':1},'tufts':{'growing':1,'of':1,'in':1},'changed.':{'we':1},'luminescence':{'will':1,'makes':1,'that':1},'older':{'astronomers':1,'and':1,'loess':1,'yucca':1,'than':1},'spectrum.':{'that':1},'copper.':{'illustration':1},'consistence':{'of':1},'obviously':{'that':1,'much':1,'means':2,'desirable':1,'depends':1,'complex':1,'the':1,'must':1},'segmented':{'marine':1},'forms.':{'illustration':1},'calcutta':{'which':1,'.':1},'suddenness':{'the':1,'like':1},'scouring':{'a':1,'tide':1},'distances':{'and':1,'distance':1,'from':5,'of':3,'within':1,'deriving':1,'are':1,'which':1,'between':1,'the':1,'with':1},'alytes':{'not':1},'cave':{'in':2,'drawings':1,'northern':4,'.':1},'judgments':{'about':1,'expressed':1,'in':1},'migratory':{'flight':1},'overflows':{'over':1},'rabbit--who':{'by':1},'quarters':{';':1},'perforating':{'the':1},'planetoids':{'splashed':1,'or':1},'useful':{'and':1,'associations':2,'ready-made':1,'branches':1,'means':1,'pennies':1,'teeth':1,'law--senses':1,'to':6,'deposit':1,'advertisement':1,'in':3,'offices.':1,'law':1,'quality':1,'first':1},'praying':{'mantis':3},'informal':{'introductions':1},'possessors':{'to':1,'back':1,'than':1},'stock--physiological':{'proof--embryological':1},'debatable':{'questions':1},'remaining':{'on':1,'six.':2,'provisions.':1},'elver':{'at':1},'unravelled':{';':1},'march':{'23':2},'insert':{'here':1},'reptilian':{'splendour.':1,'mind--mind':1,'life':1,'mind':1,'features':1},'showing':{'a':10,'division':1,'seven':2,'him':1,'upper':1,'gradual':2,'that':1,'evolution':1,'marked':1,'.':1,'how':1,'various':2,'no':1,'under':1,'in':1,'variable':1,'what':1,'the':16,'many':1,'their':1,'trout':1},'game':{'of':4,';':1,'or':1},'wiser':{'than':1},'text-book':{'of':2},'damage':{'or':1},'distance.':{'illustration':1},'wings':{'of':3,'is':2,'turned':1,'it':1,'.':4,'suggests':1,'while':1,'are':3,'have':1,'in':1,'the':1},'translucent':{'blue':1},'ponds':{'and':1,'where':1,'they':1,'.':1},'fore-limb':{'and':1,'of':2,'is':1,'has':2,'transformed':1},'long-drawn-out':{'sublime':1},'pillar':{'to':1,'the':1,'parallel':1},'resorted':{'to':1},'holes':{'and':1},'manifest':{'themselves':1},'eel':{'and':1,'is':1,'early':1,'haddock':1,'anguilla':2,'ever':2},'popular':{'lectures':1,'astronomy':1,'idea':1,'sense':1,'interpreter':1,'estimation':1},'death-feigning':{'for':1},'minced':{'snail':1},'mathematical':{'discussion.':1,'astronomers':1,'genius':1,'points':1,'consequence':1,'astronomy':1,'reasoning':1},'wrack':{'behind':1},'cones':{'and':1,'to':1},'negative.':{'a':1},'creation':{'of':1,':':1,'when':1,'.':3},'some':{'pollen':1,'remarkable':1,'insects':2,'cromagnards':1,'muscle-fibres':1,'worms':1,'parts':4,'years':2,'volcanic':1,'cases':10,'knowledge':1,'hint':1,'interesting':1,'young':1,'improvement':1,'source':1,'writers':1,'black':1,'botanists':1,'deep-seated':1,'thousands':1,'dispute':1,'which':1,'food':1,'leisure':1,'dark':2,'they':1,'radio-active':1,'uncertain':1,'adventurous':1,'stimulus':1,'deficient':1,'miles':1,'truth':1,'small':2,'force':1,'people':1,'animals':4,'idea':2,'namely':1,'are':3,'measure':8,'disturbing':1,'nocturnal':1,'creatures':1,'respects':3,'organisms':1,'solemn':1,'anatomists':1,'eminent':2,'uniform':2,'fossil':1,'new':4,';':1,'twenty-five':1,'sluggish':1,'trout':1,'degree':2,'men':1,'lakes':1,'quite':1,'water':1,'extraordinary':1,'reason':1,'extent':5,'path':1,'canals':2,'strong':1,'great':2,'thirty':1,'of':55,'region':1,'undisguised':1,'aboriginal':1,'butterflies':1,'place':1,'deep-sea':1,'other':15,'mound-birds':1,'members':1,'striking':1,'simple':2,'fishes':3,'hermit-crabs':2,'carry':1,'ape':1,'little':1,'nebulae':2,'would':2,'harmless':1,'lizards':1,'unknown':1,'long':1,'way':5,'more':1,'sort':8,'that':1,'vanishing':1,'mammals':2,'explanation':1,'precision':1,'races':1,'particular':1,'prodigious':1,'primeval':2,'careful':1,'spirit':1,'task.':1,'150':1,'distance':2,'kind':5,'word':1,'solid':1,'theories':1,'nine':1,'were':1,'beautiful':2,'imaginative':1,'larger':1,'beetles':1,'process':1,'modern':1,'geologists':1,'states':1,'say':1,'have':2,'regulate':1,'species':2,'education':1,'considerable':1,'detail':1,'astronomers':4,'very':1,'strange':1,'electrical':1,'animal':1,'semi-fluid':1,'intelligent':1,'day':2,'fairly':1,'unimaginable':1,'kinds':2,'earlier':1,'delicacy':1,'secluded':1,'waves':1,'authorities':6,'such':2,'land':1,'dragon-flies':1,'surprising':1,'magical':2,'think':1,'fundamental':3,'time':1,'wood-snails':1,'eighty-odd':2,'bodies':1,'typical':1},'yolk':{'fully':1,';':1,'has':1,'y.s.':1,'.':1},'apes--gorilla':{'orang':1},'urgent':{'need':1},'lips':{'and':2,'four':1,'audibly':1},'economic':{'and':1},'besides.':{'interpretation':1},'nerve-fibres':{'one':1},'lingers':{'in':1},'body-mind':{'.':1},'universes':{'why':1,'comparable':1,'.':1,'like':1,'in':1},'bruising':{'the':2},'savage':{'nature':1},'nonproprietary':{'or':1},'fifty-millionth':{'of':1},'pitchblende':{'about':1,'which':1},'exceeding':{'the':1,'that':1},'competitions':{'arose':1},'pounding':{'breakers':1},'civilization':{'.':1},'sympathetic':{'ganglia':1,'colouring':1},'claimed':{'that':1},'knitting-needle':{'in':1},'eating':{'at':2,'one':1},'protrusible':{'tongue':1,'tentacles':1},'processing':{'or':1},'lakes':{'and':1,'there':1,'are':2},'stem':{'still':1,'diverged':1,'help':1,'goes':1,'.':2},'step':{'meant':1,'towards':1,'two-thirds':1,'which':1,'in':6,'toward':1,'was':3},'lasts':{'till':1,'through':1,'no':1},'become':{'equally':1,'words':1,'beautifully':2,'satisfactory':1,'an':1,'at':1,'sea':1,'in':3,'luminous':1,'living':1,'bipeds':1,'unavailable':2,'unavailable.':1,'burrowers':1,'silvery':1,'shorter':2,'permanent':1,'fatal':1,'more':3,'real':1,'yellowish':1,'separate':1,'secondarily':1,'invisible--just':1,'faintly':1,'steadied':1,'parr':1,'utterly':1,'not':1,'instinctive':1,'dissipated':1,'quite':1,'invisible.':1,'a':13,'organically':1,'perfectly':1,'like':1,'liquid':1,'of':1,'large':1,'the':2,'adapted':1},'abroad':{'during':1},'facility:':{'http:':1},'shine':{'very':1,'out':1},'faith':{'that':1},'76':{'photo':1,'the':1,'venus':1,'capella':1},'entailed':{'on':1},'prothyl':{'as':1},'warm-bloodedness':{'is':2},'four-footed':{'ancestry':1},'chaps.':{'illustration':1},'silence':{'and':1,'immense':1},'seeing':{'there':1,'it':1},'baboons':{'.':1},'visit':{'to':1,':':1,'http:':1},'within':{'into':1,'60':1,'as':2,'itself':2,'.':1,'their':2,'which':2,'themselves':1,'them':2,'his':1,'reach':1,'five':2,'90':2,'recent':1,'a':7,'about':2,'limits':1,'this':1,'30':1,'bounds':1,'reasonable':1,'the':20,'fixed':1},'libelled':{'as':1},'encircling':{'rampart':1},'one-millionth':{'of':2},'france':{'and':3,'in':3},'smells':{'indeed':1},'theory.':{'the':1,'while':1,'illustration':1},'statistics':{'worked':1},'feelers.':{'illustration':1},'renewal':{'.':1},'sea-snail':{'and':1,'.':1},'transcending':{'the':1,'anything':1},'placing':{'a':1,'the':1},'moseley':{'found':1,'s':1,'some':1},'heritage':{'not':1,'much':1},'spawning':{'none':1,'solution':1,'.':1,'beds':1,'are':1,'method':1},'revolving':{'very':1,'as':1,'electrons':1,'in':1,'round':1,'blades':1},'tortoise-shell':{'butterfly':1},'manufacture':{'and':1,'subtle':1,'much':1,'chlorophyll':1},'himself':{'and':1,'established':1,'educated':1,'the':1,'.':1,'in':1,';':1,'by':1},'registered':{'on':1,'trademark':2},'frost':{'and':1,'acting':1,'but':1},'torch':{'of':1},'shore-crab':{'is':1,'shows':1,'.':1},'properly':{'the':1},'authority':{'on':2,'thinks':1},'newer':{'loess':1},'hares':{'and':1},'dull':{'sheaths':1,'white':3,'red-hot':1,'red':1,'.':1},'zooelogical':{'discoveries':1},'lamp-shells':{'trilobites':1,'molluscs':1},'folk-ways':{'to':1},'drifters':{'the':1,'or':1,'plankton':1},'skull':{'and':6,'represents':1,'from':1,'then':1,'of':2,'is':2,'was':3,'.':3,'discovered':2,'looks':1,'which':1,'the':2,'with':1,'warns':1,'170':1},'circuits':{'as':1},'sifting':{'process':1,'.':1,'to':1,'continue':1,'which':3,'the':2,'by':1,'out':3},'foresight':{'and':1,'to':1,'means':1},'state--':{'radiant':1},'cautiously':{'out':1},'similar':{'palatable':1,'needs':1,'disturbance':1,'inference':1,'adaptations':1,'organisms':1,'sedimentary':1,'performances.':1,'processes':1,'results':1,'forms':2,'to':5,'experiments':1,'statements':1,'in':1,'things.':1,'disorders':1,'pieces':1,'conditions':1,'deposits':1,'stage':1},'non-living':{'sea-dust':1,'world.':1},'adults':{'of':1,'the':1,'like':1},'introducing':{'dust':1,'2':1},'metals':{'afforded':1,'would':1,'began':1,'but':1,'as':1,'were':1,';':1,'seem':1,'the':1},'unwise':{'to':1},'1894':{'in':1},'1895':{'sir':1,'roentgen':1},'1896':{'becquerel':1},'1890':{'that':1},'shown.':{'in':1},'kidney':{'filters':1},'cotton':{'packet':1,'were':1},'ancestors':{'a':1,'belonged.':1,'breathing':1,'on':1,'may':1,'of':5,'.':4,'which':1,'were':2,'during':1},'amounts':{'almost':1,'according':1},'heat.':{'recent':1,'illustration':1,'that':1},'prerogative':{'of':2},'mantises':{'which':1},'dissolved':{'away':2,'in':2,'salts':1,'out':1},'electrical':{'industries':1,'force':1,'installations':1,'nature':1,'influence':1,'energy':2,'phenomena.':1,'phenomena':2,'.':1,'cell':1,'attraction':2,'storm':1},'themselves.':{'illustration':1},'milk-glands':{'of':1},'dashes':{'round':1},'bodies.':{'4':1},'draw':{'water':1,'this':1,'a':1,'back':1},'clean':{'and':1},'calculating':{'boy':2},'crouching':{'bird':1,'lying':1},'potentialities':{'of':1},'triumph':{'that':1},'visits':{'us':1,'another':1},'frances':{'pitt':1},'william':{'king':1,'james':1,'bragg':2,'leche':2,'ramsay':1,'crookes':5},'astronomy.':{'ball':1},'chameleon':{'140':1,'attacked':1,'may':1,'is':2,'.':1,'s':1,'which':1,'in':1,'the':1,'inflated':1,'anolis':1},'does;':{'with':1},'cuttlefish':{'do':1,'or':4,'swimming':1},'structure':{'201':1,'and':3,'or':1,'would':1,'do':1,'far':1,'of':8,'is':1,'between':1,'mainly':1,'.':4,'adaptation':1,'which':1,'in':1,';':1,'has':1,'the':1},'independently':{'established':1,'darting':1},'correlated':{'with':1},'e':{';':1,'vivo':1,'.':9},'practically':{'a':1,'dates':1,'cosmopolitan':1,'anything':1,'certain':2,'extinguished':1,'all':1,'as':1,'every':4,'invisible.':1,'invisible':1,'the':1,'ready-made':1,'illimitable':1},'physics':{'and':2,'is':1,'.':1,'cannot':1,'so':1,'at':1,'has':1,'with':1,'are':1},'portentous':{'furnace':1,'event':1,'mines':1},'required':{'to':2,'five':1,'by':1,'thirty-five':1,'for':3},'resolving':{'to':1,'the':1},'orbit':{'to':1,'of':2,'round':1,'.':1},'utilised':{'to':1,'we':1,'by':1,'directly.':1},'depth':{'of':2,'the':1,'limit':1,'.':1},'night.':{'meteors':1,'higher':1},'utilises':{'the':1},'ignorant':{'of':2},'underrated':{'.':1},'berries':{'and':1},'requires':{'to':2,'the':1,'for':1,'ten':2},'sounded':{'by':1},'evenly':{'together':1},'gr':{'granules.':1},'cheerful':{'and':1},'34800':{'1':1},'go':{'and':1,'into':3,'back':4,'down':2,'through':3,'farther':2,'irresponsibly':1,'in':2,'out':2,'their':1,'up-stream':1,'since':1,'to':4,'too':1,'forward':1,'round.':1,'badly':1,'far':2,'free':1,'hand':1,'they':1,'a':1,'on':8,'fully':1,'straight':1,'up':1,'so':1,'deeply':1,'wrong:':1,'the':1,'round':2},'compact':{'little':2,'readily':1},'birthplace':{'after':1,'where':1,'.':1},'baron':{'cuvier':2},'arid':{'and':1,'summer':1},'suits':{'their':1,'the':1},'task.':{'quick':1},'friendly':{'home':1},'fond':{'of':3},'moribund':{'animalcules':1},'rebounding':{'branch':1},'1796':{'the':1},'miners':{'when':1},'wave':{'would':1,'thunder':1,'of':1,'.':1,'shapes':3,'forms.':1},'board.':{'the':1},'trough':{'to':1,'is':1,'in':1},'more.':{'there':1,'sec':1},'whirlpools':{'.':1,'in':1},'scrapers':{'gravers':1},'stiff':{'when':1,'tail-feathers':1},'positions':{'of':1,'towards':1,'so':1,'.':2},'button':{'at':1},'michael':{'s':1,'hart':1},'hive':{'bees':1},'tree.':{'the':1,'sec':1},'verdict':{'omne':1},'sedentary':{'plants':1,'sea-squirts':1,'sponges':1,'or':1,'types':1},'betelgeux':{'has':1},'deg.-34':{'deg':1},'teeth.':{'adaptations':1,'illustration':1},'dilute':{'substances':1},'booty':{'.':1},'detaches':{'a':1},'gumboil':{'too':1},'picked':{'them':1,'off':1,'it':1,'up':3},'creatures--the':{'first':1},'notwithstanding':{'our':1},'fishermen;':{'without':1},'plays':{'possum.':1,'upon':2,'its':1,'an':2},'paintings':{'on':2},'opaque':{'covering':1,'substances.':1,'substance':1,'with':1,'substances':2},'b-c.':{'older':1},'atoms--different':{'kinds':1},'cell':{'that':1,'to':1,'as':1,'in':2,'the':1,'has':1,'come':1},'prejudicially':{'affected':1},'experiment':{'and':1,'showed':1,'would':1,'that':1,'with':1,'.':4,'will':1,'2':1,'which':1,'in':1,';':1,'has':3,'was':2,'he':1},'poles':{'of':3,'especially':1,'.':1},'rotted':{'into':1},';':{'just':1,'indeed':1,'soon':1,'yet':3,'before':1,'copernicus':1,'interesting':1,'3':3,'to':2,'out-breeding':1,'4':2,'8':1,'his':1,'rational':1,'meanwhile':1,'food':1,'they':25,'not':1,'nor':1,'h':1,'where':1,'round':1,'energy':1,'some':4,'ourselves':1,'out':1,'even':2,'living':1,'what':2,'organisms':1,'its':2,'enough':1,'discovers':1,'7':2,'probably':1,'we':7,'here':1,'water':3,'others':2,'by':5,'on':4,'c':1,'of':2,'larger':1,'or':1,'simple':1,'ca':1,'one':3,'another':2,'mercury':1,'from':1,'there':11,'two':1,'thirdly':1,'2':4,'therefore':1,'6':2,'corresponding':1,'that':12,'ages':1,'but':39,'those':1,'he':3,'sound':1,'b':2,'mc':1,'this':3,'while':1,'r':1,'and':61,'almost':1,'thus':1,'it':51,'an':1,'as':1,'at':1,'in':17,'partly':1,'if':6,'perhaps':4,'foretells':1,'how':1,'5':2,'which':2,'9':1,'though':3,'gradually':1,'most':1,'man':1,'a':7,'lower':1,'short':1,'for':3,'sometimes':2,'so':1,'the':65},'completion':{'assuming':1},'melancholy':{'the':1,'in':1},'cellulose':{'walls':2,'but':2},'filings':{'on':1,'arrange':1},'commercial':{'redistribution.':1},'fifteenth':{'of':1},'arrow-worm':{'and':1},'following':{'short':1,'for':1,'that':1,'this':1,'list':1,'professor':1,'sentence':1,'definite':1,'up':2,':':1,'which':1,'each':1,'the':3,'stages':1},'boot.':{'sec':1},'collar-bone':{'which':1},'canals':{'and':2,'of':1,'running':1,'have':1,'.':2},'water-weeds':{';':1},'convert':{'even':1,'to':1,'nitrogenous':1},'indivisible':{'thing':1,'.':3,'particle':1,'they':1,'in':1},'anvil':{'a':1,'the':1,'could':1,'221':1,'.':1},'haunts':{'and':1,'both':1,'of':5,'there':1,'.':2,'untenable':1,'are':1,'in':1,'the':1,'or':1},'animalcules':{'especially':1,'which':1},'benevolence':{'which':2},'repel':{'one':1},'products':{'the':1},'stars--the':{'shape':1,'nebular':1,'age':1},'hearty--we':{'might':1},'stump-like':{'legs':1},'daybreak':{'and':1},'addresses':{'.':2},'danger':{'home':1,'but':1,'of':1},'foothold':{'and':2,'to':1,'in':2},'limited--there':{'are':1},'wit':{'of':2,'enough':1,'to':1},'vegetation--a':{'very':1},'singing':{'of':1},'cloud':{'and':1,'formations.':1,'of':1,'to':2,'32':1,'not':1,'makes':1,'or':2},'reflector':{'differ':1,'of':1,'.':1,'at':1,'instead':1,'the':1,'has':1},'remains':{'adjusted':1,'bring':1,'as':2,'are':1,'in':1,'unaltered':1,'to':1,'known':1,'that':1,'very':1,'occurred':1,'unfrozen':1,'164':1,'quite':1,'with':1,'man':1,'a':2,'obscure.':1,'of':7,'clear':1,'were':2,'found':4,'the':1,'fixed':1,'stationary':1,'consisted':2},'hydra':{'growing':1,'and':1,'72':1,'a':1,'many':1},'contentment':{'.':1},'crab':{'and':1,'then':1,'gets':1,'on':1,'these':1,'is':3,'continues':1,'soon':1,'to':1,'s':2,'116':1,'has':1,'prefers':1,'must':1},'vehicle':{'and':1,'of':2},'stage':{'and':1,'what':1,'or':1,'fastened':1,'like':2,'of':4,'is':1,'there':1,'.':1,'in':4,';':1,'its':1,'before':1},'depreciate':{'the':1},'started':{'the':1,'his':1,'with':1,'less':1},'becomes':{'a':4,'limited':1,'gradually':1,'feebler':1,'lead':2,'very':1,'radium':2,'hard':1,'uranium':1,'electrified':1,'possible':1,'shorter':1,'much':1,'impure.':1,'radiated':1,'negatively':1,'aware':1,'the':5,'great.':1,'more':4},'visibility':{'are':1,'but':1},'43.4':{'alpha':1},'rivalry':{'of':2},'huxley':{'regarded':1,'1825-95':2,'by':2,'called':1},'sea-floor':{'and':1,'a':1},'crosses':{'a':1,'the':2},'consort':{'with':1},'lapse':{'of':1},'averaged':{'off.':1},'recession':{'of':1},'3--the':{'moon':1},'meet':{'and':1,'exceptional':1,'this':1,'where':1,'their':1,'frequently':1,'the':3,'with':1},'nurture':{'habits':1,'seems':1},'drops':{'of':2,'as':1},'control':{'a':1,'of':2,'over':1,'in':1,'but':1,'.':1,'as':1,'each':1,'the':1},'corpuscular':{'theory':1},'escapes':{'this':1,'attention':1,'from':1,'by':1,'.':1},'escaped':{'and':1},'his':{'chariot':1,'magnetic':1,'actions':1,'hind-legs':1,'polish':1,'throne.':1,'previous':1,'pectoral':1,'limbs':1,'rapid':1,'disposal':1,'beagle':1,'kingdom.':1,'astonishment':1,'world.':1,'grip':1,'plate':1,'big':2,'navigable':1,'wives':1,'famous':1,'breast':1,'facial':1,'vacuum':1,'foot':2,'experiments.':1,'distrust':1,'science':1,'fertility':1,'teeth.':1,'ethical':1,'lowly':2,'infancy':1,'best--':1,'dead':1,'affiliation':1,'cost':1,'living':1,'pedigree':1,'tube':1,'fingers':1,'lowliness':1,'conduct':2,'origin.':1,'achievements':1,'theory':1,'business':1,'dental':1,'behaviour':1,'ancestry':1,'flanks':1,'eye':2,'tortoise':1,'conviction':1,'pursuits.':1,'messages':1,'interesting':1,'or':1,'origin':1,'own':3,'family':1,'bonnet':1,'erect':1,'god-like':2,'refined':1,'greatness.':1,'mental':2,'parentage':1,'fields.':1,'monkey':1,'own.':1,'brute':1,'long':1,'milieu':1,'observations':1,'greatness':1,'right.':1,'telegraph':1,'descent.':1,'head':3,'relationship':1,'bodily':2,'hole':1,'breast-pocket':1,'structure.':1,'encouragement.':1,'work':1,'individual':1,'more':1,'eyes':1,'domesticated':1,'everyday':1,'innings':1,'leisure-time':1,'electro-magnetic':1,'power':2,'faults':1,'reach.':1,'arguments':1,'answer':1,'stock':1,'development':2,'noble':2,'elbows':1,'social':1,'hand':1,'mouse-pupil':1,'mouth':2,'mate':2,'solidarity':1,'attempt':1,'observation':1,'charges':1,'starting':1,'chickens':1,'daily':1,'hypotheses':1,'fundamental':1,'tubes':1,'left':1},'pulling':{'things':1,'the':2},'sought':{'after':1,'out':1},'cave-men':{'of':1,'lived':1,'or':1,'show':1},'herring-gulls':{'lift':1},'embodiment':{'to':1,'or':2,'of':1},'defective':{'you':1,'work':1,'or':2},'digested':{'or':1},'confessed':{'that':2},'andes':{'.':1},'arrangement':{'of':4,'is':1,'there':1,'by':1},'solidifying':{'of':1},'located':{'on':1,'in':1,'at':2,'also':1},'sentiments':{';':1,'in':1},'instinctively':{'a':1,'recognize':1,'as':1,'for':1,'but':1},'re-use':{'it':2},'circular':{'magnetic':1,'orbit':1,'craters':1},'pink':{'mouth':1},'fostered':{'and':1,'not':1},'furiously':{'upon':1},'thunderstorm':{'we':2,'.':1},'trinil':{'in':1},'regrown':{'double.':1,'.':1},'sugar-bird':{'in':1},'free-swimming':{'larval':1,'larvae':1},'1.88':{'4230':1},'gulps':{'.':1},'conspicuousness':{'serves':1},'divided':{'their':1,'the':1,'into':5,'.':1},'immensity':{'of':1,'is':1},'least':{'meant':1,'a':3,'cold':1,'within':1,'600':2,'has':1,'interesting':1,'half':1,'there':1,'twenty':1,'one':1,'as':1,'of':2,'two':1,'in':1,'progress':1,'tremor':1,'.':2,'the':1,'by':1,'inclination':1},'astronomical':{'instruments':1,'society.':2,'instrument':1},'spots--they':{'are':1},'sperm':{'-cell':1},'boils':{'because':1},'primates':{'and':1,'sprang':2,'began':1,'soon':1,'.':1,'emerged':1,'in':1,'was':1},'including':{'climate':1,'shrews':1,'that':1,'some':1,'life':1,'legal':2,'obsolete':1,'checks':1,'but':1,'how':1,'the':5,'river':1,'outdated':1,'any':1},'obelia':{'68':1,'consisting':1},'converting':{'it':1},'facilitates':{'the':1},'brittle':{'spikelet-bearing':1},'avebury':{'s':1},'27-1':{'2':1},'outer':{'layers':1,'and':1,'stream':1,'space':1,'envelope':1,'one-mile':1,'crust':1,'surface':1,'crust.':1,'mile':1,'world':2,'ring':1},'exclusion':{'or':1},'thence':{'to':1},'up-stream':{'as':1},'masses':{'and':2,'of':6,'the':2,'or':1,'a':1},'water-weed':{';':1,'glued':2},'brook':{'of':1},'him':{'and':1,'partly':1,'of':1,'.':2,'how':1,'which':1,'in':1,'with':2},'registration.':{'illustration':1},'pre-dravidians':{'and':1},'master.':{'learning':1},'dead-leaf':{'butterfly':2},'popularly':{'known':1,'supposed':1},'shasta':{'daisy':1},'hills.':{'the':1},'rising':{'and':2,'from':1,'into':1,'sometimes':2,'water':1,'to':1,'in':1},'africa.':{'illustration':2},'stout':{'knitting':1},'hands':{'and':1,'did':1,'.':1,'in':1,'of':1},'front':{'and':3,'of':3,'door':1,'side':1,'.':1},'revealed.':{'even':1,'illustration':1},'masters':{'of':1},'f.e.s.':{'a':5,'diagram':1,'protective':1,'earthworm':1,'when':1,'hermit-crab':1,'hind-leg':1,'glass':1,'green':1,'new':1,'the':5,'trypanosoma':1,'venus':1},'mastery':{'of':5,'by':1,'.':1},'university':{'of':2,'library':3,'10':1},'plate-holder':{'on':1},'magnitude':{'and':2,'of':1,'what':1,'which':1},'mode':{'of':1},'pools':{'and':1,'of':2,'it':1,'dried':1,'which':1,'in':1},'evolution--how':{'it':1},'legions':{'of':1},'upward':{'and':2,'to':1,'at':1},'mare.':{'illustration':1},'map':{'of':2},'globe':{'and':1,'from':1,'like':1,'turns':1,'.':3,'will':1,'to':1,'bounded':1,'which':1,'was':1},'steadied':{'into':1},'mollusc':{'and':1,'s':1,'shells':1},'sands':{'of':2},'measure':{'be':1,'them':1,'for':1,'this':1,'speed':1,'explained':1,'it':1,'.':2,'how':1,'controlling':1,'unveiled':1,'dependent':1,'the':1,'with':1,'climb':1},'separating':{'the':1,'from':1,'positively-electrified':1},'special':{'protective':1,'vertical':1,'danger':1,'rules':1,'study':1,'protection':1,'interest':1,'make-up':1,'skin-leaves':1,'photographic':1,'properties':1},'143':{'protective':1},'ejecting':{'beta':1,'an':1},'vaporisation':{'of':1},'9.--the':{'great':1},'confess':{'to':1},'protoplasm':{'which':1,'flowing':1},'may':{'afterwards':1,'consider':1,'obtain':1,'rest':1,'bring':1,'go':2,'follow':2,'still':2,'find':1,'help':1,'29':2,'charge':1,'choose':1,'save':1,'swim':1,'do':1,'get':1,'read':1,'express':1,'mention':2,'not':4,'tend':1,'fitly':1,'realise':1,'contain':1,'become':3,'mean':1,'traverse':1,'set':1,'we':1,'see':1,'1924':1,'pass':6,'creep':1,'even':1,'by':1,'yet':1,'wriggle':1,'approach':1,'refer':1,'make':3,'be':124,'notice':1,'extend':1,'associate':1,'here':1,'qualify':1,'distinguish':1,'bask':1,'change':1,'convert':1,'keep':1,'credit':1,'place':1,'retain':1,'safely':1,'think':1,'elect':1,'divide':1,'conclude':1,'merely':1,'determine':1,'speak':4,'use':2,'raise':1,'prove':2,'there':2,'add':1,'.':1,'call':1,'therefore':1,'only':1,'form':2,'serve':1,'hear':1,'gain':1,'demand':1,'copy':2,'look':2,'remain':1,'suppose':1,'learn':3,'spawn':1,'give':3,'escape':1,'it':1,'say':3,'at':1,'have':27,'seem':3,'seek':1,'occur':2,'lie':1,'turn':2,'perhaps':1,'travel':1,'also':3,'take':1,'rise':1,'quote':1,'produce':2,'recognise':1,'assume':1,'well':3,'roughly':1,'spend':2},'time.':{'the':2,'illustration':1,'in':1},'pendent':{'whalebone':1},'cause':{'a':3,'and':1,'clouds':1,'of':2,'tiny':1,'chemical':1,'to':1,'the':1,'bodies':1},'achievements':{'of':2,'so':1},'fly.':{'the':1,'illustration':1},'that--':{'first':1},'withering':{'leaves':1,'leaf':1},'completely':{'disappear':1,'invisible.':1,'mysterious':1,'camouflaged.':1,'worked':1,'empty':1},'ancestry':{'of':2,'.':1,'but':1,'in':1},'egg-cocoons':{'in':1},'x':{'indicates':1},'mares':{'brought':1},'spongillidae':{'the':1},'hostile':{'way':1},'determining':{'the':1},'route':{'of':1},'times':{'and':4,'among':1,'smaller':5,'over':1,'it':1,'as':7,'thinner':2,'human':1,'in':3,'still':1,'from':1,'for':2,'whipping':1,'there':1,'when':1,'long':1,'.':2,'cooling':1,'until':1,'more':1,'we':2,'around':1,'that':6,'lizzie':1,'rise':1,'during':1,'emergence':1,'longer':1,'a':3,'faster':1,'of':3,'the':6,'round':1},'counterpart':{'of':1,'in':1},'keen':{'and':2,'a':1,'senses':1,'struggle':2,'are':1},'keel':{'on':1,'which':1,'for':1,'if':1},'apennines':{'have':1},'glories':{'of':1},'sargasso':{'sea.':1,'weed':2},'fertilises':{'these':1,'the':2},'baleen':{'whale':1},'possessing':{'the':1,'with':1},'powerful':{'a':1,'telescopes.':1,'muscles':1,'friar-birds':1,'leg':1,'strokes':1,'legs':1,'tides':1,'factors':1,'possible':1,'agencies':1,'magnet':1,'microscope':1,'current':1,'as':1,'.':1,'than':2,'lens':1},'disembodied':{'electricity':2,'atom':1},'fertilised':{'egg-cell':7,'egg':2,'ovum':2,'by':1},'light-brown':{'colour':1},'lighter.':{'the':1},'proterospongia':{'69':1,'one':1},'activity.':{'this':1},'precisely':{'the':2,'because':1,'controlled':1,'like':1},'quality':{'and':1,'which':2,'that':1,'of':4,'is':1,'.':2,'they':1,'in':1,'than':1},'suck':{'.':1},'long':{'slope':1,'golden':1,'strings':1,'afterwards':1,'weighs':1,'process':2,'series':1,'is':1,'ages':4,'it':2,'as':6,'gristly':1,'summer':1,'result':1,'another':1,'curved':1,'lifetime':1,'racial':1,'tubular':1,'arm':1,'before':3,'story':1,'gamut':1,'pedigree':1,'prehensile':1,'ones':1,'since':3,'.':4,'to':4,'tail':1,'low':1,'way':3,'time':2,'has':1,'red':1,'stilt-like':1,'ago':12,'begin':1,'run':2,'arboreal':1,'history':2,'inclined':1,'after':1,'body':1,'haunt':1,'ovipositor':1,'step':1,'journey':2,'threads':1,'with':1,'day':1,'chapter':1,'on':1,'and':3,'like':1,'stalks':2,'we':1,'the':1,'lizard-like':2,'face':2,'range':1,'branched':1,'period':2,'night.':1,'night':1,'periods':1,'rising':1,'tongue':1,'narrow':1,'summer.':1,'or':1,'pre-human':1,'are':1},'bears':{'very':1,'the':1,'in':2},'dove':{'and':1},'land--the':{'air.':1},'relations':{'and':1,'making':1,'of':1,'with':1,'to':1},'well-formed':{'when':1},'attach':{'to':1},'attack':{'it':1},'fishes.':{'eventually':1,'there':1,'cambrian':1},'declines':{'to':1},'wrapped':{'up':4,'it':1},'perfectly':{'still':1,'aerated':1,'straightforward':1,'circular':1},'final':{'spectrum':1,'.':1,'dispersion':1,'stable':1,'answer':1,'clue':1,'unification.':1},'circulate':{'round':1},'hydrosphere':{'.':1},'2-1':{'2':1},'rays--the':{'alpha':1},'exactly':{'like':1,'where':1,'equal':1,'the':2,'balance':1,'similar':1},'well-finished':{'statuettes':1},'stress':{'on':1},'lists':{'of':1},'feint':{'towards':1},'chemicals':{'which':1},'manipulation':{'of':1,'another':1},'natural':{'process':1,'spectrum':1,'rate':1,'leafy':1,'knowable':1,'size':1,'death':7,'inheritance.':1,'inheritance':2,'question':1,'to':1,'reduction':1,'therefore':1,'size.':1,'conditions':2,'resources':1,'surroundings.':1,'death.':1,'law':1,'death--procession':1,'reflex':1,'history':22},'waist':{'of':1},'photograph':{'a':1,'from':2,'reproduced':1,'of':11,'showing':4,'below.':1,'tied':1,'an':1,'note':1,'255':1,'attaining':1,'are':1,'taken':4,'the':3,'.':1,'shows':3,'clearly':1,'is':2,'fig':1},'glow-worm':{'or':1},'well-established':{'jellyfish':1},'bed':{'of':1},'bee':{';':1,'or':1,'can':1,'.':1},'providing':{'large':1,'access':2,'it':1,'copies':1},'distinguished':{'from':2,'of':1,'astronomers':1,'physicists':1,'solar':1,'anthropologist':1,'man':1},'spurs':{'of':1},'exhibit':{'in':1,'pieces':1},'enforced':{'descent':1},'lightly':{'built':3},'unchanged':{'since':1},'abyssal':{'area':1},'yielding':{'and':1},'p.m':{'.':1},'nototrema':{'there':1},'need':{'and':2,'a':1,'for':3,'be':1,'is':1,'.':1,'not':6,'foundations':1,'hardly':4},'precursors':{'of':4},'screw':{'in':1},'student-citizen':{'otherwise':1},'pursued':{'by':1},'able':{'even':1,'to':36,'with':2,'artificially':1,'in':1},'darkened':{'nest':1},'celandine':{'with':1},'instance':{'a':1,'by':1,'iron':1,'that':3,'of':6,'is':2,'in':4,'when':1,'having':1,'will':1,'how':2,'which':2,'have':1,'were':1,'the':1,'.':1,'was':1,'occurs':1,'to':1,'must':1},'relatives':{'there':1,'some':1,'like':1,'illustrate':1},'rischgitz.':{'professor':1,'baron':1},'pursues':{'a':1,'it':1,'another':1},'blades':{'of':1},'lectures':{'and':1},'moths':{'in':1,'are':1,'that':1},'connected':{'to':2,'story':1,'with':4,'by':1},'last--that':{'is':1},'learnt':{'something':1},'intrinsic':{'racial':1},'gallery':{'there':1},'speed--and':{'must':1},'enregistrations':{'are':1},'radiating':{'away':1,'heat':1,'or':1},'ovum-producer':{'for':1},'upset':{'both':1},'prickle':{'or':1},'astonishing':{'fact':1,'rapidity':1},'prickly':{'fruits':1},'se':{'.':1},'wot':{'isn':1},'impression':{'147':1,'that':1,'of':7,'is':1,'when':1,'illustration':1,'which':1,'on':1,'left':1},'emerging':{';':1,'from':4},'sent':{'on':1,'an':1,'to':1,'through':1,'forth':1,'out':1},'multicellular':{'animals':7},'influences.':{'but':1},'well-being':{'throughout':1},'pigling':{'creeps':1},'graptolites':{'and':1},'slow.':{'illustration':1},'based':{'on':5,'upon':1},'sheriff':{'of':1},'millennia':{'of':1,'in':1},'brighten':{'almost':1},'bases':{'embedded':1},'bud':{'a':1,'by':1},'inherited':{'nature.':1,'from':1},'attained':{'dark':1,'to':3,'a':1,'by':1},'employed':{'and':1,'to':1,'the':1,'in':1},'mortality':{'and':1,'had':1,'hardly':1,'.':1},'seizing':{'and':2,'every':1,'killing':2},'120':{'large':1,'deep-sea':1,'the':1,'flinty':1},'121':{'the':1,'egg':1},'123':{'miles':1},'124':{'photo':1,'woolly':1},'125':{'of':1,'albatross':1,'000':1,'storm':1},'sifting--the':{'groaning':1},'128':{'the':1},'thomson':{'sir':2,'evolution':1,'end':1,'262':1,'this':1,'was':1,'professor':1,'j':1,'regius':1,'as':1,'release':1,'imagined':1,'experimental':1,'darwinism':1},'endless':{'nooks':1,'disturbances':1},'three-hundredth':{'of':1},'gutenberg:':{'1.e.1':1},'processes':{'on':1,'that':1,'of':6,'into':1,'.':1,'to':1,'are':2,'which':1,'such':1},'automatic.':{'upper':1},'gutenberg.org':{'license':1},'trucks':{'.':1},'imperious':{'for':1},'introductions':{'to':1,'like':2,'too--the':1},'she':{'flies':2,'often':1,'soon':1,'at':1,'picked':1,'reached':1,'would':1,'had':2,'handed':1,'does':2,'got':2,'has':1,'was':4,'secures':1,'gave':1,'then':1,'never':1,'very':1,'brushes':1,'flew':1,'wanted':1,'succeeded':1,'presented':1,'did':2,'ever':1,'applies':1},'contain':{'a':1,'wheat':1,'within':1,'electrons':1,'defects':1,'more':2},'amphibia':{'senses':1},'embryonic':{'gill-clefts':1,'food-canal':1,'reptiles':1},'spotted':{'and':1,'leopard':1,'.':1},'multiplying':{'usually':1,'the':2,'by':2,'but':1},'burying':{'them':1},'34.7':{'smaller':1},'cuts':{'both':1,'the':1,'off':2,'it':1},'canine':{'tooth':2,'teeth':1},'inkling':{'of':1,'that':1},'breathe':{'dry':5,'on':1,'depend':1,'oxygen':1},'photosphere--is':{'of':1},'legacy':{'of':4,';':1},'powder':{'to':1,'which':1},'frog-like':{'mouth':1},'humane':{'sentiments':1},'surmised':{'about':1},'unconscious':{'elimination':1,'co-operation':2},'apes--the':{'gorilla':2,'gibbon':1},'southward':{'migration':1},'tend':{'to':15,'toward':1},'state':{'of':23,'visit':1,'applicable':1,'.':3,'to':1,'as':1,'in':1,'growing':1,'such':1,'s':1,'law':1,'the':2},'mind.':{'and':1,'there':1,'other':1,'sec':1,'viii':1,'another':1,'in':1},'carapace':{'of':1,'is':1,'or':1},'allotted':{'to':1},'tens':{'of':2},'neither':{'atmosphere':1,'stores':1,'very':1,'agreement':1,'aspect':1,'in':1},'kidneys':{'are':1,'the':1,'at':2,'.':1},'generations.':{'this':1,'to':1},'comparable':{'on':1,'in':2,'to':4},'attention':{'saving':1,'they':1,'may':1,'of':2,'to':1,'at':1,'decide':1,';':1},'renamed.':{'creating':1},'constituted':{'of':2},'importance':{'and':1,'on':1,'though':1,'becomes':1,'is':1,'were':1,'when':1,'namely':1,'to':1,'as':1,'of':6,'too':1,'in':1,'was':1,'than':1},'hurrying':{'streams':1},'edge-on':{'to':1,'44':1,'notice':1,'of':1},'8.--the':{'sun':1},'efficiency':{'and':1,'of':1,'is':1,'.':1,'in':1},'key':{'to':2,'after':1,'from':1,'opening':1,'.':1},'group':{'and':1,'always':2,'of':6,'only.':1,'the':1,'or':1},'precious':{'and':1,'to':1,'animal':1,'contents':1},'distribution':{'and':1,'underwent':1,'of':6,'.':1,'must':1},'secchi':{'the':1},'hits':{'the':1},'sediments':{'were':1},'limits':{'of':7,'the':1,'in':1,'that':1},'mongol':{'australian':1},'minds':{'of':2,'the':1},'preyed':{'upon':2},'strains':{'of':1,'differing':1,'that':1},'admit':{'a':1,'of':3,'the':1,'that':1,'to':1},'manifestations':{'and':1,'of':1,'in':1},'joy.':{'finally':1},'plankton':{'and':1,'is':1,'as':1,'.':1},'estimation':{'.':1},'torn':{'off':1},'studying.':{'some':1},'886.0':{'29.46':1},'colonisation':{'of':1,'was':1},'habitual':{'surroundings':1,'intelligent':1},'penetrating':{'deeply':1,'consequences':1,'opaque':1},'kin-sympathy':{'and':1},'distinguish':{'the':1,'six':1,'several':1,'different':1},'preparedness':{'until':1},'together.':{'except':1},'sea-cucumber':{'119':1,'it':1},'sense.':{'bibliography':1},'tread':{'of':1},'gregarious.':{'the':1},'addition':{'to':5,'that':1,'it':1,'of':1},'disintegrate':{'much':1,'under':1},'own.':{'the':1,'contents':1,'illustration':1},'cent':{'of':1,'selection':1,'.':3},'immense':{'extent':1,'distance':1,'stretches':1,'darkness':1,'distances':1,'column':1,'void':1,'fossilized':1,'amount':1,'importance':1,'rate':1,'mass':1,'monotony':1,'sea':1,'outbursts':2,'velocity':1,'electrical':1,'accumulation':1,'upward':1},'slowly':{'and':1,'on':1,'about':1,'dying':1,'creeping':1,'into':1,'changed':1,'it':1,'back':1,'down':1,'dissolved':1,'dissolve':1,'changing':1,'worked':1,'.':1,'taking':1},'flinders':{'petrie':1},'dead.':{'illustration':1},'shoulders':{';':1},'senses':{'and':2,'do':1,'recognise':1,'of':4,'.':1,'besides':1,'to':1,'which':1,'in':1,'touch':1,'interpret':1},'diversity':{'and':1,'in':1},'digged':{'and':1},'releasing':{'electrons':1},'four-toed':{'horse':2},'176-177':{'side':1},'expenditure':{'possible.':1},'1769-1832':{'86':1,'one':1},'mail':{'.':1},'mammals--with':{'their':1},'novel':{'and':1,'situation':1,'restlessness.':1,'way':1},'unsegmented':{'worms':1},'domestication':{'illustrate':1},'asexual':{'reproduction':4},'air-tubes':{'blood-channels':1,'takes':1,'or':1},'16.--the':{'moon':1},'chalk':{'cliffs':1},'ten-millionth':{'of':1},'owns':{'a':2},'comets':{'and':2,'is':1,'or':1,'we':1,'.':1},'ago--a':{'few':1},'tide.':{'arctic':1},'inhabits':{'british':2},'surface':{'and':8,'among':1,'often':1,'is':4,'it':1,'an':1,'through':2,'are':1,'in':2,'trailing':1,'millions':1,'from':1,'.':19,'to':3,'does':1,'therefore':1,'which':2,';':2,'was':1,'waters':2,'resembles':1,'but':2,'water':1,'by':4,'must':2,'of':27,'receives':1,'were':1,'the':2,'or':1,'bodies':1,'view':2},'examined':{'to':1,'must':1,'.':1},'lambs':{'and':1,'.':1},'conical':{'projection':1,'teeth':1},'inference--or':{'reason':1},'capture':{'small':1,'and':1,'especially':1,'air.':1},'shooting':{'star':1,'outwards':1,'stars':1,'out':1},'zoophytes':{'corals':1,'and':1},'above.':{'illustration':1},'began':{'on':1,'their':2,'long':1,'.':2,'to':25,'as':1,'in':3,'the':3,'with':2},'views':{'and':1,'we':1,'with':1,'.':1},'parts':{'and':1,'about':1,'to':1,'of':13,'company':1,'was':1,'.':1,'sufficiently':1,'only':1,'take':1,'which':1,'in':2,'ebbs':1,';':1,'save':1,'fluctuate':1,'are':3},'ante-natal':{'life':4,'sleep':1,'period':1,'hood':1},'underground':{'world':2},'party':{'distributing':1},'chlamydosaurus':{'of':1},'tapped':{'supplies':1},'capelle':{'in':1},'experimented':{'on':1,'with':1},'formations.':{'illustration':2},'appearances':{'may':2},'effect':{'and':1,'on':3,'would':1,'may':1,'of':5,'when':1,'.':1,'owing':1,'which':3,'movement':1,'measured':1,'than':1,'before':1},'clouds--some':{'with':1},'compared':{'to':4,'with':8},'surroundings.':{'the':1},'colouring':{'this':1,'remains':1,'the':1,'was':1,'of':1},'prophesied':{'for':1},'fierce':{'and':2,'flood':1},'frequently':{'transfer':1,'spread':1,'recurrent':2,'doubled':1},'destruction':{'of':1,'the':1},'poultry':{'are':2},'scarcely':{'taken':1},'reflection':{'of':1,'.':1},'cliff-loving':{'bird':1},'i':{'am':1,'had':1,'.':4,'came':1,'have':1,'the':1,'was':1,'present':1},'obstacles':{'.':1},'well':{'and':4,'named':1,'says':1,'developed':6,'illustrated':1,'known':2,'as':8,'dried':1,'have':1,'in':2,'shown':1,'able':1,'.':2,'to':1,'be':2,'afford':1,'concealed':1,'suited':3,'alone':1,'advanced':1,'placed':1,'protected':1,'accustomed':1,'mixed':1,'adapted':3},'shell--there':{'is':1},'nebulous':{'matter':2},'rife':{';':1,'in':1},'mccabe':{'a':1,'joseph':1},'years--but':{'in':1},'deadly':{'trypanosome':1},'glowed':{'under':1},'neutralised':{'and':1},'45':{'photo':1},'enormously':{'great':1,'slow':1,'greater':1,'.':2,'high':1,'enlarged':1,'denser':1,'distended.':1,'elongated':3,'increased':1},'increasingly':{'a':1},'accurate':{'analytical':1,'to':1,'measurements':1,'student':1},'mistaken':{'.':1},'leisure-time':{'observations':1},'radium--the':{'discovery':1},'sources':{'of':2},'ermine':{'is':1,'has':1,'mainly':1},'mistakes':{'often':1,'like':1,'that':1},'distant':{'planet':1,'aquatic':1,'star':1,'planets':1,'from':2,'ages':1,'past':1,'shores':1,'blaze':2,'stars':2,'date':1,'world':1},'skill':{'and':1,'.':1,'as':1,'without':1,'they':1,'in':2,'the':1},'jackal':{'and':1},'recapitulated':{'by':1},'grappling':{'and':1,'tentacles':1},'1.f.1':{'.':1},'1.f.6':{'.':1},'ovum':{'and':1,'introducing':1,'from':1,'is':1,'or':1,'with':1,'divides':1},'1.f.4':{'.':1},'density':{'heat':1,'stretching':1,';':1},'deposits':{'of':1,'which':3,'would':1,'were':1},'lured':{'upwards':1},'extends':{'not':2,'from':1,'at':1},'maintaining':{'tax':1},'recapitulates':{'at':1},'size.':{'illustration':1},'warrant':{'for':2},'clouded':{'that':1},'fate':{'of':2,'with':1,'by':1},'disappearance':{'of':2,'as':1},'devised':{'by':1},'utah':{'.':1},'propelled':{'themselves':1},'fats':{'and':1},'262':{'electrons':1,'from':1},'historic':{'interest':1},'267':{'arrangements':1,'disintegration':1},'contingents':{'from':1},'burden':{'and':1},'propeller':{'.':1},'immediately':{'preceding':1,'has':1,'lying':1,'for':1,'.':1},'crusher':{'is':1},'prominent':{'eyebrow':2},'loss':{'of':6,'there':1,'in':1},'fleas':{'and':1},'necessary':{'mathematical':1,'for':1,'that':1,'may':1,'it':1,'.':2,'to':9,'in':1,'apprenticeship':1},'lost':{'and':1,'faunas':1,'is':1,'some':1,'three':2,'races':1,'so':1,'or':1},'sizes':{'of':5,'according':1,'which':1},'ctenophores':{';':1,'or':1},'exhausted':{'by':1,'are':1},'payments':{'and':1,'must':1,'should':1},'lose':{'all':1,'one-millionth':1},'page':{'34.':1,'.':2,'also':1,'are':1,'280':1,'the':1,'92':1,'at':2},'likes':{'to':1},'therein':{'lays':1},'shed':{'germ-cells':1,'in':1,'.':1},'glare':{'of':2,'out':1},'offshore.':{'conditions':1},'arrows':{'tycho':1},'belonged':{'.':1},'phenomena':{'and':1,'then':1,'may':1,'of':3,'studied':1,'near':1,'.':1,'as':1,'cannot':1,'including':1,'are':3,'in':2,'not':1,'mean':1},'library':{'very':1,'of':2,'.':3},'husk':{'.':1},'warmer':{'water':1},'home':{'for':4,'of':1,'university':3,'.':5,'in':5,'anger':1,'was':1,'or':1},'peter':{'perhaps':1,'could':1,'was':1,'which':1},'planetesimal':{'dust':1},'scales':{'and':1,'to':1,'of':1,'shows':1},'before.':{'illustration':1},'projection':{'of':2},'broad':{'flat':1,'massive':1,'way':1,'outlines':2,'fact':2,'saucers':1},'kettle':{'on':2,'over':1,'containing':1},'cabbages':{'such':1},'injects':{'the':1},'appreciative':{'awareness':1},'tadpole':{'becomes':1,'has':1,'with':1,'mouth':1},'fountain':{'of':4},'mutation':{'and':1,'is':1},'demonstrated':{';':1},'limitations':{'are':1,'.':1},'incandescence':{'and':1},'inaccurate':{'or':1},'butterfish':{'or':1},'reaching':{'a':1,'to':1,'the':1,'which':1,'project':1},'millions.':{'the':1},'expansion':{'of':3},'imperfectly':{'known':1,'finished':1,'warm-blooded':1},'instinct':{'and':3,'may':1,'is':2,'by':2,'to':1,'as':1,'cannot':1,'in':1,';':1,'with':1,'professor':1},'stows':{'this':1},'sways':{'from':1},'macpherson.':{'illustration':1},'embryos':{'of':4,'an':1,'that':1},'freedom':{'and':1,'of':3,'understanding':1,'in':1},'interlinked':{'system':1,'in':1},'discovered.':{'primitive':1,'illustration':1},'chance':{'on':1,'as':1,'.':1},'flesh-and-blood':{'natural':1},'dominion':{'astrophysical':1},'tongue':{'a':1,'on':1,'and':1,'of':2,'upon':1,'ending':1,'can':1,'which':2},'liberating':{'the':1,'egg-cells':1},'equally':{'spaced':1,'illumined':1,'well':1,'large':1,'stimulated':1,'important':1,'unwise':1,'by':1},'contending':{'theories':1},'cell-wall':{'of':1},'crossland':{'observed':1},'previously':{'unknown':1,'in':1},'primal':{'mud':1},'washington':{':':1},'due':{'to':28,'as':1},'scharff':{'r':1},'times.':{'there':1,'b-c.':1,'illustration':1,'one':1,'c-f.':1,'the':1},'additions':{'or':1},'properties--ready':{'to':1},'endeavours':{'which':1},'utility':{'the':1,'for':1},'doubtless':{'a':1,'this':1,'discover':1,'as':1,'in':1,'gets':1,'present':1},'mississippi':{'and':1},'additional':{'distance':1,'cost':1,'terms':2,'weight':1,'contact':1},'zoologist':{'in':1,'means':1},'museum':{'and':1,'natural':14,'of':3,'57':1,'after':2,'it':1},'phrases':{'as':1},'associates.':{'in':1},'noticed':{'that':4,'already':1,'in':1,'by':1,'.':1},'night--relieved':{'only':1},'daniell':{'alfred':1},'inner':{'upper':1,'life':3,'aspects':1,'stream':1,'one':1,'aspect':1,'ear':1,'or':1},'cell.':{'this':1},'reiteration':{'of':1},'crushing':{'seeds':1},'north':{'and':1,'europe':3,'from':1,'scandinavia':4,'e.g':1,'when':1,'pole':2,'pacific':1,'an':1,'to':1,'1500':1,'sea':2,'in':1,'227':1,'american':1,'america':4,'or':2},'gluten':{'albumin':1},'make-up':{'which':1},'triangular':{'piece':1},'fountains':{'of':1},'gait':{'is':1,'human':1,'but':1},'gain':{'of':1,'leisure':1,'an':1},'sprinkling':{'of':1},'highest':{'level':1,'of':2,'up':1,'reaches':1,'brilliancy':1,'octave':1,'authorities':1,'line':1,'animals--birds':1},'eat':{'it':1,'in':1},'he':{'replied':1,'discovered':1,'ceased':1,'differs':1,'had':7,'destroyed':1,'belongs':1,'constitutes':1,'has':16,'then':2,'means':1,'produced':1,'did':2,'revolutionised':1,'found':4,'went':1,'traces':1,'reduced':1,'says':3,'often':1,'declines':1,'estimated':1,'thinks':1,'puts':1,'learns':1,'wondered':1,'induces':1,'laid':1,'does':2,'got':3,'shows':1,'measures':1,'chose':1,'reacts':1,'maintains':1,'disappeared':1,'approaches':1,'interposed':1,'asks':1,'poured':1,'could':1,'became':1,'confronted':1,'asked':1,'first':2,'one':1,'likes':1,'cultivated':1,'considers':1,'passes':1,'would':2,'jerks':1,'much':1,'wrapped':1,'was':8,'knows':2,'took':3,'repeatedly':2,'worked':1,'must':1,'plants':1,'made':1,'showed':1,'believes':1,'will':1,'arranges':1,'can':5,'of':1,'plunges':1,'called':2,'and':1,'is':7,'walks':1,'thus':1,'buried':1,'allowed':1,'claimed':1,'tells':1,'said.':1,'drained':1,'began':1,'also':2,'speaks':1,'tapped':1,'concedes':1,'used':1,'may':1,'who':1,'drives':1,'accurately':1,'tries':1,'said':1,'likes--and':1,'so':1,'lays':1,'fitted':1,'once':1},'volplaning':{'of':1,'parachutists':1},'cells':{'and':2,'on':2,'kept':1,'boxed':1,'that':1,'of':4,'showing':1,'no':1,'together':1,'.':5,'marked':1,'but':1,'have':1,'which':2,';':2,'whereas':1,'are':3},'two-spined':{'sticklebacks':1},'exerts':{'a':1},'stories':{'of':1,'if':1},'pumped':{'although':1,'out':1},'eyes.':{'furthermore':1},'piece':{'of':29,'became':1},'display':{'perform':1,'of':3,'.':1,'in':1},'neanderthalensis':{'first':1},'cheek-bones':{'and':1},'universal':{'inevitableness':1,'commodity':1,'freedom':1,'acceptance':1,'or':1,'attraction':1,'carrier':1,'open':1,'ether':3},'penny':{'you':1,'in':3},'climax.':{'the':1},'lobes':{'ps':1,'l':1},'crystals':{'and':1,'of':1,'the':1,'or':1,'in':1},'education':{'and':1,'of':3,'included':1,'she':1},'draco':{'volans':2},'heat--forms':{'of':1},'forest.':{'there':1},'functions':{'of':1,'alike':1,'.':1},'apple-trees':{'of':1},'vibrations.':{'the':1},'offensive':{'persons':1},'vacuole':{'cv':1,'fv':1},'onwards':{'it':1,'.':1},'meteor':{'reached':1,'shattering':1},'chemist':{'use':1,'john':1,'was':1,'but':1},'disposing':{'of':1},'over':{'and':8,'all':3,'fifty':2,'diverse':1,'80':1,'functioning':1,'their':1,'again':5,'space':1,'two':4,'.':1,'to':4,'2':1,'8':1,'200':1,'life':1,'hundreds':1,'five':2,'a':6,'new':1,'100':1,'one':1,'11':1,'31':1,'30':1,'taut':1,'the':23,'800':1,'its':2},'star':{'and':2,'distances':1,'appeared':1,'had':3,'is':4,'corresponds':1,'cluster':1,'as':1,'registers':1,'at':2,'in':2,'sinks':1,'whose':1,'for':2,'perhaps':1,'seems':1,'due':1,'.':6,'to':2,'goes':1,'clusters':1,'which':1,'light-years':1,'means':1,'may':1,'but':1,'it':1,'revealed':1,'crosses':1,'clouds':1,'of':1,'against':1,'near':1,'following':1,'algol':1,'makes':1,'or':2},'scrutinising':{'these':1},'living':{'and':1,'flesh':1,'tissues':1,'mainly':1,'an':1,'at':2,'creatures--the':1,'images':1,'ape':1,'organisms':1,'things':2,'representatives':3,'.':2,'creatures':32,'creature':8,'body':1,'a':1,'we':1,'adaptations':1,'form':1,'fire':1,'in':5,'material':1,'hand':3,'burden':1,'to-day':1,'to-day.':1,'man':1,'plants':1,'on':4,'fossils':1,'for':1,'creatures.':1,'items':1,'microcosm':1,'anthropologists':1,'matter':9,'materials':1,'organism':1},'vega':{'34.7':1},'gradations':{'of':1,'from':1},'stag':{'and':1},'pathways':{'marked':1},'out.':{'if':1},'drainpipes':{'to':1},'dewey':{'that':1},'persistent':{'nevertheless':1,'patience':1,'experiment':1,'death-feigning':1,'grasp':1,'tendency':1},'eighties.':{'it':1},'inset':{'circle':1},'15-20':{'feet':1},'determination':{'to':1},'skimming':{'on':1},'indirectly':{'into':1,'from':1,'the':1,'hastened':1},'disruptive':{'chemical':1},'secondly':{'it':1},'saturating':{'outside':1},'psycho-analyst':{'must':1},'is--but':{'it':1},'mackerel':{'and':1},'better.':{'now':1},'dynamic':{'.':1,'systema':1},'unfurl':{'more':1},'straws':{'he':1,'were':1,'she':1,'.':2},'rampart':{'is':1},'shrinkages':{'which':1},'up.':{'the':1},'whose':{'distance':1,'luminescence':1,'skull':3,'origins':1,'point':1,'fine':1,'warm-bloodedness':1,'stinging':1,'atoms':1,'instrumental':1,'motions':1,'webbed':1,'movements':1,'type':1,'gravitational':1,'mental':1},'gamut':{'between':1},'calculate':{'how':1,'the':1,'your':1,'that':1},'swam':{'close':1,'instinctively':1},'auk':{'were':1},'berridge':{'f.z.s.':8},'bragg':{'247':1,'one':1,'says':1,'that':1},'miall':{'l':1},'presents':{'a':1,'the':1},'fine-grained':{'lithographic':1},'investigation':{'shows':1,'.':1},'vocabulary--he':{'has':1},'teaching':{'very':1},'bird--too':{'far':1},'descendant--the':{'modern':1},'updated':{'editions':1},'hind-limb':{'of':1},'counted.':{'but':1,'in':1},'void':{'the':1,'.':1},'cockchafers':{'are':1},'vase':{'which':1},'thinopus':{'the':1},'smack':{'of':2,'their':1},'asia.':{'man':1},'nourished':{'from':1},'govern':{'what':1},'radio-active':{'substance':1,'substances':3,'.':1,'matter':1,'elements':4,'or':1,'bodies':2},'affect':{'a':2,'our':1,'the':5,'your':1},'vast':{'and':1,'stores':2,'reservoir':1,'disturbances':1,'process':1,'energy':1,'as':1,'numbers':1,'crowd':1,'masses':1,'regions':1,'majority':1,'figures':1,'structures':1,'vegetation':1,'whirlpool':1,'medium':1,'that':2,'new':1,'population':1,'streams':1,'changes':1},'transformed.':{'before':1},'kataleptic':{'state':1},'baking':{'qualities':1},'naturalist':{'louis':1,'of':1},'crops':{'with':1},'conductor--six':{'times':1},'present.':{'the':1},'herbert':{'spencer':1},'indefinitely':{'.':1,'in':1},'danger-signal':{'sounds':1},'1859.':{'heritable':1},'greenish':{'plants':1,'warty':1,'phosphorescence':1},'employees':{'expend':1,'are':1},'breast-bone':{';':1,'has':1,'it':1,'.':1},'clothes':{'it':1},'favoured':{'the':1,'speculation':1},'carnivore':{'by':1},'force':{'and':2,'them':1,'proceed':1,'developed':1,'between':1,'due':1,'but':1,'equal':1,'at':1,'which':1,'of':3,'.':2},'senescence':{'but':1},'concise':{'view':1},'dome-like':{'and':1},'japanese':{'deep-sea':2,'variety':1},'current--the':{'dynamo--magnetism--ether':1},'intelligible.':{'sec':1},'hundredfold':{'in':1},'cactus':{'and':1},'even':{'thinner':1,'learning':1,'ten':2,'less':1,'it':1,'an':1,'as':1,'planetoids':1,'through':1,'at':5,'picked':1,'in':9,'before':1,'cut':1,'wholesome':1,'for':1,'make':1,'when':7,'gases':1,'by':1,'to':4,'then':1,'routine':1,'if':6,'more':6,'picture':1,'his':1,'greater':1,'though':1,'after':1,'suffused':1,'rise':1,'although':1,'suck':1,'with':2,'than':1,'conspicuous':1,'hints':1,'a':8,'on':1,'several':1,'liquid':1,'these':2,'of':4,'proud':1,'against':1,'this':1,'without':1,'vaster':1,'the':17,'calculates':1},'unborn':{'young.':1,'reptile':1,'child':1,'offspring':1,'.':1},'asia':{'and':2,'that':1,'is':1,'africa':1,'.':2,'in':1,'was':1,'minor':1},'liberated':{'and':2,'on':1,'from':3,'eggs':1,'when':1,'were':1},'haze':{'and':1},'rest.':{'illustration':1},'reverently':{'and':1},'dr.':{'schoetensack':1,'cyril':1,'romanes':1},'new':{'corner':1,'ebooks.':1,'knowledge':4,'forms':1,'surroundings':1,'physics--the':1,'world.':1,'associations':1,'views':1,'food':1,'revelations':1,'ones':1,'world':2,'devices.':1,'worlds':1,'corners':1,'freedom.':1,'parasite':1,'possibilities':1,'microscope':1,'habits':2,'view':5,'body':1,'domain':1,'methods':1,'habitat':1,'generation':2,'parasites':1,'individualities':1,'home':1,'ebooks':1,'psychology':1,'habits--experiments':1,'competitions':1,'method':1,'discovery':1,'rhodesian':1,'theory':1,'leg':1,'joy':1,'objects':1,'york':11,'linkage':1,'computers':1,'haunts':1,'kingdoms':1,'72-inch':1,'factor.':1,'kinds':1,'or':1,'departures':10,'one':2,'use':1,'nebulae':1,'area':1,'.':2,'territories':1,'card':1,'interest':1,'suit':1,'shell':1,'clue':1,'zealand.':1,'lives':2,'kind':1,'conception':3,'star.':1,'variations':2,'devices':2,'state--':1,'cards':1,'property':2,'and':2,'permutations':1,'discoveries.':1,'sense':1,'flora.':1,'rays':1,'variety':2,'views--the':1,'feature':1,'inquiry':1,'gateways':1,'doors':1,'development':1,'elements':1,'star':1,'opportunity':1,'zealand':2,'modes':1,'light':2,'departure':2,'element':1,'materials':1,'physics':1},'net':{'detaches':1,'result':1},'ever':{'because':1,'tap':1,'show':1,'within':1,'discover':1,'in':1,'seen':2,'matures':1,'imminent':1,'been':1,'.':2,'take':1,'be':1,'life':1,'lived':1,'devised':1,'thrown':1,'perceived':1,'made':1,'rescued':1,'resolving':1,'rose':1,'passing':1,'arising':1,'could':1,'comes':1,'realised':1},'evolving':{'and':1,'brain':1,'set':1,'system':1,'on':1},'muzzle':{'region':1},'seventh':{'printing':1},'never':{'even':1,'nearer':1,'absent':1,'like':1,'ceases':1,'less':1,'becomes':2,'getting':1,'see':1,'been':1,'germinates':1,'completely':1,'understand':1,'showed':1,'mixing':1,'learned':1,'more':1,'focussed':1,'at':1},'drew':{'this':1,'the':1},'anthropology':{'will':1,'home':1,'and':1,'.':1},'met':{'the':1,'with':2,'by':1,'in':2},'108':{'600':1},'active':{'development':1,'and':1,'life':1,'links':2,'for':1,'cuttles':1,'protozoa':1,'strenuous':1,'cooperative':1,'in':1,'deep-sea':1,'the':1,'swimmers':1,'nor':1},'100':{'tons.':1,'miles':1,'000':9,'after':1},'cardboard':{'and':1,'we':1,'were':1},'interpret':{'as':1,'except':1},'contraction':{'process':1,'of':1,'is':1,'and':1},'dry':{'land':27,'land--the':1,'season':1,'work':1,'air':10,'land.':2,'branch':1,'pasture':1,'ground':3,'was':1,'air--by':1,'after':1},'plates':{'hanging':1,'form':1,'exposed':1},'-reptile':{'embryo':1},'buckled':{'up':1},'rests':{'and':1,'on':2},'light.':{'we':1,'no':1,'all':1,'illustration':1,'it':1,'now':1},'credit':{'of':3,'the':3,'amphibians':1,'card':1,'man':1},'permit':{'of':1,'all':1},'california':{'is':1,'has':1,'.':1},'adopting':{'this':1},'suitable':{'site':1},'fell':{'on':1,'near':2},'eyebrows':{'of':1},'growth.':{'under':1},'mobility':{'very':1},'mail.':{'the':1},'war.':{'the':1,'illustration':1},'peahen':{'stag':1},'god-like':{'intellect':2},'protozoa.':{'the':1},'counts':{'we':1,'rarely':1,'for':1},'lung.':{'it':1},'circumvent':{'the':1},'tertiary':{'strata':1,'times.':1,'era':1},'head-on':{'fashion':1},'is--substitutes':{'for':1},'duck-billed':{'platypus':3},'wingless.':{'it':1},'invaders':{'of':1},'dog-toothed':{'cynodonts':1},'duesseldorf.':{'according':1},'stinging-cells':{'the':1},'overhead':{'at':1,'means':1},'calm':{'and':1,'of':1,'unbroken':1},'cassowary':{'201':1,'its':1},'water-spider':{'argyroneta':1,'the':1,'conquering':1},'right.':{'illustration':1},'type':{'is':1,'reaches':1,'say':1,'have':1,'in':2,'should':1,'relatively':1,'from':1,'for':1,'.':2,'intermediate':1,'rich':1,'has':2,'was':1,'we':1,'but':1,'marked':1,'known':1,'such':1,'with':1,'must':1,'off':1,'like':1,'of':9,'equal':1,'makes':1,'finds':1},'tell':{'all':1,'for':1,'us':6,'at':1,'the':4,'where':1},'gorilla.':{'activity':1},'peeping':{'above':1,'out':1},'lungs':{'a':2,'as':1,'where':1,'but':1,'.':1},'wary':{'trout':1},'oscar':{'riddle':1},'expose':{'the':1},'under':{'a':2,'stones':1,'different':1,'his':1,'her':2,'this':3,'surface':2,'side':1,'water':2,'parts':1,'stimulation--giving':1,'our':2,'the':15,'its':1},'dogma':{'of':1},'warm':{'countries':1,'moist':1,'volcanic':1,'shallows':1},'bipedal':{'dinosaur':1,'progression--always':1,'erect':1},'spawning-pond':{'from':1},'ward':{'f.e.s.':20,'.':1},'latent':{'indefinitely':1,'life':1,'state':1},'flora':{'and':1,';':1,'as':1,'which':1},'room':{'and':1,'we':1,'for':1,'in':1},'civilisations':{'and':1,'of':1},'suggestive':{'fact':2},'guise':{'of':1,'would':1},'root':{'and':2},'humerus':{'or':1},'allantois':{'is':1,'persist':1},'squirting':{'jets':1},'give':{'and':1,'just':1,'certain':1,'modern':1,'it':2,'an':1,'in':1,'out':1,'her':3,'six':1,'definite':1,'to':1,'way':1,'you':1,'more':1,'notice':1,'very':1,'rise':8,'them':1,'such':1,'a':4,'off':2,'prominence':1,'up':2,'us':3,'way.':1,'the':7,'utterance':1},'climax':{'and':1,'among':1,'of':3,'in':5},'involve':{'any':1},'fizzing':{'about':1},'down-stream.':{'1':1},'advancing':{'slope':1,'dog':1,'troop':1},'masterly':{'skill':1,'book':1},'halobatidae':{'wingless':1},'january':{'30':1,'21':1,'22':1,'6':1},'shell-shock':{'is':1},'coral-snakes':{'cobras':1},'faults':{'he':1},'amazing':{'particles':1,'quantities':1},'messrs':{'.':3},'answer':{'even':2,'and':1,'them':1,'forecloses':1,'that':1,'follows':1,'is':7,'back':2,'.':1,'to':4,'first':1,'opens':1,'must':2},'willing--has':{'come':1},'blanket':{'of':2},'minority':{'have':1,'give':1},'undergoing':{'disintegration':2,'disintegration--and':1,'radical':1},'reconciled':{'.':1},'abdomen':{'beneath':1},'food.':{'illustration':1},'long-continued':{'structure':1},'curiosity':{'and':1,'are':1,'its':1},'mud-minnows':{'did':1},'amoeboid':{'cells':4,'line':1},'overtaken':{'.':1},'still;':{'but':1},'descends':{'again':1},'think':{'to':1,'for':1,'that':12,'of':19,'less':1,'.':2,'also':1,'they':2,'clearly':1},'still.':{'and':1},'maintain':{'a':1,'the':1,'that':2},'frequent':{'meals.':1,'paddling':1,'changefulness':1,'occurrence':1,'exhibition':1},'1872':{'charles':1},'carbonic':{'acid':2},'inhabitant':{'of':1},'overtakes':{'it':1},'operations':{'on':1},'fife':{'started':1,'which':1,'in':1},'enter':{'suddenly':1,'our':1,'into':2,'the':2,'deeply':1},'sheltering':{'blanket':1,'is':1},'co-operating':{'with':2},'murray':{'sir':2,'called':1,'.':2},'helena':{'the':1},'hibernation':{'.':1},'down.':{'some':1,'however':1,'illustration':1},'budding':{'or':1,'.':2},'copyright':{'status':1,'royalties':1,'notice':1,'agreement':1,'research':1,'1922':1,'in':2,'holder':4,'or':1,'laws':2},'partisans':{'at':1},'famille':{'lieu':1},'before':{'the':13,'they':5,'it':4,'an':1,'birth.':1,'betraying':1,'our':3,'birds':1,'that.':1,'proceeding':1,'matter':1,'with':1,'there':7,'.':3,'anyone':1,'their':1,'reptiles':1,'you':2,'man':1,'was':1,'we':2,'downloading':1,'reaching':1,'mammals':1,'birth':3,'amphibians':1,'water':1,'heat':1,'them':1,'but':1,'hatching':2,'true':1,'him':1,'he':1,'anything':1,'i':1,'this':1,'she':1,'passing':2,'or':3},'10.5':{'regulus':1},'gyges':{'ring':1},'crew':{'of':1},'better':{'case':1,'by':1,'still;':1,'brains':2,'is':1,'than':1,'forms':1,'to':2,'brain':1,'insertion':2,'teeth':1,'method':1,'or':1,'heel':1},'differently':{'from':1},'persist':{'not':1,'there':1,'when':1},'weeks':{'old':2,'perhaps':1,'removing':1,'when':1,'of':1,'or':1},'overcome':{'the':3,'in':1},'donors':{'in':1},'23.--star':{'cluster':1},'disintegration--and':{'the':1},'swim-bladder':{'of':1,'into':1,'which':1},'combination':{'of':3,'which':1},'within.':{'but':1},'strangest':{'of':1},'caterpillar':{'and':1,'on':1,'.':1},'weaponless':{'animal':1},'indulge':{'for':1},'bluish':{'colour':1},'secured.':{'there':1},'bony':{'fish':3,'collar':1,'flat-fishes':1},'meat':{'and':1,'darted':1},'brightness':{'in':1},'indivisible.':{'the':1},'fogs':{'were':1},'arrested':{'defective':1,'.':1},'proofreading':{'team':2},'mounts':{'guard':3},'went':{'before':1,'on':4,'towards':2,'through':1,'out':1},'meal':{'.':1},'bone':{'and':1,'for':2,'of':1,'u':1,'which':1,'in':1,'the':1,'muscle':1},'mean':{'and':1,'distance':1,'great':1,'save':1,'that':7,'stagnation':1,'one':1,'1':1,'to':1,'so':1,'not':1,'the':1,'.':1,'by':3},'telescope.':{'illustration:':1,'but':1},'afforded':{'the':1,'much':1,'by':3},'problems.':{'sec':1},'successively':{'worked':1},'suspended':{'particles':2,'at':1,'for':1,'in':1},'conifer':{'and':1},'principles':{'employed':1,'of':2},'hive-bees':{'italians':1},'taught':{'to':2,'two':1,'us':1,'that':2},'wave-lengths':{'.':3,'that':1},'first-class':{'sensory':1,'cereal':1},'extract':{'from':1},'conspicuous.':{'at':1},'conjectures':{'which':1},'superposing':{'a':1},'restricted':{'to':2,'that':1,'.':1},'content':{'even':1,'to':2,'ourselves':1,'for':1},'sparkle':{'in':1},'cave-man':{'may':1},'is.':{'energy':1,'let':1},'reader':{'a':1,'who':1,'may':1,'imagines':1,'an':1,'will':1,'to':1},'surprise':{'none':1},'sluggish':{'fishes':1,'turtle':1,'the':1,'animals':1,'creatures':1},'langur':{'monkeys':1},'turning':{'upon':1,'off':1,'the':1,'every':1,'up':1},'meridian.':{'the':1},'hangers-on':{'and':1},'wave-length.':{'deep-red':1},'ascending':{'the':1},'skin.':{'but':1},'246':{'photo':2},'240':{'white':1},'243':{'the':1},'telescopes':{'begins':1,'and':1,'smaller':1,'for':1,'of':2,'.':1,'at':1},'shaggy':{'hair':1},'began.':{'archaeozoic':1,'ordovician':1},'starts':{'as':1,'.':1},'messages':{'from':1,'.':3},'thus':{'diverts':1,'set':1,'just':1,'produces':1,'certain':1,'some':1,'it':4,'separated':1,'as':2,'at':2,'sir':1,'from':2,'appear':1,'securing':2,'no':2,'began':1,'there':5,'uranium':2,'two':1,'been':1,'to':1,'helps':1,'molecules':1,'volvox':1,'we':12,'arises':1,'form':1,'again':1,'becomes':1,'formed':1,'possible':1,'completely':1,'although':1,'fishes':1,'flowers':1,'producing':2,'a':1,'animals':1,'driving':1,'this':1,'professor':2,'shunted':1,'ascertain':1,'the':12,'spiders':1},'isn':{'t':1},'survive--although':{'they':1},'arrived':{'at':3},'cave-lion':{'and':1,'cave-hyaena':1},'loud':{'noises':1},'user':{'provide':1,'to':1,'who':1},'untutored':{'bird':1},'features':{'and':1,'of':3,'there':1,'but':1,'so':1,'which':1,'such':1,';':1},'grade':{'bring':1},'unlit':{'lamp':1},'peculiarity':{'of':1},'disappearing':{'a':1},'enumerate':{'the':1},'radiate':{'away':1,'long':1,'out':1},'immensely':{'large':1,'larger':1,'greater':1,'faster':1},'ditch':{'or':1,'.':1},'hood':{'is':1,'spread':1,'called':1,'or':1},'monotonous':{'world':1,'green':1},'anyone':{'providing':1,'may':1,'.':1,'anywhere':2,'can':2,'in':1,'else':1},'pelagic':{'plants':1,'life':1,'bird':2,'haunt':1,'area':1},'84116':{'801':1},'shiver':{'.':1},'periwinkle':{'or':1},'witnessing':{'the':1},'dwell':{'too':1},'growth':{'and':1,'of':6},'fiery':{'tongues':1,'vapour.':1,'fate':1,'journey':1,'eruptions':1,'outbreak':1},'radiation':{'and':1,'from':2,'of':2,'.':1,'cannot':1,'in':1},'ages--the':{'procession':1},'feathers':{'of':2,'proving':1,'.':1,'are':2,'have':1,'91':1,'the':1,'or':1},'pre-material':{'world':1},'floor.':{'jasper':1},'digs':{'away':1},'glumes':{'or':1},'somewhat':{'like':2,'suddenly':1,'of':1,'as':1,'higher':1,'in':1,'simpler':1,'difficult':2},'feature.':{'some':1},'conger-eels':{'and':1},'brazil.':{'the':1},'peculiar':{'and':1,'people':2,'physiological':1,'characteristics':1,'interest':2,'bones':1,'cases':1,'circumstances':1},'begins':{'on':1,'his':1,'.':1,'to':2,'as':1,'at':1,'in':1},'distance':{'a':1,'and':3,'towards':1,'from':8,'that':1,'of':13,'is':2,'in':2,'thus':1,'period':1,'.':5,'varies':1,'between':1,'it':2,'plays':1,'the':3,'once':1,'was':1,'away':1,'more':1},'creatures.':{'we':1,'the':1,'illustration':2},'dredge':{'has':1},'structures':{'and':5,'reveal':1,'inherited':1,'are':1,'tend':1},'regularised':{'and':1},'sea-serpents':{'terrestrial':1},'preparation':{'for':2},'matter':{'and':16,'chlorophyll':1,'says':1,'exists':1,'is':14,'it':1,'four':1,'as':2,'itself':1,'exist':1,'are':7,'have':3,'in':7,'consists':2,'throughout':1,'ether':2,'254':1,'if':1,'cannot':1,'from':2,'there':2,'.':18,'contained':1,'therefore':1,'which':7,'flowing':1,';':1,'really':1,'was':3,'into':2,'passed':1,'energy':1,'that':4,'may':1,'than':1,'of':10,'however':2,'but':2,'quite':1,'were':2,'cutting':1,'moving':1,'here':1,'itself.':3,'not':1,'end':1,'along':3,'by':1,'a':1,'on':1,':':2,'this':1,'ever':1,'attracts':1,'required':1,'up':1,'agoing.':1,'or':2,'trillions':1,'so':1,'can':1,'contain':1,'through':1,'the':2,'out':1,'reduced':1},'messengers':{'regulate':1,'from':1,'are':1,'which':2,'more':1},'silly':{'ants':1},'shore-waters':{'to':1},'hailstones':{'on':1},'enables':{'the':2,'them':1,'us':3,'it':1},'extracting':{'the':1},'chrysalis':{'probably':1},'recommence':{'when':1},'membranes':{'the':1,'vocal':1},'modern':{'mathematical':1,'researches':1,'mammals':1,'brain...':1,'times.':1,'comparative':1,'times':2,'birds':2,'size':1,'horse':4,'representatives':1,'philosopher':1,'spectroscopist':1,'astronomers':1,'investigation':1,'physicists':1,'instruments':1,'flowering':1,'type':5,'divers':1,'tree-shrews':1,'civilisation--coal':1,'life':1,'theory':2,'brains':1,'line':1,'giant':1,'direct-reading':2,'physicist':1,'binoculars':1,'world':1,'estimate':1,'astronomy':6,'telescopes':1,'man':10,'advance':1,'observatory':1,'language':1,'species.':1,'science':8,'industry':1,'science.':1,'diffraction':1,'british':1,'theories':1,'bird':3,'man.':1,'dynamo':1,'representation':1,'history':1,'physics':1,'view':1},'mind':{'and':3,'among':1,'is':3,'at':1,'in':6,'seemed':1,'from':1,'for':1,'.':12,'which':1,'has':4,'we':4,'205':1,'that':3,'cannot':1,'let':1,'the':2,'a':1,':':1,'of':15,'craves':1,'can':1,'entirely':1,'out':1},'eyes':{'and':4,'the':1,'of':5,'could':1,'.':5,'to':1,'are':3,'become':1,'protrude':1,';':1,'themselves':1,'having':1},'rigorous':{'boundary':1},'seed':{'being':1,'was':1,'for':1},'nervures':{'on':1},'seen':{'among':1,'emerging':1,'sometimes':1,'gripping':1,'just':1,'is':2,'an':1,'as':1,'full':1,'through':1,'at':4,'another':1,'in':15,'shooting':1,'its':1,'even':1,'what':2,'from':1,'for':2,'to':5,'giving':1,'when':2,'.':5,'how':1,'enough':1,'under':1,'energy':1,'we':1,'towards':1,'that':5,'edge-on':2,'but':1,'quite':1,'boys':1,'every':1,'entangled':1,'by':2,'a':1,'on':5,'washing':1,'driving':1,'of':1,'later':1,'making':1,'the':3,'or':1,'are':1},'seem':{'strangely':1,'do':1,'we':1,'for':1,'always':1,'bound':1,'early':1,'to':18,'bad':1,'does':1,'in':1},'grind':{'a':1},'seek':{'to':1,'any':1,'out':1},'tells':{'and':1,'of':2,'its':1,'us':6},'starfish':{'is':1,'sea-lilies':1,'acorn-shell':1,'which':2,'with':1,'called':1,'asterias':2},'point.':{'and':1},'chest':{'and':1,'.':1},'chess':{'with':1},'blotched':{'by':1},'permian':{'light':1,'period':3,'ice':2,'.':1,'reptiles':1,'the':1,'was':1},'established':{'on':1,'all':1,'may':1,'is':1,'between':1,'an':1,'.':2,'in':3,'themselves':1,'one':1,'by':2,'fact':1},'changefulness':{'and':1,'of':2,'rather':1},'vermiform':{'appendix':2},'regular':{'flux':1,'relation':1,'orbit':1,'movement':1},'meaning':{'of':10,'the':2,'.':1,'an':1},'see.':{'as':1,'that':1},'promising.':{'illustration':1},'refractor':{'and':1,'is':3,'measures':1,'the':1,'48':1},'zealand':{'is':1,'which':1},'broadcast':{'in':1},'observation':{'and':1,'on':1,'by':1,'that':1,'.':1,'or':1},'consumed':{'and':1},'deliberate':{'introductions':1},'m':{'and':1,'.':1},'dog':{'scouring':1,'and':4,'shown':1,'turning':1,'that':2,'of':2,'professor':1,'or':2,'as':1,'carrying':1,'at':1,'a':1,'in':1,'van':1,'the':1,'has':3,';':1},'breathes':{'dry':1,'by':1},'definitely':{'formulated':1,'proved':1,'begun':1,'that':2,'free':1,'guiding':1,'the':1},'principle':{'we':1,'of':2,'is':1,'can':1,'which':2,'applies':1,';':1},'molluscs':{'and':1,'.':1,'are':1,'ascidians':1,'in':1},'dover':{'and':1},'planetary':{'system.':1,'families':2,'nucleus':1},'aquatic':{'ancestors':1,'animals':1,'insects':1,'surinam':1,'ancestry':2,'locomotion':2},'rayleigh':{'stated':1},'visitor':{'gave':1},'probe':{'for':1},'skin-wing':{'a':1},'ending':{'in':1},'brilliancy':{'.':1},'attempts':{'to':4,'made':1,'at':1,'have':1},'fungas':{'spots':1},'counteractive':{'measures':1},'creature--far':{'from':1},'ear.':{'illustration':2},'representing':{'nude':1,'one':1},'explain':{'what':1,'presently':1,'for':1,'this':3,'how':1,'the':6,'why':1},'folded':{'in':1},'sugar':{'fats':1,'.':1},'judged':{'as':1,'from':1,'by':1},'above':{'and':1,'distances':1,'all':1,'is':1,'seven':2,'our':1,'scale':1,'shrinkage':1,'six':1,'them':1,'illustration':2,'it':1,'diagram':1,'five':1,'with':1,'boiling-point':1,'sea-level':1,'a':1,'illustration.':1,'these':1,'pictorial':1,'them.':1,'the':12},'compounded':{'of':2,'so':1},'indicus':{'--are':1},'morsel':{'of':1},'chromosphere':{'great':1,'extends':1,'are':1,'.':1},'stop':{'and':1,'vii':1,'when':1,'but':1,'at':1,'the':2},'perceive':{'a':1,'their':1},'coast':{'of':1},'12':{'is':1,'000':2,'what':1},'energy--what':{'a':1,'heat':1},'21.--typical':{'spectra':1},'ignoble':{'creatures':1},'comply':{'with':5,'either':1},'bat':{'the':1,'flying':1,'s':1,'shares':1},'bar':{'of':1,'.':1},'17':{'origin':1,'1905':2},'room--pour':{'molecules':1},'fields':{'.':1},'bay':{'and':1,'of':1},'bag':{'of':1,'containing':1},'microscope':{'behaving':1,'these':1,'which':1},'discs':{'of':1,'that':1,'.':1},'troop':{'of':1,'masked':1},'18':{'photo':1,'solar':1},'fertility':{'and':1,'in':1},'upwards':{'and':3,'of':2,'from':1,'that':1},'ears':{'and':2,'of':2,'.':1},'ethical':{'face':1},'head-brains':{'the':1},'reference':{'to':1,'has':1,'in':1},'testing':{'probing':1,'all':2},'alterations':{'would':1,'in':1},'tag--but':{'larger':1},'zones':{'of':1,'each':1},'decided':{'to':1,'that':1},'interruptions':{'of':1},'subject':{'and':1,'we':1,'of':2,'is':2,'here':1,'to':4,'as':1,'deeply':1},'pebbles':{'gripped':1,'.':1},'voyage':{'found':1,'darwin':1},'said':{'and':1,'is':1,'some':1,'in':1,'what':2,'for':2,'there':2,'long':1,'.':1,'to':9,'enough':1,':':1,'that':19,'but':1,'a':1,'about':1,'like':1,'of':2,'later':1,'so':1,'the':4,'consisted':1},'scrap':{'from':1},'sail':{'or':1,'in':1},'artificial':{'floor':1,'light':2,'fogs':1,'light.':1,'surroundings':1,'item':1,'transmutation':1},'pets':{'of':1},'simplest':{'forms':2,'animals':1,'form':2,'of':2,'possible':1,'multicellular':1,'bacteria':1,'creatures':1},'unsolved.':{'the':1},'sorts':{'and':1,'of':4,'occupations':1,'out':2},'polygamous':{'.':1},'lethargic':{'state':1},'profitable':{'to':3,'movements':1,'habit':2,'one':1},'cleverer':{'mammals':1,'animals':1,'than':1},'venture':{'out':1},'mountain-top-like':{'cusps':1},'physicist':{'and':1,'set':1,'brings':1,'.':1,'to':1,'has':1},'harvard':{'college':4},'386':{'times':1},'cousin':{'to':1},'motto':{'in':1},'suggested':{'genealogical':2,'this':1,'that':6,'however':1,'.':1,'to':1,'at':1,'another':1,'in':2,'by':2},'air--a':{'globule':1},'sperm-producer':{'and':2},'canines':{'and':1},'against':{'a':5,'downward-projecting':1,'branches':1,'her':1,'instability':1,'these':1,'certain':1,'it':1,'evaporation':1,'their':1,'intensities':1,'of':1,'accepting':1,'the':17,'one':2},'feathering':{'of':1},'puffin':{'s':2},'1.--diagrams':{'of':1},'distinction':{'of':1,'has':1,'so':1},'confronted':{'his':1},'simplified.':{'we':1},'fore-leg':{'of':1,'has':1},'appeared':{'suddenly':1,'upon':1,'related':1,'.':2,'to':1,'in':1,'inconceivable':1,'or':1},'repertory':{'of':5},'buries':{'itself':1},'incessant':{'colliding':1,'movement':2},'inquisitive':{'insects':1,'adults':1,'interest':1},'purling':{'brook':1},'lick':{'observatory.':4},'initiative':{';':1,'so':1},'lowly':{'forms':1,'origin.':2},'ether':{'and':11,'because':1,'exists':1,'disturbances':1,'is':2,'surrounding':1,'as':1,'are':1,'carry':1,'if':1,'permeates':1,'what':1,'disturbance':4,'.':8,'2':1,'which':1,'flowing':1,';':3,'has':2,'was':2,'then':1,'may':1,'but':2,'waves':2,'he':1,'by':2,'must':1,'of':2,'carries':1,'light':1,'or':1},'now.':{'the':1},'recognises':{'the':1},'puts':{'a':1,'the':1,'his':1,'forth':1,'it':2},'basis':{'of':5,'for':5,'but':1},'ramifying':{'system':1},'three':{'and':3,'cautions':1,'letters':1,'reasons':1,'arms':2,'feet':2,'in':2,'females':1,'species':1,'centuries':1,'different':1,'or':3,'dimensions':3,'distinct':2,'fingers':1,'to':3,'wonderful':1,'weeks':3,'hundred':3,'conditions':1,'lowest':1,'aspects':1,'complete':1,'inches':2,'thousand':3,'great':4,'atoms':1,'hours':1,'semicircular':1,'pairs':1,'months':2,'times':5,'chief':1,'miles':1,'fundamental':1,'quarter':1,'other':1},'erect':{'posture':1,'after':1,'lines':1,'attitude':2,'the':1,'he':1,'consisted':1},'milieu':{'.':1},'chrysanthemum':{'of':1},'trigger':{'of':4,'is':1,'which':1,'.':1},'interest':{'and':2,':':1,'for':3,'that':2,'of':2,'is':1,'us':1,'.':4,'to':3,'are':1,'in':5,'increasing':1,'was':1,'or':1},'entered':{'our':1,'into':2,'upon':1,'so':1,'on':1},'chaffinch':{'disguise':1},'threw':{'in':1},'light-year':{'is':1},'deeper':{'down':1,'and':1,'waters':1,'hollows':1},'quantities':{'not':1,'of':2,'pour':1,'destined':1},'sunshine':{'then':1,'of':1},'cold--an':{'eternal':1},'meadow-grass':{'before':1},'locations':{'where':1,'.':1},'168':{'profile':1},'164':{'suggested':1,'the':1},'165':{'the':1},'166':{'photo':2},'167':{'photo':1},'160':{'professor':1,'000':1,'tons':1},'161':{'photo':1,'after':1},'encyclopaedia':{'giving':1},'ether.':{'waves':1},'exception':{'and':1,'of':1},'were--the':{'working':1},'tank':{'of':1},'winding':{'in':1},'originate':{'and':1,'is':1},'spontaneously':{'and':1,'become':1,'or':1,'liberated':1,'becomes':1},'horse-power':{'in':1},'near':{'them':1,'that':2,'scarborough':2,'duesseldorf.':1,'victoria':1,'relative':1,'its':1,'shore':1,'at':2,'enough':2,'the':18,'with':1,'heidelberg':3,'as':2},'neat':{'way':1},'aeroplane':{'s':1,'in':1},'balance':{'of':1,';':1,'used':1,'between':1,'.':2},'study':{'and':1,'rabbits':1,'in':1,'of':12,'under':1,'mammals':1,'.':1,'which':1,'leading':1},'twenty-four':{'hours':2},'spawn':{'and':1,'only':1,'in':4,'.':3},'longer.':{'illustrations':1},'seven':{'hours':2,'different':1,'rays':1,'neck':1,'inches':1,'months':1,'two':1,'colours':5,'other':1,'planets':1,'stages':2},'thought.':{'sec':1,'yet':1},'mexico':{'to':1,'by':1},'diaphragm':{'came':1},'is':{'all':4,'evidence':5,'believed':3,'caused':2,'comparatively':2,'four':1,'remarkably':1,'abundant':2,'looking':1,'certainly':5,'inverse':1,'electricity':2,'concerned':2,'young':2,'to':52,'thinnest':1,'preserved':1,'inconspicuous':1,'worth':2,'tethered':1,'worse':1,'outside':1,'very':48,'indubitable':1,'radio-active':1,'vastly':1,'continued':1,'illustrated':1,'asexual':1,'probably':7,'woven':1,'familiarly':1,'smaller':1,'insignificant':1,'overlying--the':1,'past':1,'likely':1,'utter':1,'estimated':1,'situated':2,'shining':1,'even':2,'established':1,'what':7,'necessary.':1,'comparable':1,'beaten':1,'contributed':1,'expressed':1,'liberated':1,'above':1,'shared':2,'falling':1,'ever':1,'melancholy':1,'never':5,'leaping':1,'desired':1,'learnedly':1,'represented':5,'obtained':1,'great':5,'commonly':1,'descended':1,'usually':3,'conveniently':1,'composed':6,'love':1,'suddenly':1,'merely':1,'explained':2,'apt':3,'highly':10,'brought':4,'rarely':2,'from':4,'would':1,'superficially':1,'two':1,'doubt':1,'therefore':1,'taken':1,'unthinkable':1,'lessened':2,'more':23,'rich':1,'started':1,'pursuing':1,'one-sided':1,'suffused':1,'varying':1,'known':11,'given':4,'carried':2,'locked':1,'room':1,'this':6,'moulted':1,'itself':1,'obvious':1,'can':1,'growing':1,'making':2,'stimulating':1,'proof':2,'nearest':2,'bent':1,'pushed':2,'something':2,'wonderful':2,'struck.':1,'huge':1,'rather':4,'divided':1,'breaking':1,'fortunate':1,'1':1,'located':2,'instead':1,'left--to':1,'maternal':1,'intended':1,'inconceivably':1,'derived':2,'movable':1,'disgusted':1,'eighty-eight':1,'coming':1,'such':4,'horizontal':1,'inconceivable':1,'revealed':1,'a':196,'short':1,'natural':3,'effective':1,'yielding':1,'fortunately':1,'so':21,'pulled':4,'secured':1,'justifiable':2,'unpalatable':1,'indeed':1,'mainly':3,'discharging':1,'produced':3,'held':1,'through':3,'committed':1,'still':9,'its':5,'admirably':1,'superior':1,'26':1,'how':2,'susceptible':1,'interesting':14,'actually':1,'better':2,'covered':1,'travelling':2,'admirable':1,'easier':3,'then':4,'popularly':1,'affected':1,'greater':2,'thereby':1,'food':1,'safe':4,'wise':1,'not':79,'now':18,'always':7,'reasonably':1,'tenanted':1,'arrested':1,'establishing':1,'transmitted':1,'reasonable':1,'radial':1,'found':6,'entirely':4,'physiologically':1,'afforded':3,'doing':1,'there':10,'crushing':1,'related':2,'our':3,'beyond':5,'thick':2,'really':4,'living':1,'shown':5,'surrounded':3,'content':1,'contained':1,'denoted':1,'revolving':1,'twenty-five':1,'borne':2,'disputed':2,'built.':1,'incalculable':1,'quite':10,'reason':3,'surely':2,'struggle':2,'intensely':1,'thrown':1,'enormous':1,'organic':1,'keen':2,'disturbed':2,'moving':5,'assuredly':1,'most...':1,'first':1,'complete.':1,'constantly':4,'blown':1,'synonymous':1,'reflected':6,'one':23,'well-known':1,'done':1,'sunlight':1,'another':13,'impossible':8,'immensely':1,'discharged':1,'bitten':1,'little':3,'necessarily':2,'needed':1,'unknown':2,'their':2,'2':1,'too':3,'passed':1,'molecular':1,'vigorous':1,'that':76,'relieved':2,'continuous':2,'wisdom':1,'wasted':2,'prodigious':1,'undoubtedly':2,'flightless':1,'16':1,'divisible':1,'double':1,'enabled':2,'slowed':1,'866':1,'matter':2,'supposed':5,'historical':1,'accessed':1,'and':2,'unrestricted.':1,'gathering':2,'lightly':1,'turned':2,'vitally':1,'unlikely':2,'cleaned':1,'imperfect':2,'obviously':3,'apparently':1,'any':3,'relatively':1,'forced':1,'built':2,'efficient':1,'thoroughly':1,'able':5,'snow':1,'also':18,'trying--the':1,'absorbed':2,'embryological':1,'sure':1,'diminishing':1,'-273':1,'most':5,'connected':1,'printed':1,'nothing':7,'alpha':1,'measured':1,'conspicuous':2,'considered':1,'calculated':1,'sometimes':8,'repeated':1,'dissolved':1,'accounted':1,'normally':1,'lying':1,'precise':1,'particularly':2,'supported':1,'scattered':1,'discovered':2,'scarce':2,'enormously':2,'nearer':1,'founded.':1,'shuffling':1,'with':2,'excessively':1,'enough':6,'unhappy':1,'only':19,'going':7,'touched':1,'molecules':1,'regrowing':2,'adequate':1,'evinced':1,'meant':5,'compounded':2,'exceptional':1,'dependent':1,'familiar':2,'famous':3,'unimportant':1,'123':1,'nearly':1,'closely':5,'drawn':2,'instinctive':2,'dr':1,'justified':1,'beset':1,'evolution':2,'instructive':2,'influenced':1,'common':2,'rung':1,'characteristic':3,'fixed':2,'steam':1,'strengthened':1,'swept':1,'physically':1,'condensed':1,'observed':1,'are':1,'enhanced':1,'tender':1,'close':1,'luminous':1,'forthcoming':1,'best':1,'subject':2,'said':5,'probable':4,'distinctive':1,'missing':1,'continually':1,'written':1,'between':2,'conceptual':2,'progress':2,'neither':1,'available':1,'we':1,'reproduced':1,'nature':2,'tending':1,'however':5,'efficiency':1,'386':1,'suggested':4,'both':1,'essentially':2,'reported':2,'freely':1,'ill':1,'thickly':1,'against':1,'called':21,'sensitive':1,'passing':1,'among':2,'volcanic':1,'simple':1,'acted':1,'maintained':1,'simply':4,'learning':3,'associated':2,'pouring':1,'described':1,'capable':1,'scented':1,'due':5,'.':3,'recognised':1,'hardly':6,'resting':1,'life':2,'partly':5,'sufficient':5,'formed':2,'an':40,'diverted':1,'applied':3,'these':3,'plain':6,'eclipsed':1,'intimately':1,'reflex':1,'64-6221541':1,'flooding':1,'taking':1,'owed':1,'almost':8,'endowed':1,'thus':4,'it':7,'according':1,'helped':1,'good':2,'clinging':1,'in':33,'ready':1,'if':2,'tumbled':1,'perhaps':3,'occupied':1,'limited--there':1,'clearly':1,'solidary':1,'capped':1,'split':2,'finite':1,'difficult':6,'independent':1,'used':7,'wisest':1,'running':2,'arrived':1,'climbing':1,'circumvented':1,'centred':1,'lower':2,'largely':2,'paralysed':1,'humanly':1,'well':10,'magnified':1,'rife':1,'without':1,'the':158,'left':3,'departed':1,'just':5,'less':4,'being':3,'profoundly':1,'disguise':1,'stored':1,'atomic':1,'rocked':1,'behind':1,'useful':1,'renewed':1,'corroborated':1,'possible.':1,'passive':1,'spread':1,'transformed':1,'easy':2,'born':1,'struck':1,'increased':1,'loss':1,'showing':1,'decomposed':1,'possible':15,'marked':2,'advanced':1,'acute':1,'sorting':1,'necessary':7,'like':11,'lost':2,'shaped':1,'cooler':1,'admittedly':1,'62':1,'lapsed':1,'fully':1,'soft':1,'essential':1,'towards':2,'right':1,'often':22,'some':4,'somehow':1,'urgent':1,'added':2,'jupiter':1,'52':1,'perfected':1,'irresistible':1,'provided':1,'gradually':3,'condensed--who':1,'for':4,'unlocked':1,'recorded':1,'critical':1,'masked':2,'conquering':1,'good.':1,'freed':1,'indestructible':2,'peculiarly':2,'continuing':1,'broken':4,'worthy':1,'by':3,'on':6,'about':8,'mingled':3,'anything':1,'getting':1,'of':16,'mutually':1,'steadily':2,'introduced':1,'consequently':1,'swimming':1,'diversely':1,'equally':1,'within':1,'bound':1,'because':2,'lively':1,'primarily':1,'einstein':1,'nowadays':1,'doubtless':2,'seen':18,'indispensable':1,'flying':1,'long':1,'much':12,'infected':1,'low':1,':':4,'considerably':1,'complete':1,'secreted':1,'abundantly':1,'constituted':1,'heat':1,'true':20,'considerable':3,'posted':3,'absent':1,'made':10,'arranged':1,'evident':1,'obscure.':2,'whether':2,'dangerous':1,'placed':3,'converted':1,'emotional':1,'clear':7,'hotter':2,'certain':9,'slowing':1,'general':1,'transfused':2,'as':9,'at':11,'effected':2,'again':1,'raised':1,'inborn':2,'no':60,'unaccustomed':1,'out':1,'poor':1,'white-hot':1,'convincing':1,'ultimately':1,'generated':1,'important':2,'suited':3,'included':1,'aware':1,'promising.':1,'to-day':1,'happening':1,'practically':6,'cohesion':1,'ascertained':1,'implied':1,'time':1,'far':5},'it':{'holds':1,'illustrates':2,'scooped':1,'over':1,'fall':1,'splitting':1,'leads':1,'boils':1,'through':2,'looks':8,'cuts':1,'consists':2,'facilitates':1,'agrees':1,'causes':1,'crashing':1,'sprang':1,'sinks':1,'burns':1,'betokens':1,'furnished':1,'seems':23,'should':3,'forms':4,'to':18,'only':2,'spread':1,'firmly':1,'positively':1,'easy':1,'under':2,'8':1,'hammers':2,'has':82,'might':6,'sent':1,'gave':1,'meant':3,'then':1,'his':1,'wished':1,'goes':3,'listeth':1,'means':7,'contracts':2,'breaks':1,'continues':1,'stop':1,'possible':8,'flew':1,'engulfs':2,'matters':1,'cannot':5,'they':1,'altogether':2,'not':2,'meets.':1,'now':3,'neither':1,'discovered':1,'necessary':1,'went':2,'lies':1,'did':3,'always':2,'fixes':1,'serves':1,'loses':2,'herald':1,'off':1,'expels':1,'turns':1,'found':2,'feeds':2,'works':1,'mean':1,'reveals':1,'often':5,'exists':1,'sends':1,'folds':1,'acquires':1,'back':1,'alive':1,'differs':1,'used':1,'swims':3,'are':1,'picked':1,'reached':2,'collects':1,'out':1,'ascends.':1,'what':1,'probable':1,'for':4,'profit':1,'away':2,'revolves':1,'stops':1,'climbs':1,'misses':1,'does':14,'provides':2,'without':2,'got':1,';':1,'seemed':1,'ever':1,'occurs':4,'shows':2,'be':5,'we':1,'give':2,'led':2,'chose':1,'passes':3,'pours':1,'jumps':1,'works--the':1,'disintegrates':1,'works.':1,'surely':1,'put':1,'refers':1,'emits':1,'change':1,'takes':6,'on':6,'dates':1,'hunts':1,'consisted':1,'limits':1,'rests':1,'could':2,'settles':2,'approaches':1,'against':2,'must':20,'suggests':1,'became':5,'greatly':1,'usually':1,'leaps':1,'makes':2,'finds':1,'comes':4,'being':1,'own':1,'afterwards':1,'weighs':1,'had':17,'into':6,'were.':1,'corresponds':1,'reaches':1,'one':1,'running':1,'skips':1,'casts':1,'likes.':1,'impossible':3,'.':31,'doubtless':1,'utters':1,'rises':3,'from':3,'collides':1,'would':23,'remains':4,'expands':1,'there':1,'chooses':1,'vibrate':1,'by':2,'fully':1,'belongs':1,'appears':3,'recognised':1,'furnishes':2,'tells':1,'grew':1,'hardly':1,'until':1,'perishes':1,'slips':1,'that':3,'becomes':2,'contains':3,'convinces':1,'took':1,'strikes':1,'gently':1,'implied':1,'lives':3,'stiffens':1,'probably':1,'with':2,'than':1,'present':1,'he':1,'begins':1,'save':1,'were':18,'builds':1,'looks.':1,'was':98,'originate':1,'bids':1,'up':3,'promotes':1,'will':20,'exerts':1,'can':19,'applies':1,'about':1,'happened':1,'leaves':1,'breeds':1,'and':12,'buries':1,'changed':1,'go':1,'jettisons':1,'escapes':2,'almost':1,'is':473,'occupies':2,'thus':1,'naturally':1,'or':1,'an':1,'as':7,'at':1,'in':13,'need':4,'follows':4,'made':1,'proceeds':1,'if':1,'gives':2,'again':4,'needs':1,'shuts':1,'thereby':1,'amounts':1,'began':4,'acts':1,'when':3,'aside':1,'intelligently':1,'also':1,'parts':1,'which':1,'brings':1,'you':1,'gets':2,'pecked':1,'pursues':1,'practicable':1,'effected':1,'looked.':1,'wrongly':1,'radiates':1,'may':59,'fails':1,'occurred':1,'develops':1,'grows':2,'uses':1,'thrills':1,'contain':1,'concentrating':1,'died':1,'glow':1,'a':2,'implies':1,'advantageous':1,'records':1,'behaves':1,'clear':2,'sometimes':4,'flow':1,'breathes':1,'obviously':1,'more':1,'points':1,'so':2,'fitted':1,'harks':1,'the':4,'once':2,'requires':1,'possesses':1,'came':2,'repeatedly':1},'iv':{'the':1,'.':3},'ii':{'the':1,'.':3},'clinging':{'to':1},'in':{'limited':2,'all':20,'evidence':1,'skeleton':1,'particular':2,'four':2,'sleep':1,'canes':1,'hunting':1,'reptiles':1,'those':3,'masculine':1,'very':4,'indubitable':1,'duck-ponds':1,'every':5,'asia.':1,'hibernating':1,'monkeys':3,'minute':1,'archaeopteryx':1,'apprehension':1,'succession':2,'relation':1,'sedentary':1,'pterodactyl':1,'revolution':1,'ten':4,'dealing':2,'rivers':2,'cost':1,'nests':1,'what':2,'constitution':1,'nature.':2,'favour':1,'asia':2,'uniform':1,'new':3,'nails':1,'contrast':1,'movement':2,'body':1,'degree':2,'ninety-nine':1,'atoms':1,'water':2,'others':1,'directions':1,'fifteen':2,'great':7,'bygone':1,'northern':2,'healthy':1,'compliance':2,'miniature':1,'amount':2,'action':2,'locomotion':2,'mistake':2,'amphibians;':1,'diameter':14,'egypt':1,'africa':3,'gristly':2,'1907':2,'1900':2,'1901':1,'attendance':2,'from':2,'two':3,'cretaceous':1,'france':3,'comparing':1,'doubt':1,'black':1,'fossiliferous':1,'more':2,'horses':1,'pencil':1,'bodily':1,'glass':1,'warm':2,'virtue':3,'varying':1,'andalusia':1,'keeping':1,'animals':3,'this':48,'facilitating':1,'paragraph':6,'nine':1,'stature':2,'following':1,'making':4,'nurture':1,'control':1,'figure':1,'process':5,'persuading':1,'india':1,'pieces':1,'autumn':1,'orion':2,'times':2,'spite':6,'winter':5,'destroying':1,'six':1,'machine':1,'buns':1,'vital':1,'animal':2,'elephant':1,'ordinary':1,'civilisation':1,'edinburgh':1,'southern':1,'orbits':1,'unawares':1,'mankind':4,'waves':1,'1887':1,'such':8,'response':1,'trinil':1,'man':19,'a':188,'short':3,'natural':2,'outline':1,'so':1,'order':7,'typical':1,'imagining':1,'reproduced':1,'breaking':1,'september':1,'hand.':2,'years':1,'radio-active':3,'pascal':1,'existence':1,'cold':1,'its':36,'apes':1,'interesting':1,'amazing':1,'writing':3,'forms':1,'fig':1,'travelling':1,'admirable':1,'them':3,'good':1,'greater':2,'similar':1,'practice':1,'underneath':1,'overpowering':1,'not':1,'courtship':1,'sea-urchins':1,'respiration.':1,'all.':1,'truth':1,'each':3,'pools':2,'liberating':1,'doing':1,'year':1,'our':16,'operation':1,'1898.':1,'special':1,'canada':1,'living':2,'space':4,'safety':2,'kent':3,'millions':1,'turning':1,'monkeys--activity':1,'others--which':1,'little':1,'reason':1,'fastening':1,'organic':4,'e.g':1,'determining':1,'cosmic':1,'british':1,'behaviour.':1,'motion':1,'turn':4,'length':7,'place':1,'consequence':2,'locating':1,'south':1,'flying':1,'faculty':1,'number':6,'one':14,'dominating':1,'another':11,'precisely':1,'quality':1,'sockets':1,'size':11,'horse':1,'obedience':1,'their':35,'sumatra':1,'intermediate':1,'fiery':1,'reign.':1,'white':1,'store':1,'exploring':1,'that':5,'relieved':1,'kangaroo-like':1,'1918':1,'part':6,'western':1,'conger-eels':1,'1912':2,'1917':1,'kind':3,'accordance':3,'isolation':1,'matter':1,'supposed':1,'gigantic':2,'photosynthesis':1,'and':7,'modern':8,'mind':5,'locations':1,'interruptions':1,'any':19,'domestication':1,'relatively':2,'strength':1,'studying':1,'suddenness':1,'scotland':3,'isolated':1,'moist':1,'perigord':1,'internal':1,'which':43,'forming':2,'green':1,'circles':3,'inky':1,'play':1,'permian':1,'opposite':2,'scotland.':1,'most':15,'nothing':1,'difficulties.':1,'whalebone':1,'professor':1,'perceiving':1,'section':2,'fact':5,'quantity':1,'saying':2,'walking':1,'insects':2,'brief':1,'multicellular':1,'manchester':1,'prodigious':1,'changeful':1,'subtle':1,'thickness':3,'fine':1,'gilded':1,'knowledge':1,'stormy':1,'situations':1,'proportion':2,'considerable':1,'surroundings':1,'flood.':1,'darwin':1,'abeyance.':1,'photographs':1,'his':23,'exceptional':2,'expectation':2,'trees':2,'nearly':1,'words':1,'conjunction':1,'areas':1,'evolution':12,'luminosity':1,'violent':2,'flight.':1,'insectivorous':1,'miles':1,'croatia':1,'common':1,'activity':1,'view':1,'unison':1,'multiplying':1,'reference':1,'habit':1,'electrons--and':1,'intelligence':3,'radium':1,'silurian':1,'relative':1,'1921':5,'migration':1,'andromeda':2,'creating':1,'combustion':1,'ways':1,'opening':1,'birds--intelligence':1,'birds':14,'3':1,'various':4,'crookes':1,'europe':5,'we':1,'terms':4,'august':1,'parental':1,'ignorance':1,'queensland':1,'coma':2,'cities':1,'both':6,'many':26,'connection':8,'whole':1,'experimental':2,'point':1,'simple':1,'sweet':1,'vain':1,'ants':3,'height':1,'concluding':1,'adaptation':3,'scottish':1,'majestic':1,'extinct':1,'ether':5,'adults':1,'considering':2,'late':1,'unusual':1,'java':3,'addition':6,'damp':1,'three':6,'.':1,'tropical':2,'interest':2,'bewildering':1,'empty':1,'life':4,'sufficient':1,'search':1,'amphibians':1,'1864':1,'1869':1,'1868':1,'general':2,'captivity':2,'respiration':1,'plants':1,'sixes':1,'prehistoric':1,'these':10,'britain':4,'air':1,'lesser':1,'formats':1,'wild':3,'picturing':1,'girth':1,'albatros':1,'almost':1,'is':1,'it':7,'bipedal':1,'itself':2,'1895':2,'different':4,'locomotion;':1,'estuaries':1,'several':1,'crevices':1,'higher':1,'development':1,'safe':1,'leopard':1,'cleaning':1,'recent':1,'lower':1,'colour':6,'contact':2,'regulating':1,'biology.':1,'the':800,'chemistry':1,'summer':3,'less':2,'being':4,'ideas':1,'front':3,'shape':1,'hercules':3,'distant':1,'human':5,'succeeding':2,'rapid':3,'gentleness':1,'evolution.':1,'thinking':1,'alternate':1,'wet':1,'showing':2,'sussex':2,'early':2,'vacuum':1,'belgium':1,'cape':1,'hollow':1,'dreams':1,'ponds':1,'backboned':1,'brain-development':1,'lightning':1,'true':1,'either':2,'popular':1,'65':1,'methods':1,'some':52,'choosing':1,'sight':1,'illumination':1,'proper':2,'ourselves':3,'preparing':1,'dense':1,'dimensions':1,'for':2,'broad':1,'normal':1,'fluids':1,'1856':1,'tertiary':1,'cuttlefishes':1,'intimate':1,'miles.':1,'of':1,'agreement':1,'illustration':1,'constructive':1,'broken':2,'by':2,'comparison':3,'about':1,'central':3,'getting':3,'freedom':1,'hot':1,'gentler':1,'despair':1,'ox':1,'vogue':1,'or':1,'swimming':1,'1859.':1,'gearing':1,'fishes':3,'bats':1,'lieu':2,'your':2,'ontario':1,'her':5,'shells':1,'support':1,'sargasso':2,'question':1,'war':1,'north':6,'form':1,'mammals':4,'regard':15,'gait':1,'wireless':1,'1871--a':1,'thickness.':1,'with':1,'themselves':2,'partially':1,'blanketing':1,'places':3,'dordogne':1,'iron-mines':1,'diameter.':1,'laplace':1,'nature':8,'constant':1,'mesozoic':1,'certain':5,'paragraphs':1,'an':21,'as':2,'1894':1,'kind.':1,'1896':1,'work':1,'mutual':1,'inborn':1,'no':2,'overcoming':1,'peace':1,'erecting':1,'reality':1,'other':21,'electrical':2,'themselves.':1,'thickness--a':1,'conclusion':2,'gaining':1,'explaining':1,'star':1,'scrutinising':1,'sal-ammoniac':1,'shore-pools':1,'william':1,'scores':1,'variable':1,'astronomy':2,'structure':5,'building':2,'remote':1,'ancestral':1,'holes':1,'2001':1,'thames':1,'time':4,'fresh':7,'starting':1,'having':5},'unbranched':{'radial':1},'mouse':{'as':1,'is':1,'which':1,'chose':1},'boom':{'of':1},'disappear':{'for':1,'in':1},'if':{'unimpeded':1,'all':5,'it':25,'one':5,'nothing':3,'as':2,'at':1,'in':2,'our':2,'hydrogen':1,'any':5,'no':1,'there':8,'to':1,'going':1,'instead':1,'white':1,'ever':1,'division':1,'we':39,'that':2,'painted':2,'after':1,'every':1,'they':15,'progress':1,'not':1,'an':6,'you':17,'he':1,'a':11,'substances':1,'this':2,'light':1,'asexual':1,'she':3,'the':49},'grown':{'to':1,'now':1},'them--or':{'great':1},'belle':{'vue':1},'make':{'aerial':1,'mental':1,'some':1,'it':11,'society':1,'itself':1,'its':1,'galls':1,'for':4,'no':1,'any':2,'their':1,'new':1,'instinctively':1,'more':2,'to':1,'nothing':1,'themselves':1,'a':11,'up':8,'fewer':1,'mistakes':1,'donations':1,'the':9,'shows':1},'respectively.':{'the':1},'solidary':{'with':1},'concavity':{'.':1},'belly':{'very':1},'mixtures':{'of':1},'vegetable':{'mould':1,'matter':1,'kingdom.':1},'colonies':{'communities':1,'inside':1},'grows':{'hotter':1,'larger.':1,'hotter.':1,'to':1,'broader.':1,'old':1,'until':1,'out':1},'bells':{'drove':1},'evolve':{'such':1,'in':1,'.':1},'dissolution':{'must':1},'differing':{'for':1},'delight':{'in':1},'renaissance':{'of':1},'waterfall':{'is':1,'or':1},'sea-water':{';':1,'with':1,'back':1},'kin':{'by':1,'at':1},'supposing':{'our':1,'the':1,'that':3},'opportunity':{'and':1,'for':2,'of':1,'to':2,'during':1,'was':1},'butter':{'in':1},'bell.':{'copper':1},'changes':{'and':1,'again':1,'from':1,'e.g':1,'very':1,'of':7,'that':2,'.':3,'to':1,'as':1,'are':1,'which':1,'in':9,'occurring':1,'involved':1,'with':1,'wrought':2,'endless':1},'stimuli':{'and':1,'to':1,'from':1},'neptune':{'and':1,'2971.6':1,'quite':1,'s':1,'.':1,'by':1},'sea-anemone-like':{'polyps':2},'skull-cap':{'a':1,'indicates':1,'thigh-bone':1,'157':1},'809':{'north':1},'materials':{'nearer':1,'deeper':1,'for':1,'that':1,'this':1,'of':2,'are':1,'have':1,'such':2,'or':1},'impure.':{'the':1},'qualities':{'not':1,'of':1,'with':2,'sir':1,'.':2},'bootlace':{'and':1},'claims':{'of':1},'801':{'596-1887':1},'800':{'illustrations':1,'trillion':1},'left':{'and':4,'wall':1,'is':1,'it':2,'high':1,'alone':2,'at':1,'in':1,'only':1,'out':1,'isolated':1,'their':1,'behind':3,'his':1,'showing':1,'free':1,'else':1,'not':1,'hand':1,'a':1,'severely':1,'of':1,'having':1,'the':2,'side':1},'just':{'one':1,'as':28,'examined':1,'mentioned':3,'seen':1,'before':1,'detect':1,'two':1,'been':2,'foam-bells':1,'liberated':1,'peeping':1,'means':1,'outlined':1,'said':1,'mentioned.':1,'a':1,'on':1,'like':3,'this':1,'leaving':1,'dealt':1,'the':1},'sentence':{':':1,'set':1,'with':1},'ignorabimus.':{'a':1},'sporting':{'jellyfish':1,'or':1,'stock':1},'presume':{'that':1},'longish':{'hair':1},'fife--a':{'first-class':1},'identify':{'do':1},'salivary':{'juice':1},'fullness':{'freedom':1},'facts':{'and':3,'appear':1,'that':1,'of':2,'is':2,'there':1,'favour':1,'.':2,'to':2,'are':2,'point':1,'suggest':1,'not':1,'with':1,'recall':1},'yes':{'card':1},'yet':{'there':1,'just':1,'it':6,'discovered':1,'as':1,'at':1,'another':1,'in':1,'its':1,'even':1,'again':1,'would':1,'flash':1,'admit':1,'been':1,'to':1,'without':1,'passed':1,'stable':1,'we':2,'greater':1,'that':1,'here':1,'discover':1,'met':1,'they':1,'not':1,'now':1,'the':8,'man':1,'a':2,'steadfastly':1,'this':1,'many':1,'possessed':1,'studied':1,'these':1,'remain':1,'definitely':1,'she':1,'though':1,'found':1,'unborn':1},'infinitely':{'small':1,'long':2,'minute':1},'agile':{'hunters':1,'clever':1},'regarded':{'as':13,'the':2},'royal':{'astronomical':2,'observatory':6,'college':2},'long-lost':{'heir':1},'save':{'them':1,'that':1,'in':1,'it':1,'itself':1,'blood':1,'time':1,'fun':1,'the':1,'its':1,'man':1},'resting-place':{';':1},'ago.':{'when':1,'illustration':2},'nightjar':{'with':1,'.':1},'seventy-five':{'inches':1},'loose-limbed':{'fellow':1},'roadside':{'we':1},'forester':{'or':1},'gyrating':{'with':1},'background':{'and':1,'of':2,'professor':1,'parallax':1,'.':1},'destroy':{'a':1,'energy':1,'all':2},'hibernating':{'mammals':1},'dreamt':{'much':1},'grape-sugar':{'.':1},'dreams':{'mixed':1},'shoulder':{'.':1},'ascent.':{'illustration':1},'post-glacial':{'pleistocene':2},'nude':{'female':1},'autumn.':{'we':1},'manual':{'of':1},'unnecessary':{'display':1},'x-rays.':{'below':1},'admittedly':{'provisional.':1},'signal':{'noli':1,'illustration':1,'for':1},'greenland':{'whale':2},'deal':{'about':1,'of':5,'is':1,'.':1,'in':1,'further':1,'the':1,':':1,'with':8,'more':1},'sound--':{'five':1},'deaf':{'for':1},'somehow':{'condensed;':1,'associated':1,'breaking':1,'been':1,'underneath':1,'connected':1,'or':1},'dead':{'plants':1,'star':4,'stars':1,'forests':1,'cuticle':1,'.':1,'matter':1,'reverently':1,'fishes':1,'world':3,'animals.':1,'herring':1,'or':1,'before':1},'jupiter':{'and':3,'shine':1,'saturn':1,'from':1,'23':1,'is':3,'however':1,'.':2,'s':1,'which':1,'in':1,'the':1,'483.3':1,'as':1},'paragraphs':{'1.e.1':2,'1.e.8':1},'chromosomes':{'represented':1,'nuclear':1,'2':1,'lie':1},'disadvantage--a':{'broiling':1},'shapes':{'of':1,'282':1,'.':1,'in':1,'wave-motions':1},'dense':{'by':1,'waters':1,'forests':1,'or':1,'moisture':1,'region':1,'masses':1},'stations.':{'what':1},'normal':{'development':1,'number':1,'routine':1,'baby':1,'path':1,'condition':1,'circumstances':1},'distrust':{'which':1,'for':1},'nerve-cord.':{'4':1},'flounder':{'is':2},'conquering':{'them':1,'time':1,'the':2,'two':1,'space':1},'scotland.':{'what':1},'bold':{'enough':1},'novelties':{'may':1,'.':1,'or':1,'that':1},'burn':{'itself':1},'34':{'000':1},'translated':{'the':1,'mind.':1,'into':1},'bolt':{'escaped':1,'their':1},'tartan':{';':1},'flinty-shelled':{'radiolarians':1},'invertebrate':{'stocks':1,'animals':1},'bury':{'their':1},'air--by':{'means':1},'skin-twitching':{'muscle':1},'flourished':{'probably':1,'in':1},'conceal':{'.':1},'acceptation':{'of':1},'ribs':{'and':1,'of':1,';':1,'are':1,'.':1},'azure':{'blue':1},'islands':{'and':1,'off':1,'of':1,'but':1,'.':3,'in':1},'plesiosaurs':{'dinosaurs':1},'little-changed':{'descendant':1},'automatically':{'to':1,'adjusts':1},'ores':{'of':1},'nerve':{'to':1,'for':1,'man':1},'thinner':{'and':1,'as':1,'than':3},'for.':{'information':1},'formerly':{'had':1},'intellectual':{'keys':1,'tool':1,'property':2,'adventure':1,'coin':1},'chooses':{'for':1},'down':{'and':7,'into':1,'it':1,'as':1,'sec':1,'at':1,'in':2,'before':1,'even':1,'again':1,'from':2,'their':1,'when':1,'.':4,'to':9,'behind':1,';':2,'more':1,'towards':1,'unless':1,'upon':1,'losing':1,'with':1,'by':4,'a':1,'on':5,'branches':1,'these':1,'of':5,'taking':1,'without':1,'many':1,'the':20},'lies':{'in':1,'safe':1,'.':2,'at':1,'between':1,'the':1},'doctrine':{'of':2},'lieu':{'of':2,'travail':1},'refined':{'methods':1},'crab-apple':{'of':1},'ring-formations':{'on':1},'weathered':{'by':1},'amazingly':{'.':1},'initial':{'picture.':1},'jealousy':{'and':1},'approximate':{'and':1,'way':1},'saucerful':{'.':1},'fraction':{'1':1,'of':3,'about':1},'marten':{'for':1},'form':{'and':2,'accessible':1,'is':2,'some':1,'an':2,'as':1,'including':1,'are':1,'any':1,'what':1,'no':2,'.':5,'molecules':2,'we':2,'that':1,'atoms':1,'water':1,'part':2,'reappears':1,'a':16,'fossils':1,'this':1,'of':20,'centres':1,'the':9,'or':1,'once':1},'pinna':{'a':1},'analyse':{'it':1},'feminine':{'structures':1,'characters':1,'.':1},'powerfully':{'along':1},'snow-caps':{'in':1},'magellanic':{'cloud':1},'minuteness':{'of':2},'221':{'photo':1},'evinced':{'and':1},'manatees':{'and':1},'builds':{'up':1},'understood':{'before.':1,'unless':1,'that':1,'when':1,'to':1,'as':1},'harmony':{'and':2},'attached':{'to':3,'full':1},'bounds':{'of':1,'until':1},'pistil':{'thus':1},'centipede':{'s':1},'bird-dropping':{'perhaps':1,'on':2,'spider':1},'egg-eating':{'african':1},'cosmos':{'more':1},'attaches':{'to':1},'temper':{'rather':1,'the':1,'but':1,'.':1},'fractions':{'showing':1},'strengthening':{'of':1},'sticks':{'to':1},'discovery.':{'certain':1,'2':1},'seeds--and':{'resolving':1},'covers':{'them':1,'the':1},'sticky':{'club':1},'gland':{'of':1,'.':1},'mediocre':{'stock':1},'marking':{'the':1},'profit.':{'illustration':1},'discriminate':{'infallibly':1,'differences':1,'sifting':1,'between':1,'cards':1,'the':1},'x-rays--the':{'discovery':1},'font-de-gaume':{'on':2,'cavern':2},'generally':{'described':1,'burst':1,'correspond':1,'deep':1,'as':1,'accepted':1,'adopted.':1},'handed':{'a':1,'on':1,'over':3},'carnivorous':{'confined':1,'turtles':1},'mediaeval':{'and':1},'delivered':{'up':1},'dies':{'to':1},'felt':{'thought':1,'.':1,'than':1,'that':1},'diet':{'mainly':1,'in':1},'genealogical':{'tree':6},'journey':{';':1,'through':1,'round':1,'.':3},'routine--not':{'that':1},'authorities':{'on':1,'neanderthal':1,'recently':1,'referring':1,'is':1,'there':1,'regard':1,'who':1,'have':1,'the':1,'include':1,'think':1},'died':{'away':1,'when':1,'suffered':1,'.':1},'billion':{'is':1,'the':1},'immemorial':{'and':1,'spawning':1},'happening':{'to':1,'is':1},'potato':{'and':1},'assume':{'different':1,'its':1,'that':1},'blushing':{'but':1},'microcosm':{'only':1},'daily':{'.':1,'paper':1,'mail':1,'i.e':1,'mail.':1,'round':1},'jacket':{'and':1},'gorilla':{'g':1,'inhabiting':2,'.':1,'brain':1,'s':1,'164':1,'the':2,'man':3},'almanac':{'and':1,'.':1},'teeth':{'and':3,'on':2,'that':1,'of':1,'.':5,'obeying':1,'till':1,'without':1,'so':1,'are':3,'which':2,'in':3,'fixed':1},'skull-cap.':{'illustration':1},'restored':{'.':2,'it':1,'by':1},'milt':{'and':1},'managed':{'to':1},'limbless':{'lizard':1,'larva':1},'woodwork':{'knew':1},'relieve':{'the':1},'vestiges':{'have':1},'pierces':{'with':1},'hind-legs':{'and':5,'about':1},'manages':{'to':1},'skin':{'and':5,'able':1,'is':1,'pushed':1,'as':1,'are':1,'when':1,'responds':1,'.':2,'to':1,'was':1,'extended':1,'becomes':1,'during':1,'with':1,'minute':1,'begins':1,'on':1,'of':2,'involved':1,'the':1,'or':1},'leche':{'of':2},'shot':{'out':4,'in':1,'humming-bird':1},'mill':{'in':1,'.':1},'abundant':{'modern':1,'from':1,'material':1,'evidence':1,'flux':1,'near':1,'representation':2,'oxygenation':1},'milk':{'.':2},'resourceful':{'of':1},'retention':{'of':2},'anticipation':{'of':1},'depend':{'on':4},'disorders':{'are':1},'educable':{'and':1,'loquacious':1,'creature':1,'.':1},'pouch':{'and':2,'83':1,'the':1,'on':1},'father':{'secchi':1,'of':1,'sea-horse':1,'s':1,'lumpsucker':1,';':1,'stickleback':1,'was':1,'sea-spider':1},'travel.':{'but':1},'answered':{'that':1},'finally':{'and':1,'we':1,'marquis':1,'becomes':1,'there':1,'it':2,'discover':1,'to':1,'words':1,'resulted':1,'become':1,'the':1},'appendicitis':{'.':1},'reptiles':{'and':7,'appeared':1,'some':1,'are':1,'in':4,'birds':2,'before':2,'suggest':1,'when':1,'.':1,'finding':1,';':1,'burrowing':1,'but':2,'such':2,'with':1,'on':1,'e.g':1,'did':1,'of':1,'the':1,'or':1},'swoop':{'from':1},'marks':{'on':1,'most':1,'with':1,'an':1},'vegetation.':{'the':1,'illustration':1,'they':1},'suffered':{'and':1,'from':1},'must':{'often':1,'give':1,'describe':1,'influence':1,'it':1,'one':1,'recall':1,'exist':1,'at':1,'have':17,'go':1,'still':1,'open':1,'find':1,'use':1,'necessarily':1,'appear':1,'suffice':2,'point':1,'also':4,'live':1,'therefore':1,'include':1,'be':59,'draw':1,'move':1,'return':1,'extend':1,'rise':1,'gradually':1,'however':2,'surely':1,'struggle':1,'recognise':4,'imagine':1,'not':11,'affect':1,'come':1,'comply':2,'look':2,'convert':1,'remember':3,'of':1,'require':1,'leave':1,'admit':3,'always':4,'cease':1,'first':3,'obtain':1,'think':3,'sink':1},'fancied':{'there':1},'abundance':{'of':5,'so':1,'at':1},'mud-turtle':{'or':1},'string':{'of':1,'beads':1},'einstein--the':{'tides--origin':1},'theme.':{'when':1},'soapy':{'water':1,'froth':1,'film':1},'figment':{'of':1},'first-known':{'bird':1},'merit':{'of':1},'word':{'development':1,'obviously':1,'about':1,'now':1,'like':1,'for':1,'pencilled':1,'may':1,'processing':1,'atom.':1,'surface':1,'atoms':1,'specificity':1,'.':1,'s':1,'learn':1,'need':1,'has':1,'history':1},'dim':{'and':1,'luminous':1,'at':1},'banished':{'from':1},'did':{'fly':1,'naturally':1,'great':1,'good':1,'service':1,'this':1,'all':1,'long':1,'it':1,'to':1,'much':1,'exist':1,'at':1,'they':1,'not':14,'.':1,'really':1},'die':{';':1,'after':1,'or':1,'.':2},'cavendish':{'professor':1,'physical':1},'travels':{'from':1,'straight':1,'down':2,'at':3,'in':2,'along':2,'by':2},'item':{'in':1},'excellence':{'and':1,'that':1},'perceptual':{'inference.':1,'inference':5,'influence.':1},'round':{'and':3,'it':7,'at':1,'planets':1,'in':3,'its':2,'rapidly':1,'would':1,'.':1,'which':1,'mars':1,'hers.':1,'them':2,'his':1,'that':2,'each':1,'a':5,'on':2,'about':1,'this':2,'smooth':1,'these':1,'centres':1,'the':38},'attracting':{'other':1,'or':1},'talked':{'of':1},'dealing':{'with':4,'from':1},'radium.':{'the':1},'run':{'to':1,'leap':1,'on':2},'langmuir':{'has':1},'bipeds':{'and':1},'adds':{'to':1},'1910.':{'illustration':1},'heaviest':{'and':1,'uranium':1,'.':1},'favour':{'of':1,'the':2,'in':1},'rub':{'it':1},'international':{'donations':1},'filled':{'with':1},'dwarf':{'a':1},'fibre':{'.':1},'mr':{'.':11},'appetites':{'of':1},'french':{'mathematician':1,'copper':1,'authority':1},'tangent':{'is':1,'.':1},'congestion':{'and':1},'four-chambered':{'mammalian':1},'nooks':{'of':1},'wait':{'for':2},'box':{'and':3,'of':1,'containing':1,'green':1,'.':1},'boy':{'a':1,'or':1},'cranial':{'cavity':2,'walls':1,'capacity':1},'1924':{'the':1,'made':1},'shift':{'of':2,'against':1},'intelligence.':{'illustration':1},'works.':{'sec':1,'1.e.9':1,'professor':1,'-':1},'animals--the':{'most':1,'flying':1},'smoke-like':{'haze':1},'exploitation':{'is':1},'simultaneous':{'discharge':1},'atoms.':{'molecules':1,'illustration':1},'conveniently':{'divided':2},'hither':{'and':2},'adjustable':{'in':1},'elect':{'to':1,'were':1},'merely':{'passes':1,'striking':1,'of':1,'that':1,'approximate':1,'air':1,'as':1,'have':1,'represented':1,'finger-posts':1,'means':1,'the':3},'reef-building':{'coral':2},'everybody':{'knows':1,'.':1},'coaxing':{'he':1},'wealth':{'of':1},'sake':{'of':1,'professor':1,'there':1},'hundred-thousandth':{'part':1},'uncritical':{'generosity':1},'--are':{'related':1},'trilobites.':{'looking':1},'ways.':{'iii':1},'flaunting':{'conspicuousness':1},'100-inch':{'telescope':2,'reflector':1},'phosphorescent--they':{'become':1},'cooperated':{'with':1},'lessened':{';':1,'by':1},'alpines':{'and':1},'fish-eating':{'turtles':1},'sharing':{'project':1},'labyrinth':{'if':1},'malay':{'and':1,'to':1,'islands':1},'rigid':{'during':1},'knowledge--the':{'senses':1},'effort':{'to':2,'good':1,'.':1,'much':1},'robe':{'of':1},'capturing':{'a':2,'the':1},'bushels':{'of':1,';':1},'fly':{'off':4,'for':1,'far':3,'into':2,'spreads':1,'.':1,'which':2,'in':1,'flicking':1,'once':1},'flagellum':{'by':1},'avoiding':{'death':1,'enemies':1},'sum-total':{'of':1},'amarus':{'a':1,'124':1},'reappear':{'perhaps':1,'at':1},'growing':{'on':1,'point':1,'over':1,'moulting':1,'stronger':1,'period':1,'to':1,'under':1,'thicker':1,'out':1},'making':{'a':5,'great':1,'towards':1,'daring':1,'these':1,'of':7,'cache':1,'life':1,'what':1,'it':1,'antagonistic':1,'more':1,'experiments':1,'them':1,'sentences':1,'the':10,'.':1,'intelligent':1,'animate':1,'tentatives--new':1},'thicknesses':{'of':1},'sea-spider':{'carries':1,'or':1},'claim':{'a':1},'portals':{'were':1},'bullhead':{'and':1},'predict':{'the':1},'596-1887':{'email':1},'permutations':{'and':1},'agent':{'or':1,'.':1},'sample':{'sent':1,'david':1},'stroke.':{'illustration':1},'1.f.':{'1.f.1':1},'above--that':{'is':1},'redness':{'.':1},'pages.':{'illustration':1},'rays':{'streamed':1,'visible':1,'see':1,'are':5,'have':1,'in':1,'carry':1,'out':1,'from':2,'their':1,'had':2,'except':2,'.':5,'to':3,'poured':1,'which':1,'was':1,'crookes':1,'passed':1,'that':2,'becomes':1,'emitted':1,'but':1,'263':1,'impinged':1,'carrying':1,'post':1,'must':1,'shoot':1,'diverging':1,'of':4,'as':2,'will':1,'were':2,'at':1,'the':2,'consisted':1},'comb-bearers':{'or':1},'get':{'crumbs':1,'into':3,'mind':1,'an':2,'at':3,'another':1,'in':3,'out':3,'even':1,'little':1,'from':1,'two':1,'much':1,'white':1,'more':1,'good':1,'some':2,'free':1,'correspondingly':1,'plenty':2,'a':8,'both':1,'about':1,'this':1,'the':3,'farther':1},'mongols':{'include':1,'curly-or':1},'till':{'a':1,'we':1,'daybreak':1,'there':1,'all':2,'dawn.':1,'only':1,'the':5,'he':1},'orang-utan':{'a':1,'3':1,'4':1,'232':1,'233':2},'1.e.9':{'.':1},'1.e.8':{'or':2,'.':1},'pure':{'radium':1},'skates':{'and':1},'1.e.5':{'.':1},'1.e.4':{'.':1},'1.e.7':{'and':1,'or':1,'.':1},'1.e.6':{'.':1},'1.e.1':{'through':2,'with':1,'.':1},'1.e.3':{'.':1},'1.e.2':{'.':1},'146':{'the':1,'protective':1},'147':{'cuckoo-spit':1,'photo':2},'144':{'dead-leaf':1,'another':1},'142':{'photo':1,'000':1},'swayed':{'their':1},'140':{'photo':1,'photos':1},'141':{'protective':1},'strokes':{'and':1,'of':2},'max':{'schultze':2},'accessory':{'factors':1},'mankind':{'given':1,'evolution':1,'though':1,'migrations':1,'.':3,'so':1,'at':1,'the':1,'or':1},'gill-plates.':{'illustration':1},'grow':{'down':1,'for':1,'older':1,'it':1,'large':1,'in':1,'out':1},'jellyfish':{'easily':1,'starfish':1,'is':1,'there':1,'it':1,'aurelia':1,'has':1,'with':1},'scrambling':{'on':1},'aimless':{'wandering':1},'neck':{'and':1,'passes':1,'of':1,'.':1,'vertebrae':1,'or':1},'johnson':{'and':2},'duckmole':{'and':2,'or':3},'tale':{'.':1},'idea--of':{'taking':1},'sun--measuring':{'the':1},'rarified':{'form':1},'deposit':{'on':1,'in':1,'their':1},'african':{'representative':1,'mudfish':1,'race':1,'snake':1,'the':1,'ape':1},'basket':{'a':1,'of':1,'euplectella':2,'on':1},'mottlings':{'especially':1},'proposal':{'.':1},'development.':{'continental':1},'shield':{':':1,'.':1},'cathedral':{'would':1,'each':1},'civilisation.':{'pleistocene':1,'before':1},'pointed':{'ear':1,'out':2},'wishing':{'to':1},'entity':{'just':1,'that':1,'.':1,'to':2,'which':2,'providing':1},'stability':{'and':1},'globe-fishes':{'which':1},'rings.':{'illustration':1},'planetesimals':{'into':1,'formed':1,'which':1},'pitch':{'.':1},'differs':{'from':3,'greatly':1},'tropisms':{'a':1,'obligatory':1,'play':1,'.':1},'mind--mind':{'in':1},'rhinoceros':{'had':1,'the':1,'bison':1,'irish':1},'ice-fields':{'of':1,'cleared':1},'police':{'dog':1},'monitor':{'varanus':2},'interesting':{'and':1,'because':1,'saving':1,'give':1,'is':1,'sidelight':1,'questions':1,'in':2,'birds':1,'subject':1,'information':1,'glimpse':1,'ways':1,'point':3,'to':16,'way':2,'living':1,'minor':1,'case':1,'that':1,'gradations':1,'archaic':1,'than':1,'condition':1,'recent':1,'chapter':1,'picture':1,'outcome':1,'consequences':1,'study':2,'work':1,'circumstance':1,'race':1,'greenish':1,'problem':1,'works':1,'discoveries':1,'fact':5},'yorkshire':{'stream':1},'consequential':{'punitive':1},'ours':{'would':1,'does':1,'judged':1,'but':1,'are':1},'main':{'layers':2,'use':1,'force':1,'methods':1,'primate':1,'motive-force':1,'lines':2,'processes--':1,'stem':2,'seat':1,'trends':1,'mass':2,'pg':1,'groups':1,'stems':1,'chapters--the':1,'line':14,'one':1,'types':1,'scientific':1},'captivated':{'the':1},'fire-mist':{'that':1},'sooner':{'or':2},'gregariousness':{'and':1},'begun.':{'splitting':1},'markings':{'and':1,'on':1},'leopards':{'238':1,'trained':1},'killed':{'on':1,'by':1,'in':1},'possess':{'a':2,'what':1,'well-developed':1,'.':1,'in':1,'the':3,'an':1},'stock--common':{'to':1},'obviates':{'any':1},'meets.':{'these':1},'thymus':{'gland':1},'careless':{'statement':1},'rock':{'formations.':1,'to':1,'of':1,'kangaroo':2,'record':5,'whence':1,'many':1,'dove':1,'or':1},'vogue':{'but':1},'sheep-ranches':{'were':1},'eyelid':{'is':1,'used':1,'in':1},'elephants':{'and':1,'what':1,'the':1,'is':1,'.':1},'water-bird':{'such':1},'treacherous':{'internal':1,'ooze':2},'tobogganing':{'on':1},'richly':{'endowed':1},'unlock':{'locks':1},'glaciation':{'had':1},'sifted':{'and':1,'again':1,'.':3,'for':1,'out':1},'telescoped':{'manner':1},'description':{'aeschylus':1,'from':1,'.':1},'canada':{'and':1,'about':1},'emerges':{'the':1,'from':1},'afghans':{'alpines':1},'greeks':{'applied':1,'of':1,'said':1,'thought':1},'interference':{'as':1,'with':1},'miles':{'and':1,'into':1,'deep':2,'an':1,'winding':1,'distant':1,'per':4,'in':13,'odd':1,'out':1,'away.':1,'from':5,'would':1,'away':9,'long':1,'.':9,'to':1,'above':3,';':1,'was':1,'across':1,'though':1,'coloured':1,'driven':1,'satellites':1,'a':17,'wide':1,'getting':1,'of':8,'the':2,'or':1,'at':1},'emerged':{'a':1,'on':1,'about':1,'rich':1,'in':1},'dioxide':{'and':1},'correct':{'path':1,'the':1},'assurance':{'the':1},'behaving':{'to':1},'earlier':{'a':1,'chapter':1,'form':1,'generation':1,'organisation':1,'page':1,'stages':1,'or':1},'telegraphy':{'and':1},'sideways':{'towards':1,'scooping':2},'atomism.':{'an':1},'electrically':{'and':1},'imaginable':{'.':1},'paralysing':{'effect':1},'surface-atoms':{'of':1},'existed.':{'even':1},'sunlight.':{'saturn':1},'cough':{'or':2},'orb':{'on':1},'advance':{'and':1,'towards':1,'of':3,'is':1,'in':2,'has':2},'grist':{'to':1},'derivation':{'from':1},'language':{'and':1,'logos':1,'of':1,'there':1,'to':1,'as':1,':':1},'thing':{'and':1,'we':1,'works':1,'to':3,'may':1,'is':1,'.':2,'did':1,'as':3,'existed.':1,'has':1,'yet':1,'happened':1},'invalidity':{'or':1},'2971.6':{'164.78':1},'alevin':{'encumbered':1},'assuredly':{'much':1},'waited':{'on':1,'in':1},'first':{'and':3,'discovered.':1,'telescope':1,'bird--was':1,'beholding':1,'animals':5,'preparation':1,'crop':1,'dynasty':1,'observed':1,'known':6,'animals--beginnings':2,'view':1,'sight':3,'such':1,'alternative':1,'amphibians.':1,'vital':1,'creatures':1,'terrestrial':1,'living':4,'plants--the':2,'one-toed':1,'organisms':1,'make':1,'there':3,'question':1,'three':2,'.':1,'to':3,'prism':1,'became':1,'reptiles':1,'finger':2,'time':6,'learned':1,'if':1,'was':1,'bird':2,'body':1,'be':2,'men':1,'wheat':1,'that':1,'mammal':1,'becomes':2,'voice--surely':1,'divergence':1,'use':1,'but':1,'step':2,'part':1,'sir':1,'amphibians':2,'atom':1,'fishes':1,'invasion':1,'printing':1,'one':1,'come':1,'bronze':1,'a':2,'great':5,'backboned':1,'impressive':1,'showed':1,'gale':1,'successes':1,'of':2,'books.':1,'formed':1,'discoveries':1,'thought':1,'plants':1,'definitely':1,'place':2,'evolved':1,'error':1,'fishes.':1,'found':1,'the':2,'quarter':1,'called':1,'two':1,'know':1},'dwelling':{'on':1},'americana':{'with':2},'discharges':{'at':1},'miocene':{'and':2,'n':1,'was':1,'or':1,'others':1},'arrhenius':{'svante':1},'amidst':{'the':1},'violet-light':{'waves':1},'specificity':{'which':1},'carry':{'them':1,'his':1,'many':1,'messages':1,'it':2,'us':1,'an':1,'their':2,'out':1},'sounds':{'and':2,'on':1,'become':1,'were':1,'except':1,'two':1,'are':1,'in':1,'such':1,'the':1,'.':1},'fiji':{'.':1},'rome':{'observed':1,'were':1},'discharged':{'by':2,'.':1},'interchange':{'of':2},'little':{'reptile':2,'secure':1,'family':1,'taste':1,'of':1,'is':2,'mud-turtle':1,'colony':2,'primitive':1,'evidence':1,'likely':1,'books':1,'creatures.':1,'in':3,'conical':1,'species':1,'lid':1,'glimpse':1,'books--an':1,'monkey':1,'plankton':1,'detail':1,'chemical':1,'lower':1,'doubt':4,'finger':1,'colony.':1,'units':1,'bubble':1,'over':1,'store':1,'more':1,'plate':1,'ball':1,'garden':1,'fish':1,'that':1,'structure':1,'mammals':1,'wax':1,'use':1,'glass':1,'ferment':1,'resemblance':1,'dull':1,'pool':1,'room':1,'building':1,'about':1,'freshwater':1,'like':1,'grains':1,'uneasy':1,'whether':1,'scraping':1,'patch':1,'green':1,'ten-miles-wide':1,'pockets':2,'pinch':1,'the':1,'piece':2,'book':1},'man--the':{'culmination':1,'fountain':1,'metal':1},'unduly':{'obscure':1},'parallel':{'to':2,'wires':1},'1a':{'fore-limb':1},'plains':{'and':3,'to':1,'were':1},'pockets.':{'in':1},'alfred':{'a':1,'russel':1},'speaking':{'of':2},'mining':{'no':1},'dived':{'and':1,'appropriately.':1,'disappeared':1},'american.':{'professor':1},'continuous':{'and':3,'natural':1,'relationship':1,'since':1,'gradations':1,'.':1,'current':1,'accretion':1,'night':1,'raft':1},'accurately':{'the':1,'measured':1},'crevice':{'of':1},'ridges.':{'illustration':1},'undoubtedly':{'great':1,'radio-active--then':1,'an':1},'splendid':{'failures':2},'11':{'feet':1,'the':1,'magnetism':1},'10':{'what':1,'ft':1,'photo':2,'professor':1,'.':1,'feet':1,'000':3,'uranus':1,'1910.':1},'13':{'is':1,'substitutes':1},'cracks':{'of':1},'15':{'matter':1,'from':1},'14':{'dissipation':1,'photo':1,'the':1,'you':1},'sailing':{'of':1,'round':1},'16':{'rise':1,'minutes':1,'until':1},'19':{'1911':2,'photo':2,'consists':1},'scraping':{'of':1},'coco-palm':{'for':1},'victorian':{'.':1},'protected':{'and':1,'as':1,'e.g':1},'fertilisation':{'may':1,'of':1,'it':1},'centigrade':{'below':1},'were':{'all':3,'shot':1,'being':2,'soon':1,'forests':1,'discovered':1,'introductions':1,'through':1,'handed':1,'jointed-footed':1,'still':2,'birds':1,'waiting':1,'teeming':1,'destroyed':3,'to':1,'microscopic':1,'dead.':1,'employed':1,'hidden':1,'surprised':1,'presently':1,'very':3,'wiser':1,'not':5,'hunted':1,'like':1,'presented':2,'always':2,'porous':1,'intrigued':1,'found':4,'entirely':1,'prompted':1,'somehow':1,'born':1,'sifted':1,'borne':1,'even':1,'established':2,'opened':1,'for':1,'wrought':1,'laid':3,'dominated':1,'probably':4,'neither':1,'involved':3,'fed':1,'free':1,'quite':1,'met':1,'experimenting':1,'imperfectly':1,'represented':1,'atoms':1,'beginning':1,'gained':1,'on':1,'about':1,'feeling':1,'evolved--destined':1,'indivisible':1,'broken':1,'many':2,'substituted':1,'streams':1,'usually':1,'symmetrical':1,'first':2,'composed':1,'raised':2,'afterwards':1,'slipped':1,'suddenly':1,'within':1,'marked':2,'due':1,'brought':2,'done':1,'suspended':1,'often':1,'ichthyosaurs':1,'given':1,'ancient':1,'from':1,'hunters':1,'three':1,'approximately':1,'.':1,'few':1,'much':1,'too':1,'fish-lizards':1,'taken':1,'reptiles':1,'minor':1,'composed.':1,'separated':1,'formed':4,'amphibians':2,'it':1,'overcrowded':1,'trying':1,'true':2,'expounded':1,'electrified':1,'made':6,'these':1,'originally':1,'created':1,'extraordinarily':1,'replaced':3,'evolved':2,'of':4,'prematurely':1,'more':1,'buried':1,'crowning':1,'almost':1,'composed--':1,'an':2,'entombed':1,'as':1,'at':2,'in':5,'bones':1,'sharp':1,'no':1,'breaking':1,'able':4,'continually':1,'eagerly':1,'also':4,'prospecting':1,'accumulating':1,'several':1,'rediscovered':1,'gaining':1,'living':2,'immersed':1,'after':1,'most':1,'connected':1,'rejected':1,'eaten':1,'fishes':2,'such':1,'twenty-nine':1,'a':2,'succeeded':1,'largely':1,'later':1,'magnified':1,'so':3,'the':11,'left':3,'once':3},'gigantic':{'flywheel':1,'eye':1,'streamers':1,'orbits.':1,'sun':1,'orbits':1,'.':1,'magnet':1,'glowing':1,'shreds':1,'bubbles':1,'intellect':1,'as':1,'size':2},'proofread':{'public':1},'1.':{'illustration':1},'awns':{'or':1},'coconut':{'palm':1,'from':1},'conjectural':{'.':1},'mundane':{'goal':1},'occupies':{'only':1,'more':2,'an':1},'lice':{'have':1},'entombed':{'in':1},'kurtus':{'carries':1},'metcalf':{'outline':1},'spectacle':{'again':1,'197':1,'is':1},'occupied':{'the':1,'by':2},'euclid':{'or':1},'hitherto':{'known':1,'unknown':1,'shut':1,'we':1,'the':1},'intruder.':{'when':1},'bavaria':{'and':1},'efficient':{'to':1,'answers':1,'they':1},'isolate':{'it':1},'potential':{'energy':3,'.':1},'interior':{'of':4,'is':1,'yet':1,'energy':1,'periodically':1},'performance':{'of':1,'was':1,'hundreds':1},'inveterate':{'enemies':1},'volplanes':{'in':1},'jungle':{'fowl':1,'of':1,'ends':1,'folk':1,'tribes':1},'201':{'photo':2},'200':{'well-marked':1,'cassowary':1},'203':{'jackdaw':1},'202':{'a':1,'the':1},'205':{'a':1},'norman':{'lockyer':2,'inorganic':1},'trace':{'of':5,'the':1,'some':1,'any':1},'206':{'.':1},'arguing':{'whether':1},'208':{'photo':1,'from':1},'correlation':{'of':1},'paid':{'a':1,'for':3,'within':1,'toll':1,'the':1,'by':1},'blackest':{'ignorance':1},'beta':{'and':2,'rays':3,'electrons':1},'sheets':{'of':1},'tract':{'of':2},'contrasts':{'as':1,'in':1,'between':1},'conspicuous':{'and':3,'on':1,'is':1,'material':1,'canines':1,'against':1,'60':1,'black':1,'during':1},'especially':{'among':1,'from':1,'for':1,'prominent.':1,'on':1,'of':1,'when':3,'as':1,'commercial':1,'in':4,'those':2,'look':1},'surprising':{'power':1,'that':2,'when':1,'as':1,'effects':1,'fact':1},'fills':{'the':1},'bustard':{'the':1},'hedgehog':{'mole':1},'alone.':{'the':1},'precise':{'origin':1,'needs':1,'unless':1,'scientific':1,'form-resemblance':1,'object':1,'mechanism':1,'anthropology':1,'time':1,'studies':1,'answers.':1,'vision':1},'grouselike':{'above':1},'show':{'intelligence':1,'evidence':1,'even':1,'gill-clefts--':1,'what':2,'no':2,'interesting':1,'definite':1,'.':1,'to':1,';':1,'that':9,'notable':1,'how':2,'not':1,'man':1,'a':4,'on':1,'great':2,'this':1,'arrested':1,'us':1,'face':1,'without':1,'artistic':1,'teeth':1,'the':6},'gill-cover.':{'the':1},'forbidding':{'by':1},'drawings':{'and':1,'over':1,'by':2},'uranus':{'and':1,'neptune':1,'is':1,'1781.9':1,'.':1},'saying':{'nothing':2,'.':1,'merely':1,':':2,'that':4},'threshold':{'of':1},'corner':{'and':1,'of':5,'near':1,'at':1},'gaseous.':{'now':1},'directions--an':{'alternating':1},'fend':{'for':1},'stormy':{'weather':1},'plume':{'or':1},'treasure':{'at':1},'storms':{'on':1,'.':1,'to':1,'manifest':1},'enough':{'even':1,'has':2,'for':2,'of':2,'when':1,'however':1,'.':1,'to':17,'in':1,'the':1,'air':1},'either':{'case':1,'solitary':1,'of':2,'packet':1,'plants':1,'in':1,'the':1,'with':1,'before':1},'black':{'and':2,'body':1,'quills':1,'tip':1,'spots':2,'.':2,'surroundings':1,'stuff':2,'marks':1,'tips':1,'patch':1,'or':1},'germs':{'of':1},'down-rushing':{'water':1},'pegged':{'down':1},'abeyance.':{'disappearance':1},'awareness':{'and':2,'of':2,'.':1},'single-chambered':{'shell':1},'bittern':{'and':2,'begin':2,'is':1},'contracts':{'and':1,'under':1},'persisting':{'in':1},'midriff':{'or':1},'unimportant':{'and':1,'elements':1,'bladder':1},'nearly':{'a':2,'all':5,'every':1,'thirty':1,'everything':1,'twenty':1,'three':1,'related':2,'up':1,'twice':1,'so':3,'4':1,'9':1,'186':1,'the':2,'any':1,'two':1},'distinctly':{'later':1},'conjunction':{'with':1},'secondary':{'bodies':1},'pollen-nucleus':{'of':1},'bearings':{'cannot':1},'median':{'section':2},'yield':{'us':1},'morning':{'and':1,'coat':1,'especially':1,'to':1},'stupid':{'as':1,'bird':1},'photographically':{'reduced':1},'kernel':{'of':1,'is':1,'divides':1},'declared':{'that':1},'milling':{'and':1},'seas':{'and':2,'many':1,'had':1,'.':1,'to':1,'became':1,'are':1,'were':1,'went':1,':':1,'phosphorescent':1},'seat':{'of':4},'relative':{'distances':2,'sizes':2,'peace':1,'to':1,'absence':1,'in':1,'fixity':1,'shortness':1,'beginning':1},'j.':{'thomson':2},'mud-nests':{'or':1},'mcgregor.':{'profile':2,'a':1,'photograph':1,'sand-pit':1,'piltdown':3,'restoration':1,'the':3},'unaltered':{'.':1},'sameness':{'and':1},'permeates':{'all':1},'steadfast':{'sign':1},'eoliths':{'.':1},'habits--experiments':{'in':1},'behind':{'and':1,'both':1,'them':1,'it--a':2,'it':2,'us':1,'.':2,'while':1,'the':5},'chimpanzees':{'photos':1,'233':1,'but':1,'in':1},'radiated':{'away':2,'by':1,'in':1},'accustomed':{'to':2},'reading':{'of':1,'the':1,'ourselves':1,'anything':1,'or':1},'across':{'a':3,'space':3,'it':2,'the':11,'its':1,'empty':1},'roentgen':{'discovered':2,'s':1},'deletions':{'to':1},'august':{'1922':1,'1924':1},'parent':{'on':1,'of':5,'colony':1,'s':2,'has':1,'until':1},'parental':{'care.':1,'call':1,'care':17},'ascribed':{'the':1},'sea.':{'the':3,'2':2,'conquest':1,'proterozoic':1,'land':1},'tree-lizards':{'tree-kangaroos':1},'killing':{'and':2,'out':1},'dates':{'we':1,'from':3,'except':1,'varying':1},'vaporous':{'matter':1},'feelers':{'whereas':1},'diameter.':{'the':1,'innumerable':1},'diamond.':{'as':1},'according':{'to':24},'disappointment':{'when':1},'among':{'strongly':1,'all':1,'aquatic':1,'simple':1,'domestic':1,'them':1,'spiders':1,'domesticated':1,'birds':1,'cuttlefishes':1,'terrestrial':1,'lizards':1,'animals--by':1,'other':1,'which':2,'plant':1,'mammals':1,'mammals.':1,'dissimilars':1,'animals':4,'monkeys':1,'plants':3,'backboned':1,'this':1,'cosmic':1,'sand':1,'kindred':2,'the':21},'stretches':{'of':3,'from':1},'mound-birds':{'of':1,'young':1},'terse':{'and':1},'function--we':{'may':1},'flower-vase':{'well':1},'parachutists':{'and':1,'climbers':1},'maintained':{'this':1,'that':2,'by':1,'in':1},'stretched':{'in':1},'spans':{'the':1},'associated':{'a':1,'files':1,'his':1,'is':1,'enlargement':1,'reduction':1,'in':3,'the':2,'with':17},'reason--lays':{'her':1},'technicalities':{'.':1,'in':1},'considering':{'the':3},'sensible':{'things':1},'millimetre':{'and':1,'is':1},'caricature':{'of':1},'capable':{'of':3},'one-celled':{'plants--paint':1,'marine':2,'organism':1,'animal':1,'animalcules':1},'conditions.':{'illustration':2},'wilkinson.':{'jackdaw':1,'two':1},'mark':{'races':1,'individuals':1,'.':1},'attaching':{'too':1},'marked.':{'it':1},'mars':{'and':7,'is':3,'it':1,'maintained':1,'jupiter':1,'at':1,'141.5':1,'in':1,'there':1,'29':1,'.':2,'to':1,'going':1,';':1,'showing':1,'on':1,'october':1,'as':1,'were':1,'--jupiter':1,'the':1,'makes':1,'are':1},'tree-shrews':{'tupaia':1,'tree-mice':1,'hedgehog':1},'fiftieth':{'trip':1},'educated':{'who':1},'nautilus.':{'keen':1},'offered':{'some':1,'by':2,'for':1},'suns.':{'our':1},'dangerous':{'and':1,'to':1,'motto':1,'days':1,'maladies':1},'gripped':{'and':1,'in':1},'hippolyte':{'of':1,'which':1},'cod-banks':{'is':1},'dramatic':{'discoveries':1},'wake':{'of':1},'it.':{'the':1,'there':1,'whereupon':1,'other':1,'sun-spots':1},'captivity':{'has':1,'.':1},'sound':{'and':1,'conception':1,'though':1,'of':3,'.':3,'travels':1,'cannot':1,'another':1,'consists':1,'has':1,'judgment':1,'or':1},'turtles':{'and':3,'lay':1,'have':1,'which':1},'cannonade':{'of':1},'humming-bird':{'moths':1},'promising':{'wild':1,'a':1,'as':1,'.':1},'awakened':{'from':1},'margin':{'of':3,'are':1,'interlock':1},'luidia':{'which':1},'eventually':{'there':1,'like':1,'formed':1,'it':1,'to':3,'succeed':1,'they':1,'the':1,'creep':1,'after':1},'characteristics':{'of':2,'which':1,'e.g':1},'sleeping':{'prawns':1,'sickness':5},'strain':{'and':1},'sudden':{'and':2,'protrusion':1,'throwing':1,'irruption':1,'irritation':1,'withdrawal':1,'beginning':1,'acquisition':1,'movement':1},'tse-tse':{'fly':3},'dangerously':{'.':1},'ferns':{'conifers':1},'jackdaw':{'is':1,'balancing':2},'everyday':{'functions':1,'life':1,'intellectual':1,'bodily':1,'routine':1,'conditions':1},'movements':{'and':7,'on':1,'by':2,'that':3,'of':7,'is':1,'should':1,'how':1,'as':1,'implied':1,'are':2,'which':2,'in':1,'.':1,'until':1},'bags':{'of':1},'different':{'and':1,'set':1,'physiological':1,'methods':1,'instruments':1,'wave-lengths':2,'ages':1,'metals':1,'fellow':1,'rate':1,'manner':1,'times.':1,'in':3,'kinds':9,'as':1,'colours':5,'functions':1,'rays':1,'from':7,'ways':3,'relations':1,'.':3,'forms':1,'parts':1,'rates':1,'sedimentary':1,'105':1,'degrees':2,'main':1,'sections':1,'temperature.':1,'tacks':2,'idea--of':1,'aspects':1,'substances':4,'solution':1,'lines.':1,'groups':1,'fishes':1,'world':2,'rivers':1,'types':3,'areas':1,'lengths':2,'sizes':1,'this':1,'habitat-zones':1,'countries':2,'lines':2,'haunts':1,'thicknesses':1,'patterns':1,'length':1,'levels':2,'velocities':1,'latitudes':1,'terms':1},'paw':{'and':1,'to':1,'in':1},'pay':{'a':1,'out':1,'no':1},'oven':{'at':1},'same':{'and':1,'impression':1,'macaque':1,'facility':1,'appearance':1,'is':7,'table':1,'primary':2,'general':1,'attitude':2,'mistakes':1,'in':1,'bones':1,'corner':1,'face':3,'speed':1,'disadvantage--a':1,'as':3,'size':1,'story':1,'rays':1,'temperature':2,'opaque':1,'interesting':1,'nature':1,'proportion':1,'.':2,'state':1,'experiment':1,'way':9,'must':1,'conditions':1,'side':2,'foundation':1,'sex':1,'animal':1,'power':1,'format':1,'nest':1,'material':1,'gas':2,'effect':1,'period':1,'moment':1,'everywhere':1,'waves':1,'stem':1,'distance.':1,'day':1,'change':1,'stage':1,'kind':3,'type':1,'lines':1,'shape':1,'element':1,'magnet':1,'thing':1,'place':1,'principle':1,'fundamental':1,'time':8,'species':1,'applies':1,'table.':1,'essential':1},'eggs--up':{'towards':1},'thinning':{'of':1},'speech':{'.':1},'arguments':{'on':1,'.':1},'--all':{'the':1},'played--for':{'better':1},'intermediary':{'associative':1},'movement.':{'under':1},'extended':{'on':1,'tail':1,'from':1,'the':1,'their':1},'73000':{'10':1},'prominences':{'22':1,'these':1,'of':1,'which':3,'seen':2,'shooting':1,'ever':1},'assist':{'in':1},'companion':{'and':1},'running':{'on':2,'from':1,'no':1,'birds':1,'water':1,'leap':1,'leaps':1,'down.':2,'across':1,'down':2},'dynamo.':{'by':1,'illustration':1},'driven':{'outward':1,'by':2},'is--should':{'evolve':1},'waves.':{'the':1},'ripening':{'hard':1},'break':{'out':1,'up':2,'one':1},'largely':{'a':2,'feed':1,'based':1,'due':2,'with':1,'by':1},'roughly':{'group':1},'spoonful':{'of':1},'objection':{'there':1},'frontispiece':{'laplace':1,'.':1},'bottle':{'containing':1,'upside':1},'repulsive':{'or':1},'consisted':{'of':5,'only':2,'in':1},'generalisation':{'that':1},'money':{'paid':2,'if':1},'adjustments':{'which':1},'egg-cell':{'a':1,'certain':1,'within':1,'.':3,'fertilised':1,'in':1,'with':2,'divides':1},'down-drifting':{'food':1},'aspect':{'of':5,'can':1},'multiples':{'of':1},'sprang':{'the':1,'from':4,'but':1},'pinkish':{'eggs':1},'beagle':{'voyage':1},'crocodiles':{'and':1,'a':1,'there':1,'bury':1},'dipper':{'and':1,'or':1},'4':{'and':4,'another':1,'our':1,'living':1,'depict':1,'from':1,'tentative':1,'there':1,'.':11,'1':1,'500':1,'chromosomes':3,'information':1,'forming':1,'000':1,'external':1,'by':2,'a':2,'likeness':1,'this':1,'neptune':1,'the':6,'drawing':1},'grating':{'instead':1,'is':1},'pupa':{'stage':1},'extensive':{'repertory.':1},'heavier':{'to':1,'the':1,'materials':2,'more':1,'atoms':1},'pill':{'fizzing':1},'grip':{'and':1,'the':3},'1914.':{'baby':1,'4':1,'nos':1},'bitterling':{'cannot':1,'rhodeus':2},'tenses':{'.':1},'dissected':{'out':1},'tissues':{'and':1,'no':1,'of':1,'.':1,'to':1,'are':1,'or':1},'sight.':{'the':1},'water-measurers':{'in':1},'long-haired':{'angoras':1},'disadvantageous':{'dints':1},'aiming':{'at':1},'blankets':{'otherwise':1},'thames':{'gravels':1},'vertically':{'through':1},'dingo':{'or':2},'identifying':{'a':1,'different':1,'substances':1},'brain-development':{';':1},'serves':{'as':5},'lightning':{'278':1,'of':1,'in':1,'.':1},'facing':{'towards':1,'page':1},'chamber':{'only':1,'that':1},'behaviour-variations':{'which':1},'nose':{'that':1},'spinthariscope':{'making':1},'ascends':{'to':1,'into':1},'hunterian':{'professor':1},'mimicry.':{'colour':1},'flattely':{'and':1},'reveals':{'to':1,'the':2,'about':1},'alternately':{'and':1},'titan':{'a':1},'ascend':{'to':1,'the':2},'second.':{'their':1,'the':2,'sir':1},'specified':{'in':2},'images':{'of':1,';':1},'pasture':{'.':2},'ascent':{'of':7,'.':2,'not':1,'the':1,'by':1,'170':1},'gross':{'profits':1},'entities':{'of':1,'really':1,'.':1,'in':1},'apprenticeship--an':{'apprenticeship':1},'bubbles.':{'illustration':1},'footing':{'on':1},'fluids':{'and':1,'.':1},'considers':{'is':1},'pioneer':{'scorpion':1,'backboned':1,'animal':1},'critical':{'scientific':1,'discussion':1,'to':1,'time':1,'velocity':1,'spirit':1,'testings':1},'lunar':{'dawn':1,'apennines':1},'expressing':{'themselves':1,'or':1,'judgments':1,'feelings':1},'pipes':{'from':1,'by':1},'aboriginal':{'races':1},'rooks':{'and':1,'nests':1,'deal':1},'measuring':{'the':1,'does':1,'from':1,'it':2},'prerogative.':{'the':1},'buckling':{'up':1},'seconds':{';':1,'later':1,'takes':1,'.':2},'manufactured':{'by':1},'each':{'and':1,'other.':2,'foot':1,'pole':1,'constituent':1,'limb':1,'subject':1,'standing':1,'variety':1,'distinct':1,'incipient':1,'flash':1,'spiral':1,'.':2,'cell':2,'to':1,'prism':1,'other':9,'brick':1,'is':2,'foot.':1,'body':1,'star':1,'sinks':1,'molecule':1,'kind':2,'electrified':1,'electron':1,'descending':1,'atom':2,'date':1,'article':1,'with':3,'case':1,'independently':1,'substance':1,'particle':2,'of':11,'age':1,'tenanted':1,'metal':1,'element':2,'wave-length':1,'shade':2,'about':3,'side':1,'limb.':1},'notable':{'differences':1,'was':1,'feature':3,'power':1},'unusual':{'circumstances':1},'notably':{'the':3,'to-day':1,'planarians':1,'those':1},'trials':{'was':1},'arithmetical':{'question':1},'refers':{'to':1,'in':1},'stock--some':{'of':1},'psychical':{'level.':1,'research':1},'staff.':{'please':1},'stations':{'.':1},'instantaneously':{'into':1,'.':1,'he':1},'fringe':{'round':1},'insect':{'living':1,'lived':1,'flight':1,'larvae':3,'may':1,'is':1,'.':1,'visitors':3,'s':6,'lighting':1,'are':1,'pierces':1,'has':1,'with':1},'mixes':{'with':1},'practical':{'proposal':1,'judgments':1,'interest':1,'disappearance':1},'pockets':{'on':2},'west':{'of':1,'indian':1,'salt':1,'at':1,'coast':1},'corals':{'and':1,'worms':1,'which':1},'lasting':{'power':1},'provisional':{'picture':1},'road':{'home':1},'cautions':{'to':1},'lands':{'and':1,'in':1},'fertile':{'soil':1,'land':1,'meadows':1},'sea-grass':{'a':1,'area.':1,'red':1},'spreading':{'over':1,'meadows':1},'bountiful':{'and':1},'mills.':{'sir':1,'professor':1},'haddon':{'a':2},'gambiense':{'very':1,'69':1},'einstein':{'s':1,'has':1,'the':1,'who':1},'shortening':{'of':2,'the':1},'bon':{'has':1},'shells':{'of':1,'keeping':1,'are':3,'like':1},'camouflaging':{'giving':2,'and':1,'but':1},'brute':{'associates.':1,'man':1},'appears':{'on':1,'melancholy':1,'that':2,'to':1,'therefore':1,'the':1,'or':1},'caterpillars':{'and':2,'of':1,'to':1,'through':1,'they':1,'fasten':1},'laboriously':{'manufacture':1,'taught':1},'deepened':{'interest':1},'granules':{'and':1,'are':2},'unsettled':{'parts':1},'strikes':{'these':1,'the':1,'it':1},'white.':{'and':1,'banded':1},'trouble--an':{'instance':1},'land.':{'ages':1,'illustration':1,'getting':1},'spice':{'of':1},'arranged':{'his':1,'in':5},'romantic':{'and':1},'reflex':{'arc':2,'actions':8,'.':1,'action.':1,'action':4,'response':1,'chains':1,'than':1},'vice':{'versa':1},'dordogne':{'galley':1},'arranges':{'the':1},'pre-cambrian':{'eras':1},'blackbird':{'a':1},'shell.':{'the':1,'sec':1},'mimicked.':{'the':1},'moles':{'freshwater':1,'are':1},'affection':{'for':1,'.':1},'celestial':{'objects':1},'deliberation':{'and':1},'travailing':{'becomes':1,';':1,'of':1},'fanwise':{'to':1},'deer':{'of':1,'rabbit':1},'body-making':{'is':1},'deep':{'and':1,'water':2,'cups':1,'retreat.':1,'waters':3,'isolated':1,'waters.':1,'dark':1,'reason':1,'so':1,'sea':6,'in':2,'sea--the':1,'borings':1,'cold':1,'difference':1,'lake':1,'lying':1},'general':{'and':1,'impression':1,'outlook':1,'glare':1,'features':1,'symmetry':1,'trend':1,'life':1,'statements':1,'information':1,'question':1,'ideas':7,'relations':1,'statement':1,'significance':1,'public':2,'conclusion':1,'direction':1,'terms':3,'way':5,'very':1,'reader':1,'agreement':1,'flattened':1,'astronomy':1,'outlines':1,'we':1,'colour':2,'lines':1,'rule':1,'method':1,'aim':1,'agreement.':1,'succession':1,'opinion':1,'fact':1},'imagination':{'to':1,'.':1,'of':2},'examine':{'one':1},'planets':{'and':5,'they':1,'back':1,'spinning':1,'including':1,'are':2,'in':1,'seem':1,'what':1,'from':1,'would':3,'.':4,'to':1,'drawn':2,'life':1,'showing':1,'but':1,'five':1,'besides':1,'put':3,'of':3,'together':1,'or':1,'venus':1,'round':1},'lifetime':{'will':1,'namely':1,'by':1,'.':1},'cables':{'but':1},'film':{'and':1,'of':3,'is':1,'cling':1,'on':1},'fill':{'every':3},'tedious':{'time':1},'again':{'and':6,'as':3,'are':1,'in':5,'from':1,'knowledge':1,'would':1,'there':3,'.':1,'to':2,'does':1,'recaptures':1,'meant':1,'be':1,'we':3,'after':1,'led':1,'elsewhere':1,'that':1,'becomes':1,'never':1,'but':1,'with':1,'for':1,'many':1,'the':5,'having':1},'gbnewby':{'pglaf.org':1},'retiring':{'disposition':1},'field':{'and':3,'around':1,'of':6,'is':2,'it':1,'.':2,'as':2,'book':1,'240':1,'seen':2},'prism':{'and':1,'we':2,'produces':1,'into':1,'.':3,'entering':1,'separates':1,'is':1},'unaccustomed':{'and':1},'salamanders':{'of':1},'carapaces':{'form':1},'lafayette':{'alsatian':1},'coughing':{'or':1},'shelter':{'and':1,'of':2,'with':1,'for':1},'planet.':{'so':1,'if':1},'deriving':{'their':1},'important':{'stones':1,'and':2,'because':1,'is':5,'idea':1,'general':1,'phase':1,'as':1,'in':2,'mill':1,'activity--that':1,'for':2,'to':6,'role':1,'parting':1,'was':1,'however':1,'part':4,'food-plants':1,'parasites':1,'than':1,'linkage':1,'acquisitions':1,'advance':1,'acquisition':1,'the':1,'fact':6},'itself.':{'forms':1,'of':1,'but':1,'in':1},'tackle':{'the':1},'rainbow-colour':{'.':1},'revolve':{'the':1,'round':2},'sun--a':{'kind':1},'sneeze':{'on':1,'.':1},'hoofed':{'mammals':2},'remote':{'aquatic':1,'star':1,'age':1,'antiquity':1,'future':1,'ancestors.':1,'the':1},'recapitulation':{'of':3},'casts':{'off':1},'innocent-looking':{'little':1},'burrow':{'becomes':1,'which':1,'in':1},'u':{'of':1,'the':1},'resembles':{'a':1},'ovary':{'.':1},'once':{'and':3,'adjusted':1,'useful':1,'one':1,'rotating':1,'understood':1,'in':8,'said':1,'.':1,'attained':1,'got':1,';':1,':':1,'was':2,'tell':1,'more':4,'dominant':1,'that':1,'very':2,'eight':1,'they':1,'represented':1,'a':2,'on':1,'made':1,'effective':1,'larger':1,'rule':1,'every':1,'pulled':1,'or':1},'starting':{'a':1,'new':2,'point':1,'of':1},'represent':{'the':1,'stars':1,'tentative':1},'pheasant':{'and':1,'for':1},'forget':{'the':1},'founder':{'of':1},'suns':{'many':2,'.':1,'in':1},'invariable':{'.':1},'worms':{'and':2,'like':1,'that':1,'sea-cucumbers':1,'of':1,'began':1,'but':1,'.':1,'notably':1,'to':3,'2':1,'starfishes':1,'were':1,'requires':1},'founded':{'on':1},'sunk':{'very':1,'into':1,'in':1},'cooperative':{'relations':1},'expressions':{'of':3,'have':1},'plodding':{'methods':1},'shattered':{'to':1},'red-hot':{'ball':1,'gas':2,'.':1},'brain-box':{'and':1},'inexhaustible':{'fountain':1,'floating':1,'stores':1},'former':{'.':1},'bushmen':{'.':1},'those':{'upper':1,'pieces':1,'produced':1,'excessively':1,'farther':1,'in':1,'fine':1,'whose':1,'two':1,'regions':1,'immense':1,'contained':1,'other':1,'which':3,'between':1,'open-sea':1,'we':2,'kinds':2,'elsewhere':1,'that':13,'mammals':1,'offered':1,'who':3,'problems':1,'provided':1,'now':1,'with':1,'sensational':1,'great':1,'made':1,'of':15,'days':1,'glittering':1,'called':1,'bodies':1,'at':1},'hideous':{'and':1},'turnips':{'devouring':1},'distorting':{'effect':1},'straightforward':{'.':1},'sitting':{'a':1,'among':1,'figure':1,'for':1,'156':1,'the':1},'worm.':{'the':1},'interglacial':{'period.':1,'period':1,'times':1,'times.':1,'.':1,'or':1},'sun.':{'a':1,'look':1,'this':1,'it':1,'illustration':1,'one':1,'to':1,'sec':1,'but':1,'our':1,'the':2,'laplace':1},'fall':{'a':1,'on':4,'casting':1,'is':2,'upon':2,'suggested':1,'together':1,'down':1,'without':1,'from':1,'into':4},'difference':{'and':2,'is':1,'between':4,'to':1,'saturates':1,'does':1,'in':2},'expulsive':{'force':1},'mild':{'current':1,'moist':1,'electric':1,'temperatures':1,'of':1},'forking':{'of':2},'washing':{'the':1},'benevolent':{'visitors':1},'skeletal':{'rod':1},'applicable':{'to':1,'state':1,'taxes':1},'grubs':{'and':1},'camouflaged.':{'the':1},'hollowed-out':{'cotton-reel':1},'inorganic':{'world':1,'evolution':7,'groaning':1},'economically':{';':1},'pterodactyl':{'and':1,'or':2,'wing':1},'range.':{'the':1},'selected.':{'illustration':1},'aristocrat':{'apple-trees':1},'zero':{'of':2},'perception':{'and':1,'of':1,'rapidity':1},'further':{'and':3,'slowing':1,'down':1,'books':1,'human':1,'out':1,'knowledge':1,'for':2,'opportunities':1,'experiment':1,'until':1,'revision':1,'advantage':1,'complicated':1,'with':1,'contraction':1,'inland':1,'heightened':1,'ahead':1,'found':1,'the':1,'discovery':1,'changes':1},'double-slide':{'plate':1,'plate-holder':1},'creatures':{'and':4,'appeared':1,'it':1,'sec':1,'are':3,'have':3,'in':2,'if':1,'living':1,'from':1,'varied':1,'to':1,'began':1,'there':1,'.':6,'superficially':1,'which':3,'return':1,'that':1,'may':2,'act':2,'upon':2,'but':1,'let':1,'penetrate':1,'not':1,'such':1,'with':3,'by':1,'a':1,'on':1,'like':3,'of':4,'make':2,'turn':1,'were':1,'dance':1,'the':2,'round':1},'cilia':{'shown':1,'when':1},'stood':{'in':1,'at':1,'round':1},'short-lived':{'fishes':1,'relic':1},'swamps':{'and':1,'low':1},'storks':{'and':1,'pelicans':1},'associate':{'certain':1,'the':1,'particular':1},'caffeine':{'and':1},'everlasting':{'hills.':1},'schoetensack':{'.':1},'movement':{'and':6,'all':1,'is':4,'at':1,'in':2,'251':1,'if':1,'from':1,'for':1,'recalling':1,'.':1,'which':1,';':1,'was':1,'but':1,'a':1,'on':1,'of':6,'creates':1,'can':1,'the':1,'or':1},'outgoing':{'tide':1},'malaria':{'rife':1,'respectively.':1,'from':1,'organism':2},'martians':{'draw':1},'compilation':{'of':1,'copyright':1},'calculates':{'that':1},'component':{'cells':1},'ranges':{'and':2},'favourable':{'for':1},'cylindrical':{'.':2},'operating':{'on':1},'capacities--limited':{'when':1},'standard':{'of':2,';':1},'advance--the':{'central':1},'search':{'of':1,'after':1,'for':1,'facility:':1,'.':2},'tortoise':{'and':1,'of':1,':':1,'in':1,'has':1},'ichneumon':{'grubs':1},'cock':{'with':1},'stretching':{'as':1,'from':1,'for':1},'gleams':{'of':2},'milky':{'way':15},'formation':{'of':7,'due':1,'ten':1,'in':1},'narrow':{'and':1,'core':2,'like':1,'zone':1,'crowded':1,'sheaf':1,'passage':2,'marshes':1},'beak-like':{'jaws':1},'pathological':{'variation':1},'splashes':{'in':1},'24.--the':{'great':1},'transit':{'instruments':1,'is':1,'no':1},'mastering':{'the':1},'africa':{'a':1,'and':1,'india':1,'but':1,'coloured':1,'to':1,'asia':2,';':1,'where':1},'fastening':{'them':1,'pieces':1},'most--control':{'freedom':1},'empties':{'are':1},'extinction':{'of':1,'in':1},'establish':{'themselves':2,'race':1},'readily':{'separated':1,'lifted':1,'because':1,'heard':1,'swamped':1,'classified':1,'utilised.':1,'evaporate':1,'.':1,'understood':1,'see':1,'seen':1,'captured':1},'eye':{'and':3,'sees':1,'is':1,'are':1,'in':1,'.':6,'birds':1,'there':1,'next':1,'to':1,'which':2,';':2,'has':1,'that':1,'may':1,'fell':1,'continued':1,'by':1,'these':1,'of':1,'can':1,'the':1,'glued':1},'uniformity':{'and':1},'distinct':{'and':2,'individuality':1,'elements':1,'from':2,'species.':1,'sensation':1,'ancestors--a':1,'as':1,'classes':1,'tails':1,'sparks':1,'species':1},'hillock':{'of':1},'wiped':{'out':1},'destination':{'and':1},'two':{'years':1,'straws':2,'fore-limbs':1,'fine':1,'feather-stars':1,'forms':1,'molecules':1,'main':2,'photographs':2,'moorhens':1,'doors':1,'very':1,'minute':1,'feet':3,'positions':1,'spiny':1,'humps':2,'lashes':1,'phenomena':1,'back':1,'elements':1,'magnets':1,'creatures':1,'fingers':2,'halves':1,'chimpanzees':1,'new':1,'revolved':1,'ends':2,'electricities':1,'answers':1,'atoms':2,'hours':3,'wave-motions':1,'terminals':1,'groups':4,'others':1,'quite':2,'come':1,'days':1,'opossums':2,'of':4,'months':2,'haunts':1,'extremes':1,'streams':1,'or':11,'comes':1,'reflected':1,'screens':1,'skeletons':1,'millions':1,'working':1,'spiral':1,'long':1,'.':3,'macaques':1,'stars':2,'which':1,'hundred':7,'fractions':1,'eyes':1,'inches':4,'painted':1,'thousand':3,'exactly':1,'races':1,'cases':2,'cells':1,'shelves':1,'classes':1,'minutes':1,'and':8,'suggestions':1,'metals':1,'pieces':2,'periods':1,'have':1,'in':1,'paths':1,'different':5,'perhaps':1,'things':1,'widely':1,'lithium':1,'centrosomes':1,'facts.':1,'wires':1,'kinds':6,'opposite':1,'eggs':1,'teeth':1,'sides':3,'types':3,'together':3,'chief':1,'points':3,'sets':2,'serious':1,'the':1,'bodies':2,'foetal':1},'comparing':{'these':1,'notes':1,'reptiles':1},'cultivation':{'of':1},'endowed':{'with':4,'monkeys':1},'raft':{'across':1},'ovules':{'within':1,'in':1},'lapland':{'.':1},'leisure.':{'along':1},'unlink':{'or':1},'ahead.':{'the':1},'diamond':{'the':1,'point':1,'267':1,'.':1},'staggering':{'.':1},'views--the':{'nature':1},'chimpanzee':{'and':3,'illustrating':2,'157':1,'sitting':2,'is':1,'there':1,'.':1,'gorilla':2,'s':2,'2':2,'238':1,'at':1,'the':1,'an':1,'called':1,'233':1},'magpies':{'coral-snakes':1},'controlling':{'his':1,'nerve-centres':1},'particular':{'they':1,'some':1,'paper':1,'substance.':1,'sounds':1,'things':2,'emotions':1,'colours':1,'instance':1,'state':1,'difficulties':1,'interest':1,'conditions':1,'crab':1,'combination':1,'men':1,'atoms':1,'words':1,'circumstances':1,'case':1,'kind':4,'spawning-pond':1,'items':1,'moorhen':1,'place':1,'piece':1,'order':1},'straight-haired':{'mongols':2},'it--radium.':{'that':1},'none':{'being':1,'of':6,'the':1,'knew':1,'.':1},'hour':{'passes':1,'later':1,'would':1,'radium':1,'after':1,'.':1,'at':1},'middle':{'and':1,'zone':1,'of':2,'pleistocene':1,'ages':1,'oligocene':1,'.':1,'eocene':1},'recall':{'the':3},'sucks':{'in':1,'its':1,'milk':1},'cochroaches':{'and':1},'guards':{'them':2,'the':1},'remain':{'true.':1,'to-day':1,'inert':1,'just':1,'very':1,'freely':1,'together':1,'quite':2,'coherent':1,'in':2,'latent':1,'ether':1,'glorious':1,'apart':1},'pressing':{'a':1},'taut':{';':1,'or':1,'membranes':1},'pink-flush':{'on':1},'nothing.':{'evolution':1,'it':1},'specialized':{'in':2},'marble':{'for':1},'deg':{'.':6},'stubborn':{'as':1},'compare':{'with':2,'the':1,'jupiter':1},'gravels':{'in':1},'share':{'of':2,'it':1,'appreciatively':1,'in':1},'shard':{'the':1},'sphere':{'of':1},'minimum':{'the':1,'without':1},'numbers':{'and':2,'go':1,'above':1,'of':4},'hours.':{'at':1},'sharp':{'mountain-top-like':1,'prickle':1,'mouth-parts':1,'teeth':1,'nip':1,'conical':1,'points':1},'robinson':{'showed':1},'needs':{'to':2,'with':1,'occurring':1},'awkward':{'situation':1,'alacrity':1,'feint':1},'receptacle':{'for':1},'1873-6':{'gave':1},'acts':{'on':1,'as':4,'upon':1,'in':1},'responsibilities':{'.':1},'procellaria':{'pelagica':2},'sacred':{'river-tortoises':1},'profiting':{'by':2},'stir':{'water':1},'ensemble':{'of':1},'indian':{'and':2,'islands':1,'macaque':1,'ocean':1},'advice':{'to':1},'genius.':{'illustration':1},'narrow-beaked':{'crab':1},'tangere':{'leave':1},'blood':{'and':1,'corpuscles':2,'from':1,'relationship':1,'of':5,'is':1,'never':1,'it':1,'throughout':1,'.':4,'to':1,'as':1,'goes':2,'injected':1,'the':1,'has':1,'bringing':1,'or':3},'polynesian':{'mariners':1},'coming':{'and':1,'from':1,'down':2,'to':1,'with':1,'by':1,'out':1},'bloom':{'with':1},'response':{'to':1,'the':1,'from':1},'alps':{'at':1},'reappeared':{'his':1},'crowded':{'meteors':1,'when':1,'with':1,'haunt':1,'difficult':1},'coat':{'to':1,'used':1,'helps':1},'eats':{'its':1},'dragon':{'the':1,'flying':1,'draco':1,'94':1},'coal':{'burns':1,'consider':1,'would':1,'supply':1,'derived':1,'deposits':1,'for':1,'which':1,'.':3,'or':1},'skilful':{'artificer':1},'playing':{'mammals':1,'is':1,'period':2,'possum':1,'the':1,'with':2},'covered':{'a':1,'great':1,'over':1,'all':1,'everything':1,'the':3},'chopped':{'earthworm':1},'infant':{'and':1,'s':1,'.':1,'about':1,'three':1},'rounded':{'skull':2},'winged':{'phase':1,'snails':1,'insect.':1},'much-disputed':{'lines':1},'hypertext':{'form':1},'quiet-looking':{'cloud':1},'lumpsucker':{'mounts':1,'guards':1},'through':{'and':2,'it':3,'one':1,'our':1,'any':2,'unthinkably':1,'space':1,'.':1,'which':3,'orange':1,'1.e.7':2,'them':3,'his':1,'trees':1,'estuaries':1,'every':1,'but':1,'denser':1,'contrasts':1,'an':4,'a':19,'stone':1,'glass':1,'these':2,'air':2,'this':2,'the':54,'stages':1,'its':3,'bodies':1},'lava':{'rising':1},'filters':{'and':1},'existence':{'what':1,'135':1,'of':6,'is':3,'it':1,'.':2,'namely':1,'without':1,'are':1,'animal':1,'in':2,';':1,'by':1,'as':1,'if':2},'visceral':{'clefts':2},'bell-like':{'blossoms':1},'soddy':{'has':1,'frederick':1,'have':1,'puts':1,'one':1},'24':{'the':1,'were':1},'25':{'and':1,'of':1,'trillions':1,'000':6},'26':{'and':1,'we':1,'000':2,'tons':1},'27':{'illustration:':1,'000':1},'thrilling':{'a':1,'story':1},'21':{'1914.':1,'.':1},'22':{'from':1,'would':1,'tons.':1,'yerkes':1,'miles':1,'2007':1},'sodium':{'is':1,'lines':1,'iron':2},'rigel':{'466':1},'physophora':{'hydrostatica':2},'28':{'the':1,'deg.-34':1,'mars':1},'29':{'1919':1,'a':1,'drawings':1,'1908':2,'1919.':1},'late':{'polished':1,'professor':3,'years':1,'autumn':1,'as':1,'triassic':1,'.':1},'detected':{'a':1,'anywhere':1},'microscopic':{'cilia':1,'burdens':1,'organisms':1,'food':1,'study':1,'globules':1,'fertilised':1,'animal':3,'each':1,'animals':1,'algae':1},'--and':{'that':1},'bugbear':{'it':1},'sheaves':{'in':1},'triumphantly':{'from':1},'beginnings.':{'our':1},'good':{'and':1,'atmosphere':1,'old':2,'deal':6,'reasons':1,'idea':1,'as':3,'seed':2,'in':1,'insulators':1,'will':1,'touches':1,'.':2,'instance':1,'samples':1,';':2,'conditions':1,'eyes':1,'send-off':2,'illustration':1,'reason':1,'restoration':1,'purpose':1,'pair':1,'many':1,'second':1,'example':2,'practical':1,'conductor--six':1,'temper':1,'heel':1},'seeking':{'rather':1,'automatically':1},'gardens.':{'the':1},'sappers':{'and':1},'noticing':{'the':1,'that':1},'walls':{'and':1,'of':6,'so':1,'are':1,'nor':1},'compound':{'reflex':2},'olcott':{'field':1},'detach':{'or':1},'struggling':{'too':1},'association':{'a':1,'established':1,'and':1,'of':2,'professor':1,'when':1,'to':1,'which':1,'between':1,'meeting':1},'limpet':{'s':1},'mystery':{'of':1,'they':1,'drowned':1,'.':1},'easily':{'tamed':1,'be':1,'acquiesce':1,'blown':1,'supported':1,'washed':1,'selected.':1,'called':1,'as':1,'disturbed':1,'part':1,'seen':1,'get':1,'find':1,'comply':1},'deteriorates':{'.':1},'fish-like':{'characters':1},'evade':{'the':3},'abdomen--for':{'the':1},'ashes':{'of':1},'habits':{'and':5,'all':1,'there':1,'.':2,'while':1,'which':1,';':1},'2a':{'orohippus':1},'repeating':{'the':1},'possession.':{'if':1},'exquisite':{'tactility':1,'refinements':1},'horsetail':{'and':1},'harm':{'in':1},'everyone':{'is':2,'who':2,'recognises':1,'knows':1},'mental':{'activities':1,'life':2,'endeavour':1,'ability':1,'inheritance':1,'pictures':1,'subtlety':1,'life;':1,'equipment':2,'experimenting':1,'health':1,'aspect':1,'activity':1,'images':1,'aspect.':1,'mill':1,'endowment':1,'side':2,'powers':1,'qualities':1},'hundred':{'and':2,'trillion':4,'varieties':1,'strokes':1,'of':1,'thousand':2,'million':4,'years':2,'ways':1,'planetoids':1,'degrees':2,'stars':1,'in':1,'miles':3,'the':1,'times':1,'odd':1,'generations.':1,'millions':1},'hare':{'willow':2,'it':1,'.':1,'may':1,'s':1,'in':2,'the':1,'or':1},'hard':{'and':2,'saying':1,'work':2,'times':1,'substratum':1,'to':4,'in':2,'legs':1,'or':1,'red':2},'idea':{'that':4,'of':13,'is':1,'but':1,'how':1,'has':1,'was':1,'or':1},'foxes':{'and':2,'stoats':1},'macmillan':{'the':2,'.':4},'oil':{'on':2,'from':1,'is':1,'upon':1,'down':1,'must':1},'schuchert':{'again:':1,'s':1},'connect':{'them':1},'ripple':{'of':1},'hart':{'the':1,'is':1},'antarctic':{'circle--which':1,'shore':1},'shoulders.':{'the':1},'flower':{'and':4,'puts':1,'is':1,'.':1,'basket':3,'collects':1},'associations.':{'there':1},'pigeon':{'a':1,'because':1,'212':2,'gliding':1,'is':1,'continues':1,'s':1,'but':1,'brooding':1,'carrier':1,'which':1},'acting':{'on':3,'upon':2},'49.4':{'rigel':1},'flowed':{'along':1},'print':{'editions':1},'three-quarter':{'days':1},'waterholes':{'full':1},'rejuvenescence':{'e.g':1},'circumstance':{'that':1},'dealt':{'with.':1,'with':6},'extraordinary':{'protrusion':1,'strength':1,'proceeding':1,'power':1,'variety':1,'educability':1,'things':2,'results':1,'vigour':1,'therefore':1,'interest':1,'outbursts':1,'properties':1,'adaptability':1},'terminals':{'thus':1,'.':1},'members':{'of':12,'at':1},'backed':{'by':3},'entrancing':{'interest.':1},'beginning':{'again':1,'for':1,'this':1,'of':35,'when':1,'it':1,'.':1,'to':5,'at':1,'in':2,'was':2,'with':2},'poles.':{'our':1,'there':1},'demands.':{'as':1},'snails':{'various':1,'or':1},'omit':{'one':1},'brain...':{'.':1},'audacity':{'to':1},'72-inch':{'reflector':1},'varanus':{'139':1,'the':1},'down--sometimes':{'dangerously':1},'exercising':{'the':1},'reinforced':{'by':1},'copper':{'and':1,'wires':1,'coin--smaller':1,'that':1,'immersed':1,'in':1,'together':1,'.':1,'age.':1,'wire':3,'zinc':2,'were':1,'beech':1,'age':1,'is':5,'came':1},'bullies':{'of':1},'disregarded':{'only':1},'instances':{'of':1,'where':1,'must':1},'7918':{'1':1},'done':{'is':1,'.':1,'to':1,'as':1,'with':1,'by':1},'vibrate':{'about':1,'.':1,'in':1},'climbing':{'grasping':1,'up':1},'cups':{'whereas':1},'island-universes':{'they':1},'family.':{'viviparity':1},'light-gatherer':{'.':1},'construct':{'a':2},'hollows':{'of':1},'obligatory':{'movements':1},'183':{'evolutionary':1},'assumption':{'of':2},'186':{'photograph':1,'nautilus':1,'shoebill':1,'000':7},'187':{'photo':1},'statement':{'will':1,'that':4,'often':1,'in':1},'185':{'000':1},'rates':{'.':1},'compartment':{'a':1,'b':1,'was':1},'too':{'faint':3,'plainly':1,'simple':1,'soon':2,'high':2,'inhospitable':1,'cold':3,'thick':1,'stingy':1,'easygoing':1,'little':1,'deeply':1,'there':1,'long':1,'hot':2,'much':6,'sheltered':1,'was':1,'complete':1,'shallow':1,'generous':1,'complicated':1,'closely':1,'precious':1,'great':1,'short':1,'large':1,'severe':1,'were':2,'small':2,'serious':1,'soft':1},'muscles':{'and':4,'of':2,'to':1,'going':1,'are':1,'which':1,'in':1,'than':1,'at':1},'travail':{'of':1},'lightest':{'hydrogen':1,'atom':2},'needle':{'on':1,'magnified.':1,'.':1},'park':{'in':1},'procession':{'of':3,'or':1},'part':{'the':1,'corresponding':1,'for':1,'vaporised':1,'of':54,'into':1,'in':3,'.':1,'to':3,'at':1,'under':1,'obscure':1,'with':4,'company':1},'parr':{'become':1,'about':1,'which':1},'prodigious':{'expulsive':1,'speed--and':1,'speed.':1,'outpour':1,'quantities':1,'age':1,'.':1,'scale.':1,'rapidity':2},'selenium-cell':{'which':1},'believe':{'that':11,'in':1,'an':1,'to':1,'were':1,'the':1,'by':1},'don.':{'it':1},'jump':{'at':1,'out':1},'supposes':{'that':2},'b':{'c':1,'that':1,'of':1,'showing':1,'there':1,'when':2,'it':1,'.':7,'in':1,'some':1,'alteration':1,'others':1},'parent--little':{'likely':1},'damages':{'even':1,'costs':1,'-':1},'clodd':{'story':1},'866':{'000':1},'recording':{'of':1},'dissection--or':{'screwing':1},'totteringly':{'for':1},'supposed':{'that':4,'dead':1,'to':4,'indication':1,'have':1,'the':1,'he':1},'messrs.':{'macmillan':3},'treated':{'merely':1},'anthropoid':{'embryo':1,'stock--common':1,'apes':7,'apes--the':3,'type.':1,'apes.':1,'ape':4},'rhacophorus':{'that':1},'efface':{'itself':1},'trifles':{'felted':1},'pre-existing':{'organisms':1},'ages':{'and':3,'set':1,'afterwards':1,'is':1,'sec':2,'in':1,'before':1,'living':1,'organisms':1,'there':1,'had':1,'.':4,'to':2,'which':3,';':2,'has':1,'was':1,'be':1,'we':1,'passed':6,'necessity':1,'along':1,'he':1,'ago':2,'many':1,'of':1,'the':3,'or':1},'left-handed':{'vortices':1},'egg.':{'very':1,'8':1,'3':1},'paltry':{'pigmies':1},'agee':{'when':1},'confirms':{'our':1},'fading':{'away':1},'paths':{'a':1,'of':1,'round':1,'pursued':1},'acid':{'and':1,'water':1,'indigo':1,'caffeine':1},'built':{'a':1,'and':1,'elastic':1,'on':1,'of':1,'up':10,'as':1,';':1,'with':1},'depending':{'upon':1},'trip':{'sideways':1,'which':1},'majority':{'of':7,'is':1,'are':1},'lifts':{'a':2,'the':1},'build':{'a':2,'up':5,'but':1},'deepening':{'hold':1},'sea-perches':{'live':1},'facts.':{'sec':1},'unpalatability':{'or':1},'easygoing':{'kind':1,'conditions':2,'the':1,'swimmers--for':1},'capillaries':{'of':1},'sciences.':{'the':1,'it':1},'eggs':{'and':5,'into':1,'are':2,'have':1,'in':7,'close':1,'during':1,'lie':1,'develop':3,'perhaps':1,'two':1,'.':5,'to':1,'only':1,'which':4,';':1,'77':1,'i.e':1,'with':1,'by':2,'a':1,'on':1,'of':2,'inside':2,'attached':1,'were':1,'or':4},'trains':{'lit':1,'of':1,'and':1},'salmon':{'spawn':2,'do':1,'in':1,'of':1,'is':1,'196':1,'surmounting':1,'leaping':2,'.':1,'1':1,'s':1,'keeps':1,'fry':1,'still':1,'was':1,'or':1,'as':2},'tail-feathers':{'braced':1},'took':{'origin':1,'a':1,'his':1,'longer':1,'advantage':2,'no':1,'flying':1,'up':1,'element':1,'as':1,'place':2,'so':1,'the':2},'depths':{'of':4,'showing':1,'119':1,';':1,'whence':1},'most':{'obdurate':1,'beautiful':2,'primitive':4,'debased':2,'remarkable':4,'people':4,'powerful':4,'valuable':1,'far-reaching':1,'multicellular':1,'bones':1,'inconspicuous':1,'diverse':1,'distant':3,'commonly':1,'abstruse':1,'intricate':1,'fishes':1,'birds':2,'resourceful':1,'impressive':2,'living':1,'salient':1,'daring':1,'patent':1,'interesting':2,'favour':1,'chemical':1,'to':1,'complex':1,'attractive':1,'laborious':1,'mammals':2,'mysterious':3,'promise.':1,'important':8,'difficult':1,'we':1,'popularly':1,'general':1,'scientific':1,'spectacular':2,'intimate':1,'successful':1,'familiar':1,'apparent':1,'convincing':1,'significant':1,'notably':1,'eminent':2,'part':1,'enduring':1,'recent':1,'authorities':1,'cases':9,'trying':1,'monkeys':1,'fascinating':2,'puzzling':1,'a':1,'land':1,'animals':2,'playsomest':1,'effective':2,'famous':1,'marvellous':1,'of':16,'signal':1,'countries':1,'metals':1,'enemies.':1,'distinguished':3,'project':1,'solid':2,'severe':1,'dramatic':1,'tempting':1,'distinctive':1,'ancient':3,'astonishing':1,'essential':1,'extraordinary':1},'petromyzon':{'marinus':2},'significant':{'as':1,'periods':1},'fluctuate':{'the':1},'branching':{'air-tubes':1},'transmissibility':{'of':1},'charitable':{'donations':1},'seething':{'foam':1,'mass':1,'vapours':1},'mammoth':{'drawn':2,'tube':1,'woolly':1,'age':1,'the':1},'weigh':{'a':2,'about':1,'only':1,'them':1,'approximately':1},'overcrowding':{'of':2},'organism':{'explores':1,'reproduced':1,'that':1,'may':1,'is':2,'acts':1,'which':1,';':1,'plays':1,'the':2,'its':1},'thomas':{'henry':2},'secrets.':{'the':1},'particularly':{'rich':1,'characteristic':1,'fond':1,'disposed':1,'important':1,'suited':1,'in':1,'memorable':1},'217':{'the':1},'obligations':{'and':1,'has':1},'fins':{'and':1,'on':1,'used':1,'of':1,'as':1,'taut':2},'scattered':{'the':1,'throughout':1,'was':1,'hither':1,'in':1},'converge':{'in':1},'wasted':{'in':1,'.':1},'shore-pool.':{'sec':1},'relation':{'to':3,'between':3},'carefully':{'just':1,'read':1,'there':1,'considered':1,'examine':1,'drawn':2},'212':{'photo':2},'amphibians.':{'as':1,'palaeozoic':1,'in':1},'fine':{'art':1,'crown':1,'results':1,'textbook':1,'powder':1,'suspended':1,'children':1,'creatures':1,'bulbs':1,'inequalities':1,'particles':2,'enough':1,'details':1,'vapour-like':1,'specimens':1,'product':1,'description':1,'brains':1,'time-recording':1,'translucent':1,'cross-striped':1,'photograph':1,'sections':1,'work':1,'balance':1,'example':1},'find':{'all':1,'some':1,'it':2,'in':3,'any':1,'out':4,'no':2,'two':1,'their':2,'enough':1,'much':1,'if':1,'reflex':1,'them':1,'that':11,'they':1,'included':1,'by':2,'a':4,'none':1,'these':2,'solid':1,'the':5},'downward-projecting':{'sharp':1},'giant':{'recently':1,'instruments':1,'spiral':3,'amphibians':1,'planet':1,'amoeba':1,'reptiles':2,'stars':1,'elephant':1,'whirlpools':1,'reptiles.':1},'double.':{'after':1},'depended':{'and':1,'on':1},'dividing':{'the':1,'into':2,'themselves':1,'as':1},'nervous':{'disturbance':1,'restlessness':1,'system.':1,'system':4,'excitement':1,'rhythm.':1},'bird--was':{'about':1},'distributed':{'old-fashioned':1,'project':1,'to':1,'proofreading':2,'in':1,'throughout':1,'by':1},'unhappy':{'over':1},'lockyer':{'sir':1,'detected':1,'pointed':1},'convoluted':{'.':1},'eruptions':{'at':1},'credulous':{'and':1},'8':{'and':1,'with':1,'there':1,'.':2,'in.':1,'other':1,'100':1,'minutes':2},'gills':{'again':1,'except':1,'.':3,'are':1,'which':2,';':3},'stringops':{'and':1},'merged':{'into':1},'indetal':{'is':1},'forreri':{'which':2},'dust':{'and':1,'no':1,'of':4,'.':2,'to':1,'at':1,'although':1,'in':5},'permission':{'and':1,'from':8,'for':1,'of':15,'.':1,'in':1},'express':{'a':2,'and':1,'the':1,'themselves':1,'or':1},'water-vole':{'and':1},'shore-pools':{'and':2,'makes':1,'in':1},'cheaper':{'.':1},'courage':{'and':1},'breast':{'pocket':1},'silk':{'tassel':4,'from':1,'handkerchief':1,'.':2,'threads':1,'across':1},'target':{'on':1},'transitional':{'experience':1,'between':1},'experiments.':{'illustration':1},'freedom.':{'the':1},'doubled':{'straw':1,'their':1,'over':1},'1825-95':{'86':1,'one':1},'common':{'and':1,'among':1,'habit':1,'is':1,'in':1,'at':2,'sense':1,'insectivore':1,'knowledge':1,'to':4,'chameleon':2,'foraminifer':2,'frog':1,'.':1,'hydra':1,'assumption':1,'animal':1,'chaffinch':1,'stock':1,'mud-skipper':1,'starfish':2,'centre':1,'showing':1,'ancestry--are':1,'shore-crab':2,'objects':2,'drone-fly':1,'from':1,'telescopes':1,'otter':2,'accident':1,'basis':1,'eel':3,'ancestry':1},'doubles':{'of':1},'experiments;':{'and':1},'immigrants':{'from':1},'tended':{'to':2},'disc-like':{'collection':1},'lion':{'.':1},'individual':{'is':1,'life':2,'at':1,'in':1,'movements':1,'from':1,'stands':1,'opportunities':1,'to':1,'stars':1,'has':1,'development':6,'variability':1,'plant':1,'hairs':1,'but':1,'atoms':1,'nurture':1,'types':1,'these':1,'work':1,'experience':3,'liberty':1,'project':2,'habits':1,'can':1,'the':1,'works':1,'ears':1},'starfishes':{'is':1,'spend':1,'sea-urchins':1},'medley':{'of':1},'long-fingered':{'pterodactyl':1},'tender':{'plant':1,'all':1},'forthcoming':{'for':1},'hole':{'and':2,'is':2,'before':1,'only':1,'in':1},'rays.':{'illustration':1},'gunnel':{'escape':1},'degree':{'of':12,'an':1,'which':1,'in':1,'not':1,'the':1,'.':1,'than':2},'halved':{'along':1},'please':{'read':1,'visit':1,'check':1},'splendidly':{'active':1},'halves':{'of':1,'the':1},'smallest':{'particle':2,'web-footed':1,'atom.':1,'french':1,'atom':2,'known':1},'planarians':{'and':1},'vascular':{'hood':2,'tufts':1},'to.':{'during':1},'mouthful':{'of':1},'donate':{'royalties':1,'section':1,'please':1},'sexual':{'reproduction':2},'beetling':{'ape-like':1,'eyebrows':1,'brows':1,'eyebrow':2},'historical':{'evolution':1,'succession':1,'or':1,'fact':1,'evidence':1},'masterful':{'more':1},'deliberately':{'selecting':1},'vanishing':{'mammals':1},'half-hour':{'longer':1},'reverse':{'the':1,'.':1},'journeyed':{'three':1},'annual':{'amount':1},'sons.':{'professor':1,'skeletons':1},'foreign':{'elements':1},'quadruped':{'.':1},'protopterus':{'91':1,'it':1},'elliot':{'fry':1},'point':{'and':1,'on':3,'we':1,'to':9,'that':1,'very':1,'of':9,'is':7,'though':1,'it':1,'.':5,'sound':1,'let':1,'the':3,'forty-five':1,'where':1,'out':1},'simple':{'protists':1,'and':2,'calculation':1,'instincts':1,'worms':1,'one':1,'multicellular':1,'as':1,'bibliographies':1,'creatures':3,'living':1,'many-celled':1,'one-celled':1,'there':1,'ideas':1,'process':1,'book':1,'electrical':1,'animal':1,'maze':2,';':1,'reflex':3,'sort':2,'experiment':1,'worm-types.':1,'that':1,'labyrinth':1,'but':2,'wave':1,'consideration':1,'cases':1,'flagellates':1,'outline':1,'tentatives':1,'form':1,'beginnings':1,'problem':1,'piece':1,'predatory':1},'unremitting':{'vibration':1},'smother':{'many':1},'knipe':{'s':6},'newborn':{'earth--the':1,'cuttlefish':1,'pigling':1},'electrons.':{'this':1,'when':1,'sec':1,'it':1,'illustration':1},'simply':{'a':1,'because':1,'that':2,'to':1,'thin':1,'with':1,'told':2},'unsuccessful':{'movements':1},'zeta':{'orionis':2},'throughout':{'and':1,'set':1,'that':1,'to':1,'the':13,'numerous':1,'its':1},'suppressing':{'useless':1},'expensive':{'and':1},'transformations':{'of':1},'meteorite':{'i.e':1,'or':1,'which':3},'create':{'fresh':1,'are':1,'or':2},'vertebrate':{'race':1,'at':1,'characters':1},'screened':{'the':1},'rivals':{'a':1,'in':2},'secret':{'of':6,'under':1,'from':1,'was':1,'phosphorus':1},'dropping':{'on':1},'stoat':{'becomes':1},'experiments--indications':{'of':1},'astonishment':{'a':1},'slips':{'down':1},'doles':{'of':1},'gas':{'and':3,'shot':1,'less':1,'expanding':1,'is':1,'it':1,'four':1,'as':1,'at':1,'in':3,'still':1,'would':1,'no':2,'there':1,'when':1,'.':2,'glowing':1,'which':1,';':1,'was':1,'be':1,'they':1,'absorbs':1,'about':1,'bill':1,'identified':1,'will':1,'were':1,'the':2,'cooled':1},'gap':{'to':1,'between':1},'vane':{'for':1},'waves--the':{'ultra-violet':1},'tupaia':{'began':1},'likened':{'our':1},'top--the':{'falling':1},'grains':{'of':2},'solid':{'body':2,'core':1,'and':1,'or':1,'liquid':1,'gold':1,'body.':1,'of':1,'could':1,'crust':2,'.':1,'substratum':1,'matter':1,'iron':1,'in':1,'earth':5,';':1,'earth--a':1,'the':1,'is':1,'ground':1},'tree-porcupines':{'and':1},'bill':{'and':1,'adapted':12,'where':1,'would':1},'eclipsed':{'when':1},'cluster':{'of':3,'is':1,'in':3},'plovers':{'lie':1},'replaced':{'by':9},'teaspoonful':{'of':1},'rhinoderma':{'of':1},'schultze':{'.':2},'eclipses':{'can':1},'manner':{'of':3,'away':1,'.':1,'born.':1,'at':1,'rarely':1},'youthful':{'stages':1},'adjusts':{'its':1},'debased':{'with':2},'century':{'we':1,'telescope':1,'that':2,'when':1,'.':4,'the':1,'was':1},'violently':{'and':3,'agitated':3},'metazoa':{'.':1},'regius':{'professor':1},'itself':{'and':3,'because':1,'is':3,'back':1,'an':1,'as':2,'registers':1,'through':1,'at':1,'in':5,'out':1,'again':1,'what':1,'for':1,'.':4,'to':6,'which':2,';':1,'millions':1,'until':1,'more':3,'tentatively':1,'that':1,'along':1,'with':3,'by':1,'he':1,'a':1,'on':1,'up':1,'the':2,'or':1},'atom--the':{'new':1},'saline':{'matter':2},'salina':{'that':1},'evading':{'this':1,'or':1},'discourse':{'.':2},'copying':{'and':1,'distributing':1,'displaying':1,'or':1},'leisurely':{'life':1},'ray':{'of':10,'lankester':4},'sapiens':{'the':1},'alertness.':{'ii':1},'non-digitate':{'paired':1},'eels':{'ascending':1,'are':1,'seem':1,'circumvent':1,'or':1,'illustrate':1},'keys':{'by':1},'leopard':{'is':1,'the':1},'deperet':{'transformation':1},'moment':{'a':1,'to':1,'.':1,'how':1,'s':1,'in':1,'the':3,'by':1},'purpose':{'and':1,'of':1,'is':1,'and--it':1,'here':1,'.':1,'they':1,'such':1,'the':1,'with':1},'timid':{'orioles':1},'circumvented':{'by':1,'.':1},'predecessors':{'rather':1,'of':2,'we':1},'gestures':{'and':1},'organically':{'enregistered':1},'task':{'of':1},'noli':{'me':1},'craves':{'for':1},'gambier':{'bolton.':6},'thoroughly':{'terrestrial':1,'aquatic':1,'aerial':1,'well':2,'it':1,'erect':1,'protected':1},'chemistry':{'and':1,'.':2},'spend':{'their':2,'much':1,'half':1},'examining':{'a':1},'matter.':{'a':1,'lockyer':1,'hitherto':1,'so':1,'another':1,'he':1},'snow':{'mouse':1,';':1,'upon':1,'or':1,'.':4},'profoundly':{'and':1,'influenced':1},'shape':{'and':2,'irresistibly':1,'from':1,'for':1,'that':1,'of':6,'they':1,'changes':1,'change':1},'atomic':{'theory':1,'weight':3,'energy':3,'weights':1,'numbers':1,'in':1,'reservoirs':1},'matter;':{'a':1},'alternative':{'reactions':1,'pathways':1,'but':1,'between':1},'unawares.':{'professor':1},'riki-tiki-tavi':{'which':1},'apes.':{'man':1},'timber':{'for':1},'letting':{'it':1},'superficial':{'differences':1,'work':1,'resemblance':1,'.':1},'cut':{'glass--the':1,'the':1,'up':1,'that':1},'developed.':{'nor':1},'alternate':{'directions--an':1,'format':1},'hereditarily':{'.':1},'source':{'may':1,'of':15,'which':1},'twig-insects':{'put':1},'follow.':{'since':1},'round-mouths':{'cyclostomes':1},'snap':{'at':1,'in':1},'hydrosphere.':{'formative':1},'ganglia':{'.':1},'excited':{';':1,'clucking':1},'silken':{'balloon.':1,'threads':1,'cocoon--the':1},'overhanging':{'bank':1},'big':{'and':1,'telescope':1,'spring':2,'canine':1,'sea-anemone':1,'brain':3,'as':1,'legacy':1,'simply':1,'seal':1,'toe.':1,'clock':1,'forehead':1,'toe':2,'robber-crab':2,'full':1,'brains':2,'lens':1,'with':1,'collar':1,'tree':1,'worm':1,'eyebrow':1,'seeds':1,'fact':5},'adventures.':{'there':1},'smallness':{'by':1},'far-fetched':{'and':1},'disappeared.':{'there':1},'life--a':{'progress':1},'bit':{'of':5},'stingless':{'.':1},'knock':{'over':1,'against':1},'photosphere--the':{'sun':1},'degenerated':{'in':1},'follows':{'a':1,'on':1,'from':2,'that':3,'an':1,'therefore':1,'the':1},'flux':{'and':1,'is':1,'in':1},'indication':{'of':2,'that':1},'beyond-blue':{'waves':1},'cotton-reel':{'as':1,'attached':2},'cloudlets':{'cannot':1,'come':1},'complicated.':{'sec':1},'gibbon.':{'bone':1},'valleys':{'.':1},'often':{'beautiful':1,'exhibit':1,'flies':1,'followed':1,'flapped':1,'pays':1,'overlooked':1,'float':1,'some':1,'libelled':1,'crop':1,'an':1,'say':1,'been':2,'vitally':1,'at':2,'in':2,'touch':1,'seen':1,'dug':1,'nests':1,'linked':1,'seems':1,'forced':1,'given':1,'from':1,'also':1,'apparently':1,'faint':1,'reminded':1,'outside':1,'expressed':1,'find':1,'attracted':1,'only':1,'complex':1,'easy':1,'buys':1,'got':1,'swims':1,'gets':1,'intelligent':1,'grows':1,'shows':1,'poor':1,'badly':1,'attended':1,'to':1,'make.':1,'very':3,'great':1,'safe':1,'about':2,'it':1,'saves':1,'succeed':1,'a':3,'become':1,'not':1,'associated':1,'revealed.':1,'subtle':1,'is':1,'fly':1,'and':1,'made':2,'created':1,'did':1,'of':1,'when':1,'with':4,'reads':1,'different':1,'adjust':1,'so':1,'.':1,'found':3,'lined':1,'involves':1,'referred':1},'absolutely':{'true':1,'essential':1},'hair-like':{'whilst':1},'triceratops':{':':2},'abundantly':{'these':1,'tenanted':1},'back':{'and':6,'into':1,'as':1,'at':1,'in':1,'our':1,'still':1,'again':2,'from':2,'for':1,'downwards':2,'.':1,'to':20,'which':1,';':1,'over':1,'becomes':1,'illustration':1,'125':1,'affording':1,'with':1,'by':3,'of':11,'sometimes':1,'became':1,'teeth':2,'the':1,'or':1},'evolution--there':{'is':1},'martian':{'day':2},'examples':{'of':5},'mirror':{'and':1,'for':1,'produces':1,'is':4,'.':1,'the':1,'than':1},'candle':{'but':1},'ourselves':{'to':2,'into':1,'here':2,'.':1,'how':1,'the':2,'quite':1},'pronounced':{'that':1},'crooked':{'stick':1},'condensed--who':{'can':1},'contacts':{'between':1},'affects':{'the':1},'per':{'hour':1,'second':3,'cent':5,'hour.':1,'step':1,'minute':1},'brain-case':{'of':2},'too--the':{'rabbit':1},'eliminate':{'useless':1},'king-crab':{'limulus':1},'peg':{'pulls':1},'11.--mars':{'october':1},'good.':{'bibliography':1},'scaly':{'fore-limbs':1,'covering':1},'stilt-like':{'legs':1},'life-history':{'of':7,'into':1,'.':1,'for':1,'to':1},'patient':{'with':1},'magnifies':{'this':1},'300':{'000':2,'chickens':1,'times':2},'peculiarly':{'interesting':1,'penetrating':1,'liable':1},'continuing':{'the':1,'.':1,'before':1},'fed':{'on':1,'when':1,'by':1,'.':1},'subconscious':{'cerebration':1},'more-pork':{'or':3},'flanks':{'and':1},'times--glacial':{'and':1},'feigning':{'death':3},'web-wing':{'of':1,'or':1},'nematodes':{'many':1},'piled':{'around':1},'ounce':{'or':1},'offshoot':{'is':1,'from':5},'consequently':{'the':1,'good':1,'changed.':1},'tree-loving':{'animals':1},'aliens':{'like':1},'night-light':{'noctiluca':1},'invading':{'the':1},'inhospitable':{'had':1},'gramme':{'of':1,'.':1},'relapses':{'to':1},'realisation':{'of':1},'deep-violet':{'light-waves':1,'waves':2},'ontario':{'about':1},'live-and-let-live':{'compromise':1},'plane.':{'the':1},'drosophila':{'among':1},'mudstones':{'and':2,'which':1},'trying--the':{'deep':1},'infected':{'with':1,'by':1},'manifested':{'by':1,'in':1},'checks':{'online':1},'forward':{'past':1,'to':2,'as':1,'by':1,'.':1},'examination':{'of':4},'adjusting':{'their':1,'its':1},'exterminated':{'the':1},'niagara':{'we':1,';':1,'are':1,'for':1,'falls':2},'boys':{'place':1},'quiescent':{'well-protected':1,'pupae':1},'hopes':{'that':1},'role':{'of':1,'in':2},'hipparion':{';':1},'directed':{'forwards':1},'blanketing':{'the':1},'non-existence':{'they':1},'rejection':{'of':1},'casein':{'which':1},'detachable':{'electrons':1},'generating':{'strong':1},'lungbooks':{'.':1},'planet':{'and':3,'on':1,'from':1,'around':1,'turns':1,'is':3,'after':1,'neptune':1,'but':2,'.':4,'will':1,'to':2,'s':1,'so':1,'always':1,'venus':2,'might':1,'the':1},'fitter':{'folk':1},'exploration':{'of':2},'planes':{'.':1},'water-bag':{'over':1},'groove':{'.':1},'sea-urchin':{'s':2,'which':1},'recognition':{'among':1,'of':2},'sort':{'and':1,'of':28,'when':1,'at':1,'may':1},'constant':{'interchange':1,'movement.':1,'temporary':1,'temperature':1,'state':2,'able':1,'spectrum':1,'effect':1,'amount':1,'in':1,'movement':1},'punnett':{'that':1},'expedition':{'1873-6':1},'metal':{'tags':1,'uranium':1,'globe':1,'that':1,'ages':1,'to':1,'ages.':1,'displays':1,'the':1,'vapour':1,'is':1,'vapours':1},'scarlet':{'solar':2},'single':{'word':2,'cubic':1,'molecule':1,'young':1,'feature':1,'cell':2,'prism':1,'electron':1,'grain':4,'gramme':1,'leaf':1,'atoms':1,'cell--a':1},'clever':{'synthetic':1,'associations':1,'dwarf':1,'things':2,'dog':2,'as':4,'in':1,'creatures':1},'curl':{'of':1},'dragging':{'effect':1},'prevail':{'.':1},'brethren':{'by':1},'corners':{'being':1,'of':3,'in':1},'biology.':{'the':1},'dimmed':{'by':1},'teemed':{'with':1},'confine':{'ourselves':1},'explaining':{'a':1,'positive':2,'the':1},'best--':{'a':1},'accidental':{'introductions':1,'discovery':1},'neck.':{'illustration':1},'heir':{'is':1},'surface--before':{'in':1},'prepared':{'chemical':1,'the':1,'spectrum':1},'lively.':{'illustration':1},'restoration':{'of':1,'by':3,'modelled':6,'shows':1},'relatives.':{'illustration':1},'utterly':{'dependent':1,'extinct':1,'beyond':1,'artificial':1},'fishes':{'and':5,'emerge':1,'appeared':1,'is':1,'191':1,'it':1,'as':1,'are':2,'in':2,'moreover':1,'saw':1,'before':1,'perhaps':1,'pay':1,'there':2,'had':1,'.':5,'to':2,'much':1,'which':3,'crustaceans':2,'probably':1,'was':1,'do':1,'we':1,'utilise':1,'that':1,'becomes':1,'males':1,'120':1,'cannot':1,'fishes':1,'such':1,'hold':1,'continued':1,'a':1,'like':3,'these':1,'of':1,'could':1,'will':1,'near':2,'were':3,'the':3},'stoppages':{'register':1},'desert':{'where':1},'worsted':{'instinctive':1,'mistake':1},'implies':{'a':2,'ability':1,'that':2,'rather':1,'certain':1,'becoming':1,'an':1,'complexity':1,'if':1},'vehicles':{'of':2},'speculations':{'.':1},'responded':{'to':1},'ascertained':{'is':1},'unhatched':{'crocodile':1,'or':1},'presenting':{'the':1},'ignoramus':{':':1},'failures':{'notably':1,'which':2,'that':1},'ready-made':{'capacities':1,'centres':1,'responses':1,'cleverness':1,'or':2},'tube':{'and':3,'a':1,'fertilises':1,'that':1,'of':1,'began':2,'258':1,'.':5,'bringing':1,'s':1,'as':1,'are':1,'which':1,'leading':1,'from':1,';':1,'with':1,'the':2,'is':1,'at':1},'discards':{'when':1},'tombs':{'that':1},'commoner':{'still':1,'sight':1},'telescope--the':{'largest':1},'served':{'as':3,'for':1,'an':1},'intricate':{'canal':1,'colony':2,'branches':1},'vicious':{'circle':1,'snaps':1},'disintegration':{'or':1,'that':1,'of':3,'.':1,'vital':1,'proceeds':1},'interlock':{'preventing':1},'compose':{'atoms':1},'peanut':{'and':1},'literary':{'archive':13},'blaze':{'of':1,'had':1,'means':1},'masculine':{'and':3,'features':1},'weather':{'conditions':1,'comes':1,'.':3},'gravel':{'and':1,'by':1,'.':1},'coal-field':{'.':1},'little-brain':{'type':5},'stupefying':{'effect':1},'random':{'.':1},'presently':{'the':2,'recognised':1,'what':1,'.':2},'listeth':{'and':1},'time-recording':{'machine':1},'putting':{'food':1,'themselves':1,'two':2},'aerolite.':{'sec':1},'intelligence--of':{'putting':1},'arrange':{'a':1,'themselves':1,'the':1},'severely':{'alone':1},'origin.':{'the':1,'we':1,'none':1,'7':1},'diverging':{'towards':2,'from':1},'shock':{'and':1,'or':1},'mottled':{'brown':1,'appearance':1},'penguins':{'come':1,'are':3},'murrayi':{'and':1},'believed.':{'sec':1},'unsatisfied':{'tendency':1},'orohippus':{'a':1,';':1},'bleeding':{'a':1},'crow':{'and':1,';':1},'other.':{'the':1,'there':1},'crop':{'of':2,'up--a':1,'up':2},'rivers':{'and':4,'from':1,'of':2,'but':1,'.':4,'to':1,'as':1,'in':2,'with':1,'or':1},'frog-mouth':{'sleeps':1},'insertion':{'of':2},'exuberant':{'radiation':1},'laws.':{'the':1},'nests':{'on':2,'or':1,'swaying':1},'pale-white':{'belt':1},'zest':{'with':1,'.':1},'giving':{'condensed':1,'animals':2,'these':1,'rise':4,'up':1,'us':1,'an':1,'birth':1,'off':2,'the':2,'out':1},'assisted':{'the':1},'fat':{'below':1,'.':1},'habituation':{'the':1},'paddle':{'of':1,'which':1},'access':{'to':10},'away--you':{'may':1},'crossed':{'by':1},'3a':{'mesohippus':1},'exercise':{'fifty-four':1},'rhodesian':{'cave-man':1,'man':4},'beasts':{'of':1,'have':1},'works--the':{'furnishings':1},'pelage':{'than':1},'outlying':{'electrons':3},'nimble':{'and':1},'river.':{'2':1},'intercept':{'some':1},'sink':{'and':1,'from':1,'away':1,'down':1,'to':3,'in':1,'beyond':1},'others':{'likewise':1,'as':2,'are':3,'have':2,'in':3,'rapidly':1,'for':1,'there':1,'.':4,'to':1,'which':1,'regard':1,'that':2,'read':1,'who':1,'such':1,'worked':1,'like':4,'thought':1,'suggests':1,'remain':1,'were':2,'at':1,'the':1,'weaves':1,'or':1,'climbers':1},'tremor':{'it':1,'.':1},'safer':{'to':1},'implicit':{'in':2},'widening':{'spread':1},'respiration':{'and':1,'than':1},'stalks':{'a':1,'which':1},'broken':{'and':2,'down':2,'off':2,'shells':1,'up':6,'.':1,'past':1,'their':1,'hill':2,'empties':1},'33':{'photo':2},'32':{'a':1,'comet':1,'600':1},'31':{'15':1,'735':1,'vast':1},'30':{'000-50':1,'1885':1,'000':2,'days':1},'37':{'photo':2},'alaska':{'and':1},'35':{'feet':1,'tons.':1,'000':1},'redbreast':{'and':1},'wasplike':{'which':1},'climb':{'on':1,'the':1,'up':1},'tubercles':{'on':1},'composed':{'of':13,'.':1},'named':{'coronium.':1,'the':1,'darwin':1,'20417.txt':1,'brown':1},'land-crab':{'birgus':1},'67.2':{'0.62':1},'sculling':{'and':1},'vulcanite':{'and':1},'decrease':{'of':1,'until':2,'in':1},'names':{'in':1},'oval':{'and':1,'than':1,'.':1},'tap':{'this':2},'lime':{'the':1,'64':1},'links':{'and':1,'to':1,'or':1},'readable':{'by':1,'form':1},'cretaceous':{'white':1,'there':1,'strata':1,'era':1,'period':2},'themselves':{'nearest':1,'into':3,'pass':1,'as':1,'are':3,'have':1,'in':6,'go':1,'if':1,'from':1,'.':5,'to':1,'adequate':1,'traceable':1,'then':1,'we':1,'very':1,'sufficient':1,'affording':1,'by':3,'whenever':1,'of':1,'up':1,'spontaneously':1,'unmistakably':1,'so':1,'energetically':1},'pre-arrangements':{'of':2,'we':1},'oily':{'water':1},'excitedly':{'.':1},'engender':{'where':1},'ancestral.':{'the':1},'myriads':{'of':1},'magnesium.':{'illustration':1},'proton':{'.':1},'train':{'travelling':1,'.':1},'indifferent':{'or':1},'batesian':{'after':1},'harvest':{'of':1,'at':1,'field':1},'elbow-room':{'for':1},'hints':{'of':1},'swooping':{'gull':1,'leaps':1,'87':1},'account':{'of':4,'has':1,'for':8},'understanding.':{'for':1},'f':{'.':7},'crickets':{'and':2},'pelicans':{'and':1},'non-radiant':{'matter':1},'closing':{'of':1,'words':2},'continuity':{'of':1},'experiential':{'learning.':1},'violence':{'.':1},'instinct--a':{'useful':1},'e.g.':{'nitrates':1},'proportions':{'on':2,'for':1},'reconstructed':{'from':2},'renewed':{'our':1},'mixture':{'of':2},'water.':{'the':2,'illustration':3,'in':1},'bones':{'and':2,'e.g':1,'of':2,'some':1,'.':1,'running':1,'slowly':1},'native':{'of':1},'daring':{'operations':1,'of':1},'democracy':{'.':1},'noises':{'does':1},'holds':{'a':1,'also':1,'its':1,'together':1,'in':1},'regions':{'of':3,'to-day.':1,'are':1,'or':1,'empty':1,'farther':1},'flood.':{'there':1,'sec':1},'lamp':{'and':1},'proceeded':{'far':1,'further':1},'called--it':{'will':1},'furnace':{'the':1,'like':1},'imprints':{'from':1},'says:':{'all':1,'they':1},'watery':{'with':1},'dull-red':{'heat':1},'gill-clefts':{'are':1,'they':1},'waters':{'and':1,'that':1,'afford':1,'of':5,'allows':1,'.':4,'under':2,'covered':2,'the':1,'beyond':1,'where':1,'quite':1},'philosophy':{'of':1},'collection':{'will':1,'of':4,'so':1,'are':1,'.':1},'mixed':{';':1,'all':1,'together':1},'them--simple':{'one-celled':1},'united':{'states':13,'states.':1},'preferred':{'to':1},'multiplication':{'of':4,'into':1,'takes':1,'covers':1},'soup-plate':{'but':1},'primers':{'beginning':1},'chasing':{'mates':1},'tethering':{'the':1},'bind':{'animals':1,'long':1},'lines':{'and':2,'it':1,'replace':1,'not':1,'as':1,'are':3,'have':1,'in':2,'birds':1,'would':1,'.':3,'to':2,'which':1,'drawn':1,'we':1,'they':1,'fishes':1,'he':1,'on':2,'of':7,'will':1,'placed':1,'became':1,'the':2},'correspond':{'to':4},'chief':{'among':1,'use':1,'kinds':1,'scientific':1,'importance':1,'executive':1,'theories':1,'four':1,'plains':2,'reason':1,'classes':2,'stocks':1},'counterbalances':{'its':1},'stony':{'meteorite':1},'subsequently':{'fed.':1,'ignored':1},'lined':{'with':2},'furnish':{'a':1,'the':2,'data':1},'motions.':{'sec':1},'africans':{'straight-haired':1},'lens.':{'a':1},'symbols':{'of':1,'help':1},'alacrity':{'towards':1,'with':1},'horns':{'but':1},'agricultural':{'pioneers':1},'bunch':{'of':4},'industries':{'of':1,'.':1},'bridges':{'the':1,'were':1,'he':1},'negotiated':{'he':1},'le':{'verrier':1,'bon':1},'lb':{'.':1},'la':{'chapelle-aux-saints':2},'labor':{'in':1},'age':{'and':4,'just':1,'it':1,'as':1,'in':5,'whereas':1,'seems':1,'.':4,'to':3,'which':1,';':2,'has':1,'was':1,'more':1,'that':1,'after':2,'amphibians':1,'by':1,'dates':1,'of':13,'could':1,'lasted':1,'without':1,'the':2},'squatting':{'figure':1},'marsh':{'and':2,'birds.':1,'.':1},'bridged':{'very':1},'diverts':{'.':1},'junction':{'of':1},'greater':{'distance':2,'distorting':1,'plasticity':1,'intelligence':1,'in':1,'antiquity--perhaps':1,'celandine':1,'resistance':1,'possibilities':1,'rate':1,'part':2,'mass':1,'compactness':1,'interest':2,'activity':1,'concentration':1,'than':7,'accuracy':1},'descendants':{'as':1,'to-day':1,'.':1},'faunas':{'of':1},'dam':{'of':1,'.':1},'gauging':{'their':1},'cock-paidle':{'probably':1,'or':1},'phagocytes':{'may':1,'which':1},'accumulates':{'a':1},'faunal':{'drift':1},'day':{'and':10,'is':3,'it':2,'comprised':1,'as':1,'are':1,'in':1,'seem':1,'from':1,'for':1,'rather':1,'when':3,'long':1,'.':7,'also':1,'therefore':1,'covered':1,';':1,'was':1,'we':2,'alighting':1,'becoming':2,'sink':1,'one':1,'by':2,'he':1,'of':1,'equal':2,'were':1,'the':2},'6.--solar':{'prominences':1},'least.':{'these':1},'radiant':{'heat':2,'matter.':1,'than':1,'element':1},'tenanted':{'and':1,'the':1,'to-day':1,'by':1},'identified':{'an':1,'by':2,'.':1},'blazing':{'star':1},'exploring':{'new':1,'the':1,'with':1,'habit':1},'slipping':{'down':2,'back':1},'harness':{'this':1,'and':1,'the':1},'integumentary':{'structures':1},'references':{'to':2},'giants.':{'thus':1},'jasper':{'did':1,'studied':1},'movement-controlling':{'organ':1},'vestigial':{'muscles':1,'structures':4,'third':1},'attendant':{'on':1,'field':1},'pivot':{'the':1,'through':2},'slumped':{'together':1},'tubular':{'sea-anemone':1,'shells':1},'suctorial':{'mouth':1,'tube-feet':1},'kids':{'and':1,'foals':1},'inch':{'and':2,'less':1,'of':3,'long':2,'.':6,'at':1,'in':7,'thick':3,'one':2,'or':1,'thick.':1},'wholly':{'of':1},'mate':{'and':1,'kith':1,'s':1,'has':1},'oriental':{'race':1},'technically':{'this':1,'called':1},'red':{'and':4,'fife':1,'spring':1,'deer':1,'yellow':1,'disc':1,'at':1,'tumultuous':1,'mouth.':1,'giant':1,'end':1,'sandstone':2,'.':3,'glowing':1,'stars':3,'orange':1,'star':3,'on':1,'prominences':1,'spot':1,'seaweeds':1,'ones':1,'blood':1,'waves':1,'fife--a':1,'card':1,'a':1,'worsted':2,'flames':3,'glory':1,'light':1,'region':1,'will':1,'calcutta':2,'the':1,'tinge':1,'or':3,'seaweed':1},'approached':{'too':1},'many-celled':{'wheel':1,'animals':1,'organism':1,'animal':1,'creature':1},'lizzie':{'had':1,'the':1,'never':1,'was':2,'s':1},'others--which':{'is':1},'discover':{'a':1,'that':2,'this':1,'differences':1,'some':3,'their':1,'how':1,'in':1,'the':2},'fourteen':{'hours':1,'days':2,'or':1},'coronium.':{'measuring':1,'we':1},'approaches':{'to':1,'the':3},'electricity--electric':{'current--the':1},'trends':{'of':1},'qui':{'vive':1},'likelihood':{'far':1,'the':2},'young--a':{'use':1},'backwards':{'and':1,'we':3,'for':1,'over':1,'when':1,'it':1},'yard':{'in':1},'mortar':{'of':2},'chicken':{'procellaria':2},'allied':{'to':4},'barriers':{'.':1,'must':1},'retain':{'a':1,'their':1},'mammal-like':{'and':1},'empire.':{'he':1},'south':{'sir':1,'poles.':1,'of':4,'africa.':1,'american':3,'pacific':1,'.':3,'pole':1,'poles':1,'in':1,'america':4},'predominate':{'over':1},'complete.':{'illustration':1},'rudely':{'dressed':1,'shaken':1},'finest':{'triumphs':1,'measurements':1,'exhibition':1,'gold':1},'braced':{'against':1},'investigated.':{'ether':1},'condensed;':{'but':1},'food-plants':{'of':1},'improvements':{'and':1,'like':1,'in':2},'sacs':{'which':1},'reached':{'a':1,'then':1,'about':1,'animals':1,'this':1,'their':1,'nearly':1,'immediately':1,'the':4,'its':1},'michelson':{'and':1},'humblest':{'living':2},'ancient':{'copper':1,'type.':1,'seas':3,'astronomer':1,'seashore':1,'human':1,'extinct':1,'times':1,'skeletons':1,'hunters':1,'crust':1,'peoples':1,'mediaeval':1,'life':1,'amphibians':1,'days.':1,'sea.':1,'than':1,'types':4,'days':2,'civilisations':2,'rocks':1,'beds':1},'sadly':{'impressed':1},'monkey':{'and':1,'has':1,'b':2,'that':1,'of':1,'there':1,'it':1,'an':1,'how':1,'s':3,'which':1,';':1,'.':2,'yet':1,'as':1},'guiana':{'82':1,'the':1},'all--the':{'atom':1},'ripples':{'measuring':1,'in':1},'hotter.':{'it':1},'nebular':{'theory.':2,'theory':2,'region':2,'theory--spiral':1,'gases':1,'hypothesis':4,'mass':1},'intermediate':{'positions':1,'layer':1,'between':1},'sky--this':{'we':1},'anatomises':{'the':1},'completed':{'a':1,'her':1},'acquire':{'kinetic':1,'the':1},'negro':{'and':1},'device--more':{'reflex':1},'environmental':{'sometimes':1},'slopes':{'down':1,'of':1},'plumage':{'like':1,'of':1,'is':1,'are':1,'makes':2,'or':1},'bodyguard':{'of':1},'furnishings':{'of':2},'kant':{'had':1},'shrapnel':{'which':1},'brusque':{'variations':2},'lizard-like':{'tail.':1,'tail':1},'depends':{'on':10,'all':1,'partly':1,'upon':4,'.':2,'to':1},'heavens.':{'of':1},'light':{'and':12,'emerging':1,'besides':1,'previously':1,'penetrates':1,'is':14,'coming':1,'reaches':1,'an':1,'visible':1,'as':1,'rings.':1,'are':4,'in':3,'consists':2,'our':1,'passes':2,'differ':2,'rays':1,'from':10,'tread':1,'would':1,'electricity':1,'travel':1,'there':1,'wave-lengths.':1,'sunlight':1,'.':14,'to':3,'returns':1,'production':1,'which':7,'according':1,'travelling':1,'has':3,'was':1,'into':1,'red':1,'more':1,'body':2,'then':1,'we':1,'283':1,'travelled':1,'that':4,'may':1,'becomes':1,'gathered':1,'emitted':1,'took':1,'but':2,'falls':2,'magnetism':1,'will':3,'falling':1,'waves':2,'i.e':1,'with':1,';':4,'upwards':1,'a':1,'on':9,'made':1,'takes':3,'of':20,'radiant':1,'depends':1,'against':1,'reduced':1,'travels':2,'without':2,'so':1,'can':1,'many':1,'the':4,'or':1,'comes':1},'lurching':{'movements':1},'flashes':{'of':1},'anthropologist':{'professor':1},'imaginative':{'range':1,'or':1,'minds':1},'involution':{'but':1},'wood-cock':{'which':1},'curves':{'of':1},'comfortable':{'far':1,'as':1},'tide':{'and':2,'the':2,'in':1,'or':1,'out':1},'corrupt':{'data':1},'comfortably':{'in':1},'astrophysical':{'observatory':3},'unlikely':{'that':2},'uganda':{'bug':1},'sporadic':{'and':1,'members':1},'throat':{'bulges':1},'curved':{'bodies.':1,'pillar':1,'on':1,'than':1,'fingers':1},'activity--that':{'of':1},'complete':{'and':1,'living':1,'proof':1,'stereoscopic':1,'reflection':1,'absorption':1,'.':2,'pace':1,'revolutions':1,'master':1,'fossil':1,'in':1,'one':1,'its':1,'change':1,'theory':2},'mic':{'.':1},'wits':{'and':1,';':1,'in':1,'when':1,'.':1},'gravity':{'pressure':1,'is':1,'.':1,'near':2,'the':1},'provokes':{'simple':1},'pectoral':{'fins':5,'muscles':1},'gliding':{'on':1,'from':2,'alligator-like':1,'one':1},'rediscovered':{'by':1},'jumna':{'doles':1},'unless':{'a':1,'we':2,'indeed':1,'there':2,'it':1,'they':1,'our':1,'the':3,'you':3},'trundles':{'about':1},'mathematician':{'leibnitz':1,'le':1,'can':2,'.':1},'mimics':{'they':1},'eight':{'large':1,'unbranched':1,'of':1,'months':1,'years':1,'feet':1,'sense-organs':1,'tons':1,'branched':1,'planets':2,'the':1},'peppered':{'moth':1},'cleverest':{'animals':1,'monkey':1},'sally':{'the':1,'some':1,'above':1},'plastic--a':{'generalised':1},'profoundest':{'of':1},'palaeolithic':{'and':1,'cave-men':2,'men':1,'culture':1,'peoples':1},'firelight':{'must':1},'inexorable':{'laws':1},'gullet':{'unbroken':1},'heartening':{'encouragement':1},'enthusiastic':{'.':1},'gather':{'to':1,'the':2,'round':1,'on':1},'request':{'of':1},'disease':{'and':1,'is':1,'after':1,'.':2},'animal--perhaps':{'the':1},'park.':{'profile':1,'side-view':1,'chimpanzee':3,'surface':1,'comparisons':1,'the':3},'artificially':{'and':1,'to':1,'it':1},'occasion':{'and':1,'on':1,'.':1,'suggested':1,'of':1},'normally':{'a':1,'concealed':1,'handed':1},'ten-armed':{'cuttlefish':2},'true.':{'if':1},'area.':{'swimmers':1,'it':1},'selection':{'of':3,'advantage':1},'kith':{'and':1},'text':{'to':1,'emits':1,'.':2},'supported':{'on':1,'in':1,'like':1,'by':1},'braking':{'action':1},'pinhead':{'brain':1},'continually':{'added':1,'being':2,'recuperate':1,'worn':1,'tends':1,'changing':1,'passing':1,'travelling':3},'thicker':{'fur':1},'staff':{'shows':1},'wear':{'and':1,'any':2},'knowledge':{'and':1,'be':1,'means':2,'respecting':1,'advances':1,'is':1,'there':1,'had':1,'it':1,'but':1,'.':2,'may':1,'that':2,'were':1,'extends':1,'of':13,'the':1,'has':1,'as':1,'more':1},'sparks':{'which':1},'scorpion':{'we':1},'luminescent':{'and':1,'animals':1},'body-making.':{'in':1},'insectivores':{'not':1,'and':1,'including':1},'fatiguing':{'exertions':1},'emitting':{'light':1,'rays':1},'wild.':{'two':1},'hand.':{'attempts':1,'cross-fertilisation':1,'half':1},'inferior':{'either':1},'equilibrium':{'positions':1,'has':1,'results':1,'otherwise':1},'photographs':{'we':1,'show':2,'of':1,'.':1,'fig':1,'taken':2,'by':1,'figs':1},'coin--smaller':{'than':1},'exceptional':{'and':1,'spring':1,'auroral':1,'in':1,'cases':2,'conditions':1},'beat':{'a':1,'things':1,'it':1},'photography':{'and':1},'bear':{'and':2,'on':1,'of':2,'straight':1,'illustration':1,'to':1,'numerous':1,'in':3,'the':1,'was':1},'perfection':{';':1,'is':1,'in':1,'by':1,'.':1},'swiftest':{'flywheel':1},'stigma':{'the':1},'striped':{'tiger':1,'muscles':1,'muscle':1},'halo':{'surrounding':1,'there':1,'such':1},'areas':{'and':1,'differ':1,'land':1,'corresponding':1,'was':1,'of':1,'.':1,'to':1,'at':1,'known':1,'where':1,'or':1},'crabs':{'and':1,'are':1,'that':1},'egg-laying':{'is':1,'.':1},'caves':{'unsunned':1,'in':1},'organ':{'of':3,'is':1,'called':1,'for':1,'.':1},'pglaf.org':{'fundraising':1,'for':1,'section':1,'.':1,'while':1,'donate':1},'fixes':{'a':1,'to':1,'sea-anemones':1},'shore-animals':{';':1,'e.g':1,'which':1,'have':1,'.':1},'eyebrow':{'ridges.':1,'ridges':6},'saturates':{'through':1},'excesses':{'of':1},'light--is':{'the':1},'gibson':{'gives':1},'cave-hyaena':{'mammoth':1},'farthest':{'out':1},'exists':{'because':1,'there':1,'only':1,'as':1,'in':2,'the':1},'universe--the':{'evolution':1,'solar':2},'national':{'physical':2},'flapped':{'very':1},'inextricably':{'interwoven':1},'carnivores':{'and':1},'intensity':{'of':4},'cenozoic':{'making':1,'began':1,'era':1,'or':1,'eras':1},'enhanced':{'by':2},'greece':{'and':2},'ruse':{'succeeded':1},'36.0':{'0.24':1},'shallows':{'.':1},'phases':{'of':1},'pedigree':{'of':1,'the':2,'.':2,'is':1,'must':1},'apparently':{'clever':1,'red-hot':1,'unconscious':1,'simple':1,'inexhaustible':1,'instantaneous':1,'in':1,'served':1,'you':1,'sluggish':1,'inevitable':1},'nebula':{'and':1,'what':1,'round':1,'march':2,'although':1,'of':1,'57':1,'we':1,'but':1,'.':2,'seen':2,'to':7,'need':1,'which':1,'in':8,'it':1,'revolving':1,'has':2,'laplace':1,'is':4},'difficulties':{'and':5,'may':1,'of':5,'is':1,'in':1,'when':1,'.':1,'are':3,'have':1,'were':1,'the':1},'routine':{'and':1,'cannot':1,'is':3,'.':1,'became':1,'so':2,'activity':1,'instinctive':1,'has':1,'metabolism':1},'progress':{'we':1,'towards':2,'unless':1,'demands.':1,'many':1,'is':1,'of':4,'.':5,'depends':1,'have':1,'in':3,';':1,'has':1,'was':1},'boundary':{'line':1,'lines':1},'janes':{'leonard':2},'various':{'distances':1,'methods':2,'elements.':1,'conditions.':1,'proportions':1,'intervals':1,'human':1,'subtle':1,'racial':1,'classes':1,'physical':1,'layers':1,'forms':5,'concrete':1,'ways':1,'interesting':1,'flying':1,'ways.':1,'colours':2,'parts':1,'electrical':1,'open-sea':1,'kinds':4,'bolts':1,'mammals':1,'atoms':1,'races':1,'fishes':1,'shore-haunts.':1,'stocks':1,'articles':1,'processes':1,'places':1,'departments':1,'theories':1,'lengths':2,'experiments':1,'formats':1,'stages':1,'other':1},'reproduced':{'in':3,'from':7,'below.':1,'by':18},'cauliflower':{'sticking':1,'and':1},'superior':{'to':1},'emitted':{'by':3},'deliver':{'insects':1},'willing':{'to':2,'is':1},'nightfall':{'hippolyte':1},'exist.':{'there':1,'some':1},'guiding':{'his':2},'sharply':{'away':1},'asunder':{'the':1},'freely':{'and':1,'available':1,'sharing':1,'distributed':1,'as':1,'suspended.':1,'shared':1,'round':1},'taking':{'a':1,'longer':1,'advantage':2,'it':1,'running':1,'place':2,'5':1,'the':2,'care':1},'equal':{'weight':1,'pieces':1,'to':7,'length':1,'perfection':1,'.':1},'attributed':{'this':1,'to':1},'pulp':{'.':1},'flesh-eating':{'and':1},'sexes':{'and':1,'wander':1},'wringing':{'the':1},'swim':{'much':1,'at':1,'against':1,'for':1},'conquered':{'and':1,'the':3,'one':1},'swallow':{'a':1},'temporal':{'or':1},'glorious':{'failures':1,'display':1},'otherwise':{'would':1,'there':1,'when':1,'quite':1,'the':3,'called':1},'basins':{':':1,'.':1},'acorn-shell':{'and':1},'heritable':{'novelties':1},'deflected':{'as':2},'unearthed':{'.':1},'pouring':{'floods':1,'out':2},'marett':{'r':1},'tremendous':{'energy':3,'movements':1,'question':1,'but':1,'movement':1},'everything--so':{'there':1},'muddy':{'feet':1,'precipitate':1},'copies':{'of':7},'armadillos':{'.':1},'migrate':{'about':1},'dogfish':{'have':1},'natans':{'stands':1},'curtain':{'of':1,'floating':1},'copied':{'and':1,'or':1},'sluggish.':{'animals':1},'home.':{'long':1},'herbage':{'fastening':1,'and':1,'by':1,'.':1},'composed.':{'the':1},'antlers':{'in':1},'arises':{'what':1,'from':1},'sex--emotions':{'of':1},'looked.':{'using':1},'essentially':{'a':1,'of':2,'the':1,'wrapped':1,'is--should':1},'assert':{'themselves':1},'finished':{'and':1},'angles':{'to':4,'which':1},'angler':{'of':1,'s':2},'fellow':{'short':1,'from':1},'food-canal':{'and':3,'a':1,'the':1,'muscular':1,'.':2},'arisen':{'as':1,'in':1,'from':1,'by':1,'.':1},'volunteer':{'support.':1},'homes':{'of':1,'from':1},'economised':{'reproduction':2},'splits':{'up':1},'article.':{'bibliography':1},'appearance':{'and':1,'we':1,'very':1,'of':5,'.':2,'habits':2,'cloaked':1,'which':1,'in':1},'value':{'.':1,'or':1,'in':1},'promotes':{'both':1},'dendrites':{'of':1},'amenity':{'.':1},'file':{'or':1,'should':1},'chaotic':{'molecular':1},'squid':{'in':2},'weighed':{'but':1},'arrangements':{'of':2,'for':1},'arabia':{'ceylon':1},'partner':{'s':1,'sea-anemones':2,'.':1},'tumbled':{'into':1},'watchful':{'mother':1},'physiologists':{'like':1},'locomotion;':{'new':1},'mid-europe':{'red':1},'jurassic.':{'for':1},'prognostications':{'as':1},'well-grown':{'fishes':1},'felted':{'together':1},'aquitania':{'is':1},'locomotion.':{'illustration':1},'twelfth':{'printing':1},'neolithic':{'age':1,'days':1,'community':1,'.':1,'culture':1,'men.':1,'times':1,'man':6},'material':{'and':2,'in':1,'which':4,'e.g':2,'things':2,'is':1,'of':2,'particles.':1,'particles':1,'studying':1,'aspect':1,'universe':5,'such':1,'throughout':2,'than':1,'resources':2},'soddy--as':{'any':1},'cubic':{'inch':2,'inches':2,'centimetre':2},'absent;':{'stars':1},'water-filled':{'quarry':1},'binoculars':{'is':1},'discredited':{'atomism.':1},'26.--a':{'spiral':1},'judgment':{'on':1},'buttonholes':{'at':1},'nevertheless':{'these':1,'all':1,'been':1,'master.':1},'pompilius':{'common':1},'weapon':{'on':1},'capella':{'49.4':1},'treacly':{'fluids':1},'thought':{'and':2,'even':1,'that':3,'of':2,'is':1,'it':1,'.':1,'to':1,'was':1,'they':1,'hydrogen':1},'exceedingly':{'small':2},'sets':{'of':3,'off':1,'up':1,'in':1},'comparisons':{'of':2},'wreckage':{'of':1},'arising':{'afresh':1},'latest':{'and':1,'measurements':1},'appropriately.':{'birds':1},'barking':{'down':1},'humdrum':{'non-plastic':1,'race':1},'executive':{'and':1},'domestic':{'pigeons':1,'rabbits':1,'dog':1},'harpy-eagle':{'216':1,'clean':1},'bivalves':{'and':1},'stored':{'may':1,'away':1,'up':2,'for':1},'books':{'may':1,'recommended':1,'now':1,'are':1,'.':1},'protecting':{'blanket':1,'them':1},'swimming-bells':{'and':1},'wrens--to':{'try':1},'one-toed':{'horse':1},'work.':{'1.e.4':1,'the':2,'there':1,'-':1,'first':1},'absorption':{'of':2,'was':1},'onward':{'.':1},'lake':{'and':1,'pond':1,'of':1,'constance':1,'city':1},'mathematically':{'satisfactory':1},'add':{'just':1},'work;':{'the':1},'slits':{'the':1},'spirals':{'present':1,'in':1},'warns':{'us':1},'280':{'wave':1,'in':1},'283':{'photo':1,'niagara':1},'282':{'the':2},'287':{'photo':2},'incarnations':{'and':1,'one':1},'resolved':{'into':1,'the':1,'in':1},'worlds':{'and':1,'in':3,'sec':1,'.':1},'hermonis':{'and':1},'refinements':{'are':1},'mutations':{'and':1,'then':1,'whatever':1},'royalty':{'fee':1,'payments':2},'98.8':{'arcturus':1},'elapses':{'between':1},'implements--knives':{'scrapers':1},'jupiter.':{'the':1},'audibly':{'when':1},'capacities':{'of':4,'work':1,'but':3,'are':1,'usually':1,';':1},'like':{'plaice':2,'deliberateness':1,'toads':1,'london':1,'fungas':1,'birds':1,'shuffling':1,'to':2,'insectivores':1,'very':1,'duckmole':1,'sandstones':1,'one':1,'minute':1,'patrick':1,'globe-fishes':1,'shapes':1,'sloths':1,'amoebae':1,'rats':2,'partridges':1,'sugars':1,'some':3,'sea-squirts':1,'jupiter':1,'our':5,'bark':1,'ourselves':1,'poisonous':1,'its':2,'asking':1,'trout':1,'volvox':1,'opening':1,'of':1,'carnivorous':1,'great':1,'flames':1,'many':1,'otters':1,'ants':1,'skunks':1,'chlorophyll':1,'house-flies':1,'mercury':1,'whales':1,'.':3,'white':1,'genesis':1,'pallas':1,'that':6,'centipedes':1,'coughing':1,'fountains':1,'glass':1,'those':1,'he':1,'this':2,'starts':1,'sea-anemones':1,'matter':4,'fallow':1,'silly':1,'were':1,'and':2,'rooks':1,'certain':1,'is':1,'it':2,'an':8,'as':1,'which':2,'skates':1,'but':1,'waves':1,'fishes':1,'ours.':1,'a':44,'wisps':1,'professor':2,'dog':1,'kipling':1,'so':1,'raindrops':1,'the':56,'brer':1},'success':{'and':1,'of':1,'is':1,'to':1,'as':1,'in':1,'has':1},'spiral.':{'thus':1,'but':1},'porous':{'like':1},'admitted':{'of':1,'that':5},'ozone':{';':1},'radio-active--then':{'we':1},'chick':{'does':1,'out':1},'works':{'and':1,'in':7,'its':1,'if':1,'even':1,'provided':1,'based':2,'harmless':1,'.':2,'to':1,'only':1,';':1,'unless':1,'that':2,'1.a':1,'from':1,'with':1,'by':2,'posted':1,'on':1,'possessed':1,'reports':1,'so':1,'mr':1,'calculated':1},'soft':{'food':1,'soil':1,'muddy':1,'tail':2,'.':1,'to':1,'enough':1,'parts':2,'moss':1,'browns':1,'silvery-looking':1,'abdomen--for':1},'heel':{'a':1,'of':2,'than':1},'italian':{'scientist':1},'accessible':{'by':1},'simple.':{'the':1},'propel':{'our':1},'alive':{'.':1,'at':1,'are':1},'hair':{'and':1,'is':1,'woolly-haired':1,'in':1,'the':1,';':1},'convey':{'an':1},'convex':{'curves':1},'proper':{'answer':1,'proportions':2,'number':1,'way':1,'time':1},'happens':{'for':1,'that':2,'certain':1,'is':1,'.':2,'in':1},'0.24':{'3030':1},'students':{'of':1},'masked':{'their':1,'by':2},'economical':{'reduction':1},'assuming':{'reasonably':1},'results.':{'fog':1,'but':1},'mind-body':{'at':1},'snuggle':{'under':1},'overcharged':{'with':1},'manifesting':{'itself':1},'noise':{'of':1,'.':1},'slight':{'changes':1,'as':1,'improvements':1,'keel':1,'fluttering':1,'clouding':1},'ever-lengthening':{'tail':1},'combative':{'creature':1},'stellar':{'universe.':1,'universe--the':1,'spectra':1,'system':1,'universe':5,'universes':1,'astronomy':1},'crossing':{'the':1},'host':{'of':1,'is':2,'s':1,'for':1,'.':1},'although':{'we':5,'modern':1,'thirsty':1,'all':1,'there':2,'great':1,'it':1,'at':1,'they':1,'mr':1,'small':2,'our':1,'the':8},'worthy':{'of':1},'periodically':{';':1,'bursts':1,'in':1,'pass':1},'christened':{'coronium.':1,'them':1,'electrons':1},'about':{'among':2,'seven':2,'because':1,'twenty-one':1,'ten':1,'on':3,'the':47,'energy':1,'within':1,'all':1,'10':1,'two':6,'60':1,'as':1,'two-thousandths':1,'sec':1,'35':1,'in':3,'our':2,'shooting':1,'its':1,'sun-spots':2,'six':3,'for':1,'eleven':1,'ways':1,'twenty':2,'there':1,'forty':1,'40':1,'.':2,'1':3,'their':1,'3':1,'5':3,'4':1,'which':3,'9':3,'electrons':1,'more':1,'twenty-five':1,'thirty-two':1,'500':1,'equilibrium':1,'life':2,'2-1':1,'an':2,'to':1,'580':1,'that':3,'very':1,'constantly':1,'after':1,'eighty':1,'new':1,'it':1,'them':1,'two-thirds':1,'variable':1,'100':1,'one':5,'with':3,'by':4,'elevations':1,'a':15,'four':2,'12':1,'48':1,'thirty':1,'twice':1,'we':2,'1842':1,'56':1,'half':2,'us':1,'project':2,'these':2,'donations':2,'three':5,'fundamental':1,'things':1,'nine':1,'800':1,'fifty':3},'quills':{'.':1},'branch-gripping':{'member':1,'.':1},'electron--the':{'electron':1},'certainty':{'and':1,'as':1,'has':1},'introduces':{'into':1},'preen':{'gland':1},'avoided.':{'when':1},'rock-record':{'which':1},'introduced':{'perhaps':1,'into':1,'by':1},'fitnesses':{'have':1},'ways':{'and':2,'we':1,'that':1,'of':10,'.':4,'as':1,'including':1,'in':7},'marshes':{'and':1,'fed':1,'resounded':1,'were':1},'dubois':{'in':1},'sense-organs':{'the':1,'round':1},'rhythmical':{'rise':1},'billions':{'of':3},'chemists':{'and':1,'said':1,'of':1,'who':1,'should':1,'physicists':1,'.':1},'guard':{'over':2,'is':1,'against':1},'female':{'or':1,'with':1,'where':1,'is':1,'only':1,'covers':1,'.':1,'s':1,'paper':1,'figures':1,'makes':1,'in':1,'carries':1,'stickleback':2,'yucca':1,'side':1,'at':1},'quickly':{'from':1,'that':1,'contracting':2,'as':1,'recognised':1,'moving':1,'in':1,'coiled':1,'than':2},'kallima':{'inachis':2,'conspicuously':1},'cross-fertilisation':{'of':1,'is':2},'minute.':{'in':1},'punics':{'and':1},'sticklebacks':{'are':1,'learned':1,'were':1,'live':1,'in':1},'ridge':{'for':1},'mazy':{'passages':1},'elastic':{'solid':1,'wings':1},'rushed':{'into':1},'outline':{'we':1,'like':1,'of':17,'is':2,'it':1,'will':1,'where':1,'its':1},'condense':{'it':1,'round':1},'rushes':{'on':1,'through':1,'round':1},'bees':{'and':4,'may':1,'richly':1,'which':1,';':1,'by':1},'development':{'and':1,'has':1,'often':1,'for':1,'of':18,'leaves':1,'should':1,'certain':2,'which':1,'in':1,'.':4,'is':2,'man':1},'biggest':{'gulf':1,'fact':1},'maze':{'and':1,'a':1,'in':1,'by':1,'.':1},'duffus.':{'cuckoo-spit':1,'chimpanzee':1},'woodpecker':{'inserted':1,'hammering':2},'mcgregor':{'from':2},'but':{'all':3,'particularly':1,'among':1,'able':1,'move':1,'worms':1,'bright':1,'its':4,'before':1,'also':1,'electricity':1,'agile':1,'enough':1,'evidences':1,'to':5,'only':3,'has':1,'giants':1,'eventually':2,'very':1,'sooner':1,'quickness':1,'they':19,'new':1,'not':5,'during':1,'now':2,'necessary':1,'like':1,'profound':1,'light-waves':1,'these':9,'she':2,'each':1,'because':1,'farthest':1,'some':4,'imply':1,'are':2,'our':2,'best':1,'even':4,'what':7,'for':2,'since':2,'remain':3,'birds':1,'behind':1,'difficulties':1,'between':1,'probably':1,'millions':1,'movement':1,'we':23,'eminently':1,'nature':1,'little':1,'here':2,'although':3,'others':1,'along':1,'contraction':1,'on':2,'about':1,'many':3,'omit':1,'usually':1,'adapted':1,'naturalists':1,'copper':1,'contains':1,'besides':1,'one':4,'learning':1,'your':1,'often':3,'startling':1,'given':1,'air-sacs':1,'would':1,'few':1,'positive':1,'devouring':1,'there':46,'three':1,'their':3,'was':3,'more':1,'survives':1,'lived':1,'that':4,'blindly':1,'careful':1,'with':1,'those':1,'he':6,'plants':1,'none':2,'whether':1,'science':2,'this':11,'will':2,'while':3,'of':2,'constant':1,'remained':1,'is':1,'it':74,'an':2,'as':7,'at':2,'in':16,'if':11,'different':1,'no':4,'perhaps':5,'when':10,'astronomers':1,'how':3,'another':1,'other':1,'which':2,'you':1,'relatively':1,'inconceivably':1,'ultimately':1,'most':2,'why':2,'man':5,'a':10,'expert':1,'slightly':1,'splendid':1,'enter':1,'the':90},'reminds':{'us':1},'repeated':{'trials':1,'over':1,'until':1,'but':1,'many':1},'billion.':{'illustration':1},'plague':{'of':1},'bug':{'closely':1,'actually':1},'versatile':{'life':1},'partially':{'eclipsed.':1,'reappeared':1,'collided':1,'landlocked':1,'dried-up':1},'constitute':{'light':1,'as':1,'heat':1,'matter':1},'wise':{'and':1,'saying':1,'enough':1},'glory':{'and':1,'that':1},'wish':{'to':1,'however':1,'they':1},'j':{'.':98},'variations':{'and':2,'often':1,'that':1,'are':4,'which':1,'in':3,'or':3},'lynx':{'and':1,'the':2},'minutes':{'and':1,'saving':1,'for':1,'hard':1,'.':5,'holding':1,'in':1,'the':1,';':1,'before':1},'squat':{';':1,'motionless':2},'supreme':{'synthesis':1},'rabbits':{'and':2,';':1,'.':1},'pin':{'s':2},'swimmers--for':{'there':1},'transfused':{'into':2},'reptiles.':{'triassic':1,'carboniferous':1,'permian':1,'illustration':1,'in':1},'well-defined':{'and':1,'hereditary':1},'periods':{'of':4,'but':1,'to':1,'in':1,'the':1,'if':1},'141.5':{'1.88':1},'our':{'planetary':1,'atmosphere':5,'boyhood':1,'flesh':1,'rooms':1,'human':1,'skin':1,'earth':6,'admiration.':1,'web':1,'knowledge':11,'conclusions':1,'energies':1,'dipper':1,'consideration':1,'views':3,'very':1,'oceans':1,'photograph':1,'dark':1,'coal-measures':1,'hands':1,'foot':1,'coal-fields':1,'problems.':1,'solid':1,'race':2,'common':2,'small':1,'telegraphic':1,'bone':1,'methods':1,'colossal':1,'legacy':1,'blues':2,'sun':8,'artificial':1,'moon':2,'finger':3,'new':1,'email':1,'universe.':2,'belief':1,'power':1,'attention':1,'craters':1,'stellar':2,'heads':1,'estimate':1,'cities':1,'hours':1,'great':2,'central':1,'water-oceans.':1,'universe':7,'days':2,'forbears':1,'physiological':1,'survey':1,'steadily':1,'successors':1,'whole':1,'first':2,'own':15,'point':1,'instruments':2,'primary':1,'system':6,'feet':1,'elder':1,'cultivated':1,'total':1,'kind':1,'mental':1,'little':1,'eye':1,'flying':1,'charts':1,'wonderful':2,'way':1,'time':1,'scope':1,'sort':1,'eyes':4,'shell':1,'gas':1,'appreciation':1,'solar':9,'present':1,'apprehension':1,'admiration':1,'comprehension.':1,'imagination.':1,'universe--astronomical':1,'future':1,'exploration':1,'life.':1,'problem':1,'average':1,'mud-fishes':1,'frogs':3,'modern':3,'mind':2,'metals':1,'general':1,'sudden':1,'experience':2,'orchards':1,'domesticated':1,'terrestrial':1,'ancestors':1,'winter':1,'conclusions.':1,'ideas':1,'food':1,'conceptions':1,'largest':1,'ordinary':2,'civilisation':1,'bells':1,'investigations':1,'senses':4,'milky':1,'hand':1,'shores':1,'most':2,'purpose':1,'predecessors':1,'age':1,'coal':1,'chief':1,'greatest':1,'trains':2},'paraguay':{'and':1},'mysteriously':{'regular':1,'from':2},'pit':{'the':1,'whence':1},'proceeds':{'to':1,'what':1,'the':1},'48':{'the':1,'ounces':1},'49':{'photo':1,'by':1},'corporation':{'organized':1},'44':{'photo':1},'fore-arm':{';':2,'.':1},'fruit-laden':{'branch':1},'detail':{'to':1,'so':1,'which':1,'such':1},'40':{'photo':1,'are':1,'tons.':1},'41':{'photo':1},'sandy':{'shores':1,'loess':1,'places':1},'tree-tops':{'express':1},'out':{'and':6,'among':1,'is':1,'into':1,'some':1,'as':4,'at':4,'in':12,'sounds':1,'still':1,'apparently':1,'its':5,'saline':1,'light-waves':1,'from':9,'for':3,'their':1,'1890':1,'there':1,'had':1,'three':1,'.':5,'to':4,'those':1,';':2,'pre-eminent':1,'until':1,'more':1,'we':1,'his':1,'that':6,'very':1,'measures':1,'about':1,'fat':1,'how':2,'heat':1,'waves':1,'during':1,'profitless':1,'with':2,'by':3,'vast':1,'he':1,'a':9,'on':2,'great':1,'like':1,'these':1,'of':54,'according':1,'whether':1,'streams':1,'the':9,'are':2},'quintillion':{'atoms':1},'conveys':{'that':1},'period.':{'illustration':1},'functionless':{'letters':1},'dilatable':{'sac':1},'variation':{'being':1,'of':2,';':1,'in':1},'enlargement':{'of':3},'d-e.':{'an':1},'death.':{'this':1},'astronomy':{'and':1,'be':1,'that':1,'this':1,'of':1,'.':9,'deals':1,'to':1,'as':1,'at':1,'which':1,'the':1,'has':1,'by':1,'are':1},'keane':{'a':1},'race--many':{'animal':1},'pupil':{'the':1},'4a':{'hypohippus':1},'limited':{'warranty':1,'right':2,'.':1,'to':3,'as':1,'extent':1,'than':1,'areas':2},'gossamer':{'forms':1,'the':1,'202':1,'spiders':2,'.':1},'oxygenation':{'and':1},'holman':{'matter':1},'comparatively':{'dry':1,'little':1,'everlasting':1,'shallow':1,'large':1,'few':1,'narrow':1,'recent':2},'dynasty':{'and':1},'neoceratodus':{'has':1,'by':1},'sleep':{'and':1,'the':1},'admiration.':{'sec':1},'poorly':{'developed':2},'belonged.':{'when':1},'flash.':{'it':1},'feeding':{'growing':1,'on':2,'purposes':1,'chiefly':1},'patches':{'of':1,'in':1,'on':1},'paris':{'also':1,'as':1},'34.':{'illustration':1},'ceylon':{'and':1,'the':1},'charles':{'darwin':4,'r':1,'e':1,'descent':1},'thinnest':{'vapours':1,'part':1,'parts':1,'.':1},'340':{'000':1},'whatsoever':{'we':1,'.':2},'caused':{'a':1,'though':1,'this':1,'when':1,'to':1,'in':2,'by':1},'elapsed':{'before':1},'comet--the':{'stellar':1},'risk':{'of':6},'arboreal':{'and':1,'life':5,'apprenticeship--an':1,'mammals':1,'evolution':1,'.':2,'insectivores':1,'habits':2,'apprenticeship--tentative':1,'mother':1,'apprenticeship':8,'marsupials':1},'dispense':{'energy':1,'with':2,'largely':1},'brackish':{'water':1,'swamp':1},'rise':{'and':1,'great':1,'enormously':1,'very':1,'of':8,'into':1,'.':2,'to':17,'in':1},'lurk':{'among':1},'hermon':{'there':1,'grass':1,'.':1},'every':{'ten':1,'laboratory':2,'house':1,'haunt':1,'one':1,'second':1,'human':1,'year':3,'corner':1,'element':2,'species':1,'physical':1,'now':2,'many-celled':3,'atom.':1,'addition':1,'question':1,'two':1,'port':1,'chemical':1,'few':1,'gramme':1,'other':2,'animal':3,'empty':1,'niche':3,'amateur':1,'form':1,'class':1,'gas':1,'possible':1,'killing':1,'protection':1,'atom':1,'vigorous':1,'hole':2,'twenty-thousandth':1,'opportunity':1,'day':4,'man':1,'kind':1,'substance':3,'instant':1,'third':2,'hour':1,'particle':3,'arc-lamp':1,'glowing':1,'introduction':1,'part':1,'bone':1,'time':1,'star':1,'side':4,'clap':1,'twenty-four':2},'gratification':{'of':1},'east.':{'illustration':1},'slipperiness':{'.':1},'monkeys':{'and':5,'is':1,'it':2,'sec':1,'at':1,'have':2,'securing':1,'.':3,'may':1,'other':1,'which':1,';':1,'semnopithecus':1,'learn':1,'but':1,'such':1,'than':1,'on':1,'leaving':1,'were':1,'very':1,'the':2,'where':1,'or':1,'are':2},'encounter':{'the':1},'discovers':{'the':1,'when':1},'school':{'in':1},'parrot':{'of':1,'s':2,'belongs':1,'which':1,'s-beak':1,'stringops':1},'conceive':{'of':2,'the':1,'then':1},'loess':{'of':1,'either':1,'sandy':1},'apprehension':{'so':1,'.':1},'hickson':{'s':1,'puts':1},'relics':{'of':3,'vestigial':1,'.':1},'venus':{'and':1,'flower':3,'67.2':1,'is':1,'s':1,'fly-trap':2,'earth':1,'the':3,'are':1},'humps':{'daily':1,'were':1},'degeneracy':{'in':1},'enjoy':{'pulling':1,'.':2},'veritable':{'museum':2,'physical':1},'zinc':{'and':8,'is':2,'sulphite':1,'which':1,'pass':1,'has':1},'faintest':{'stars':1},'infancy':{'is':1,'would':1},'estimates':{'which':1},'direct':{'and':2,'a':1,'knowledge':1,'descendants':1,'there':1,'competition':1,'passage':1,'to':1,'appropriate':1,'four-footed':1,'statement':1,'indirect':1,'traces':1,'or':1},'nail':{'and':1,'on':1,'as':1,'pulled':1},'yerkes':{'experimented':1,'observatory':1,'studied':1,'40-inch':4,'changed':1,'observatory.':9,'has':1,'refractor':2},'electricians':{'have':1},'street':{'a':1,'or':1},'infiltration':{'of':1},'estimated':{'to':2,'the':3,'fig':1,'that':2},'expressive':{'of':1},'shining':{'disc':1,'through':1},'blue':{'and':2,'box':1,'butterfly':1,'chequer':1,'fit':1,'in':1,'sky':6,'.':1,'hot':1,'disc':1,'green':1,'waves':1,'indigo':1,'the':1,':':1,'or':1,'reptiles':1},'change.':{'a':1,'sec':1},'hide':{'their':2},'pariasaurus':{':':2},'organisms':{'and':1,'to-day':1,'which':4,'of':1,'upon':1,'it':1,'.':1,'are':1,'have':2,'i.e':1,'found':1,'seem':1,'has':1},'solemn':{'occasion':1,'slowness':1},'beaten':{'into':2,'grain':1,'out':1},'revolves':{'round':2},'museum.':{'a':1,'meteorite':1,'carrier':2,'homing':1,'yellow-crowned':1},'liberty':{'.':1},'children':{'and':1,'who':1,'should':1},'characters.':{'in':1},'zoologists':{'with':1},'change;':{'variability--evolution':1},'conduct':{'man':1,'.':1,'in':1,'but':1,'demands':1},'ebbs':{'and':1},'supplies':{'of':1,'the':1,'.':1},'revolved':{'will':1,'on':1,'round':1},'reacts':{'cannot':1},'electricities':{'in':1},'unexhausted':{'possibilities':1},'hundreds':{'and':1,'of':15,'but':1},'seven-weeks-old':{'human':1},'resounded':{'to':1},'represented':{'as':2,'by':9,'for':1,'in':4},'path':{'followed':2,'of':6,'when':1,'marked':1,'round':2,'closely':1,'from':1,'the':1,'by':1,'if':1},'shortness':{'of':2},'through.':{'light':1},'digits':{'of':1,'on':1},'wood-snail':{'in':1},'earth--a':{'transition':1},'distinctness':{'.':1},'ventures':{'were':1},'tons.':{'the':2,'illustration':2},'leaves':{'and':3,'a':1,'or':1,'fanwise':1,'us':1,'one':1,'which':1,'the':1,'.':2,';':2},'settles':{'down':3},'mantis':{'on':1,'religiosa':2,'mantis':2},'mistake':{'to':2,'for':2,'but':1},'settled':{'down':2,'the':1,'within':1},'svante':{'worlds':1},'substances.':{'in':1},'stray':{'present-day':1,'erratic':1},'straw':{'looked':1,'as':1,'so':1},'plants--paint':{'the':1},'equipment.':{'1.f.2':1},'feelings':{'and':2,'such':1,'it':1,'in':1},'patience':{'and':2,'of':1,'were':1},'miles--eighteen':{'times':1},'anyhow':{'as':1},'greatness.':{'it':1},'ape-man--an':{'early':2},'scaffolding':{'but':1},'would':{'help':1,'do':2,'cover':1,'thus':1,'it':1,'one':1,'say':2,'cease':2,'have':15,'in':1,'go':1,'seem':4,'provoke':1,'yet':1,'witness':1,'doubtless':1,'certainly':1,'still':2,'appear':3,'lead':1,'also':1,'estimate':1,'disintegrate':1,'make':2,'unduly':1,'favour':1,'tend':3,'increase':1,'consistently':1,'only':1,'shiver':1,'take':12,'fade':1,'recover':1,'probably':1,'include':1,'cause':1,'shrink':2,'therefore':1,'then':2,'begin':2,'survive':1,'that':1,'mean--matter':1,'burn':1,'confer':1,'obtain':1,'evolve':1,'a':1,'fall':1,'not':9,'penetrate':1,'be':45,'tick':1,'fly':2,'on':1,'frequently':1,'give':3,'like':2,'tear':1,'require':2,'no':1,'account':1,'yield':1,'explode':1,'suppose':1,'contain':1,'become':1,'inevitably':1,'instantly':1,'mean':3},'palings':{'and':1},'distributing':{'a':1,'medium':1,'this':1,'performing':1,'or':1,'project':2,'any':1},'smelted':{'together':1},'romanes':{'used':2},'preserved':{'namely':1,'except':1},'musk':{'will':1,'in':1},'ages--for':{'britain':1},'beauty':{'became':1},'ll.d':{'.':2},'correspondingly':{'longer':1},'arms':{'and':3,'emerging':1,'into':1,'bear':1,'.':1,'which':1,'not':1,'or':1},'excellent':{'milling':1},'20417':{'produced':1,'language':1},'outdated':{'equipment':1},'off.':{'peculiarities':1},'me':{'alone':1,'tangere':1,'a':1,'that':2},'mc':{'the':1},'piltdown':{'man':6,'skull':5,'.':1},'parachuting--a':{'persistence':1},'henry':{'huxley':2},'appendage':{'which':1},'ernest':{'h':2,'rutherford':6},'my':{'own':1},'latitudes':{'appear':1},'clock-work':{'started':1,'so':1},'mud-fishes':{'do':1,';':1,'of':1,'are':1,'or':1},'decorative':{'plume':1},'ingenuity':{'patience':1,'has':1},'powerfulness':{'of':1},'orion':{'the':1,'40':1},'keep':{'them':1,'up':2,'two':1,'their':1,'time':1,'the':3,'themselves':1,'ebooks':1},'attract':{'them':1,'any':1},'returned':{'to':2,'.':1},'ones':{'and':1,'on':2,'about':1,'made':1,'develop':1,'is':2,'pass':1,'make':1,'.':2,'below':1,'are':5,'hatching':2,'in':1,'go':1,'such':1,'come':1,'creeping':1,'first':1},'progression--always':{'a':1},'end':{'all':1,'which':1,'being':1,'of':32,'were':1,'it':1,'against':1,'.':3,'to':2,'they':1,'in':1,'fishes':1,'the':1},'telephonic':{'communications':1},'returning':{'half':1},'intruders':{'with':1,'.':1},'damages.':{'if':1},'particulars':{';':1},'buns':{'without':1,'some':1,'ashore':1},'writers':{'have':1},'modernising':{'of':1},'widespread':{'and':2},'ancestor':{'of':2,'from':1},'badly':{'stung':1,'when':1,'agee':1},'poker':{'again':1,'into':1,'loses':1,'is':2,'in':1},'both.':{'monkeys':1},'scion':{'of':1},'mouths':{'of':2,'on':1},'erected':{'on':1},'invisible--just':{'as':1},'albumin':{'casein':1},'delicacy':{'in':1},'confirmed':{'as':1,'by':1},'lump':{'of':1},'jumping':{'out':2},'poked':{'it':1},'system--with':{'all':2},'leplay':{'school.':1},'amid':{'the':1,'green':1},'spout':{'.':1,'in':1},'hypotheses':{'and':1,'which':1},'perform':{'all':1,'distribute':1},'complexity':{'and':2,'of':3,'possible':1,'or':1},'upside':{'down':1},'eurypterids':{'or':1},'decreasing':{'coal':1},'diary':{'of':1,'is':1},'squirrel-like':{'marmosets':1},'unsteady':{'slippery':1},'flippers':{'which':1,'for':1},'recurrent':{'stimulus':1,'vicissitudes.':1},'untold':{'ages':1},'daughter-units':{'thus':1,'are':1,'that':1},'alternation':{'of':1},'orang':{'and':2,'notice':1,'is':1,'chimpanzee':2,'.':1,'will':1,'are':1,'the':2,'has':2,'than':1,'232':1},'underside':{'of':1},'inattentive.':{'of':1},'london':{'bridge':1,'the':1,'as':1,'zoological':1},'thesis':{'that':1},'terns':{'spending':1},'beside':{'it':1},'daughter-buds':{'go':1,'living':1},'borneo':{'living':1},'anolis':{'of':1},'expectations':{'there':1},'exhibits':{'a':1,'an':1},'writing':{'without':1,'from':1,'or':1},'destroyed':{'and':1,'for':1,'it':1,'but':1,'.':1,'to':1,'the':1,'was':1,'by':2},'trams':{'in':1},'fade':{'entirely':1},'400':{'000':1},'peopling':{'of':4},'centimetre':{'of':2},'250000':{'inch':1},'prevented':{'by':2},'direct-reading':{'spectroscope':2},'tree-stems':{'and':2},'revelations':{'of':2,'it':1,'to':1},'diseased':{'condition':1},'flotation':{'and':1},'skin-leaves':{'about':1},'shadows':{'are':1},'ingested':{'food':1},'swaying':{'on':1},'potatoes':{'settling':1},'water-fleas':{'and':1},'explode':{'and':1,'them':1},'instant':{'of':1,';':1,'it':1},'victory':{'is':1,'alike':1},'fitness':{'of':1,'for':1,'follows':1},'unit-bodies':{'.':1},'attained.':{'now':1},'notifies':{'you':1},'wariness':{'is':1},'flat-fish':{'has':1,'does':1,'like':1},'verrier':{'discovered':1},'provisions.':{'1.f.6':1},'emphasise':{'as':1},'member':{'and':1,'of':2,'.':2},'magnets':{'.':1},'defences':{'of':1},'clothe':{'itself':1},'depress':{'one':1},'gutenberg-tm.':{'1.e.5':1},'gibbon':{'and':1,'is':2,'orang':2,'which':1,'others':1},'driving':{'water':1,'away':1,'off':1,'the':1},'god':{'s':1},'washed':{'away.':1,'away':2,'down-stream.':1},'integrative':{';':1},'day.':{'there':1,'bibliography':1,'but':1},'laid':{'within':1,'it':1,'down':4,'in':2,'the':1,'or':1},'adjust':{'themselves':1},'millennium':{'b.c':2,'further':1,'after':1},'heavenly':{'body':1,'bodies':3},'got':{'possession':1,'a':4,'his':1,'from':1,'apparatus':1,'no':1,'very':1,'into':1,'loose':1,'it':2,'together':1,'the':3,'their':1,'started':1,'green':1,'nothing':1,'rid':2,'across':1,'films':1},'newly':{'born':1,'hatched':4},'twenty-five':{'trillion':1,'tons':1,'miles':1,'million':1},'independence':{'of':1},'splashed':{'into':1},'provide':{'access':1,'a':4,'volunteers':1,'in':1},'carcass':{';':1},'eternal':{'night':1,';':1,'night--relieved':1,'winter':1,'possible':1},'free':{'from':2,'for':1,'oxygen':1,'air':1,'if':1,'.':1,'access':1,'to':3,'future':1,'agents':1,'nitrogen':1,';':1,'hand':4,'distribution':3,'has':1,'intercrossing':1,'anyhow':1,'swimming':1},'carcase':{'of':1},'masterliness':{'of':1},'whereupon':{'the':1},'rain':{'of':1,'dissolving':1,'each':1,'began':1,'to':1},'biological':{'conditions':1,'idea':1,'necessity':1,'ideas--the':1},'calcareous':{'algae':1},'wanted':{'and':1,'.':2},'publication':{'of':1},'solution...':{'.':1},'grasses':{'and':1},'inexpensive':{'physiologically':1},'days':{'and':1,'old':2,'it':1,'in':2,'there':1,'when':1,'29':1,'.':5,'note':1,'to':2,'weeks':1,'then':1,'fourteen':1,'with':1,'he':1,'on':1,'longer':1,'of':5,'stand':1,'were':1,'following':1,'the':1},'rang':{'our':1,'up':1},'appeals':{'to':2},'possibility--involution':{'rather':1},'researches':{'have':1},'primary':{'reservoir':1,'occupations':1,'meaning':1,'emotions':1,'entity':2,'colours':3,'source':1,'reason':1,'atomic':1},'rank':{'mammals':1},'hearing':{'and':1,'this':1,'is':1,'.':1,'heard':1,'are':1,';':1,'has':1,'comes':1},'staying':{'power':1},'philosophical':{'dictum':1},'adopted':{'by':1},'scissors':{'fall.':1,'.':1},'redivides;':{'there':1},'mercury':{'the':2,'is':1,'it':1,'.':1,'s':2,'between':1,'venus':1,'36.0':1},'magnificent':{'spread':1},'toy':{'of':1},'discriminates':{'between':1},'top':{'with':1,'of':9,'end':1,'are':1},'sumatra':{'and':1},'heights':{'of':1,'holding':1,'above':1},'ton':{'of':1,'or':1,'to':1},'motility':{'are':1,'in':1},'wildly':{'down':1},'variational':{'uplifts':1},'unbroken':{'and':1,'silence':1},'toe':{'to':1,'is':1,'reaches':1},'instreaming':{'multitude':1},'tool':{'is':1,'in':1,'.':2},'brushes':{'off':1},'serve':{'to':1,'as':3,'its':1},'conspicuously':{'as':1,'coloured':1},'190':{'photo':1,'the':1},'western':{'and':1},'injected':{'into':1},'mankind--notably':{'the':1},'frankly':{'answered':1},'divisible':{'into':1},'immaterial':{'.':1},'cogged':{'wheel':1},'classes':{'of':2,'into':1,'called':1,'so':1,'which':1,'orders':1},'flame':{'shattered':1,'is':1,'was':1},'hearing.':{'instinctive':1,'power':1},'bridge':{'the':1,'for':1},'donkey':{'grazing':1},'fashion':{'so':1,'of':1,'with':1,'.':2},'handkerchief':{'.':1},'ran':{'riot':1},'progressing.':{'b':1},'agility':{'.':1,'that':1},'raw':{'material':1,'materials':3},'rat':{'or':1},'regulate':{'what':1,'growth':1,'the':1},'leafy':{'surroundings':1},'relatively':{'poor':2,'great':1,'slow':1,'easygoing':1,'less':2,'cooler':1,'shallow':4,'well':1,'uniform':1,'naked':1,'simple':1,'safe':1,'short':1,'larger':1,'small':1,'recent':2,'more':2},'reminding':{'him':1,'one':1},'-':{'of':1,'you':5,'except':1,'if':1},'isolated':{'ponds':1,'from':1,'northern':1,'here':1,'districts':1,'alpine':1},'thorough':{'aeration':1},'curly-haired':{'australian':1},'perigord':{'mentone':1},'rodents':{'and':1,'are':1},'hatch':{'inside':1,'from':1,'out':1},'world.':{'besides':1,'it':1,'illustration':1,'but':1,'another':1,'if':1,'physical':1},'effectiveness':{'of':1},'douching':{'with':1},'beta-rays':{'from':1},'propitious':{'environment':1},'greatest':{'mathematical':1,'distance':1,'accuracy':1,'reflector':1,'density':1,'of':4,'prominences':1,'triumphs':1,'instrument':1,'physicists':1,'in':1,'authorities':1,'were--the':1,'scientific':1},'though':{'it':9,'in':1,'still':1,'its':1,'there':1,'their':1,'other':1,'more':1,'we':3,'viviparous':1,'that':1,'very':1,'most':1,'they':5,'not':1,'now':1,'man':1,'a':1,'this':1,'many':1,'these':1,'the':9},'picturesquely':{'the':1},'leaf.':{'illustration':1},'tree-snakes':{'tree-lizards':1},'swampy':{'low':1},'glimpses':{'of':1},'plays--the':{'reindeer':1},'plenty':{'of':4},'coil':{'of':3,'is':1,'thus':1},'coin':{'and':1,'through':1},'parting':{'of':1},'glow':{'as':1,'made':1,'with':3,'into':1,'.':2},'lift':{'a':1,'it':1,'sea-urchins':1},'flow':{'of':10,'is':2,'in':1,'or':1,'.':1},'spencer':{'formulated':1},'unwary':{'person':1},'curie':{'and':1,'was':1},'orderly':{'hierarchy':1},'reputation':{'of':1,';':1,'for':1},'gratefully':{'accepted':1},'constance':{'or':1},'chariot':{'and':1},'bait':{'and':1},'spikelets':{'in':1},'manifestation':{'of':3,'in':1},'solutions':{'are':2},'nerve-cells':{'and':4,'an':1,'in':1,'.':1},'mingle':{'with':1},'observatory.':{'a':3,'giant':1,'star':1,'diagram':1,'meteorite':1,'3':1,'jupiter':1,'fig':10,'solar':1,'mars':1,'the':4,'100-inch':1},'endowment':{'of':2,'.':1},'availability':{'of':1},'founded.':{'if':1},'spite':{'of':6},'flat-fishes':{'we':1,'like':1},'situations':{';':1,'which':1},'institution':{'of':1,'at':1,'for':1},'turkestan':{'and':1},'fifty-foot':{'beach':2},'disgust':{'.':1},'gods':{'.':1},'lodge':{'reminds':1,'has':1,'sir':1},'announce':{'every':1},'insect-visitors--began':{'to':1},'borrowed':{'house':1,'shell':1},'waltz':{'round':1},'solution.':{'imitation':1},'nerve-cell.':{'7':1},'watch':{'a':4,'.':1},'fluid':{'water':1,'the':2,'that':1,'was':1,'.':1},'system--regions':{'of':1},'existence--which':{'includes':1},'shutting':{'out':1},'tuberculosis':{'.':1},'despite':{'these':1},'report':{'1914.':1,'1915.':4,'1917.':3,'1917':1,'1914':1},'knocks':{'it':1},'wavy-haired':{'pre-dravidians':1},'gutenberg-tm':{'and':1,'web':1,'license.':1,'concept':2,'name':1,'license':7,'is':1,'work':5,'trademark':4,'s':1,'collection':2,'mission':2,'project':1,'depends':1,'including':1,'works.':2,'works':3,'electronic':18,'ebooks':2},'beads':{'screw':1},'to-day--the':{'elk':1},'countries':{'a':1,'of':1,'there':1,'are':1,'.':1},'rowing':{'and':1},'taken--the':{'emergence':1},'public':{'is':1,'would':1,'support':1,'domain':8},'twice':{'.':1,'as':2,'they':1,'during':1,'the':2,'or':1},'progress.':{'vi':1,'sec':1,'conquering':1},'automatic':{'machine':2,'internal':1,'machine.':1},'farther':{'and':3,'away.':1,'from':2,'away':2,'back':2,'in':1,'north':1},'new.':{'the':1,'illustration':1},'swept':{'down':1,'away':1,'slowly':1,'out':1},'habit':{'a':1,'and':1,'may':1,'of':8,'some':1,'amongst':1,'which':1,'has':1},'nut':{'and':2,'drop':1},'send-off':{'in':2},'retreat.':{'the':1,'another':1},'resist':{'such':1,'the':1,'snapping':1},'t.':{'hobhouse':1},'sea-squirts':{'and':1,';':1,'which':1},'life-preserving':{'value':1},'volans':{'of':1,'which':1},'disturbing':{'influence':2},'discriminating':{'and':1,'quality':1},'combustion':{'is':2,'as':2,'it':1},'capacity':{'and':1,'about':1,'for':3,'that':1,'of':1,'is':1,'.':2,'in':1,'the':1},'ranged':{'one':1},'paternal':{'origin':1,'and':1,'care':1},'mud':{'and':3,'getting':1,'encasements':1,'when':1,'.':2,'that':1,'or':1},'wave-lengths.':{'light-waves':1,'light--visible':1},'finger':{'and':3,'on':1,'from':2,'would':1,'joints':1,'.':1,'usually':1,';':1},'monkeyish':{'features':1},'367':{'000':1},'stored-up':{'energy':1},'approach':{'of':1,'the':2,'160':1,'by':1,'us':1},'discovery':{'and':1,'has':2,'that':2,'of':29,'site':2,'to':1,'which':1,'in':1,'go':1,':':1},'guesses':{'as':1,'or':1},'elk':{'and':2,'the':1},'confusion':{'of':1},'incarnation':{'to':1},'weak':{'and':1,'breakage':1,'keel':1,'plane':1,'one':1},'however':{'composed':1,'and':1,'there':4,'is':1,'it':4,'say':2,'another':1,'in':1,'if':1,'different':1,'acknowledge':2,'interesting':1,'faint':1,'long':1,'by':3,'to':1,'only':2,'slowly':1,'take':1,'that':8,'continuous':1,'what':1,'following':1,'they':2,'not':1,'with':1,'than':1,'a':2,'on':1,'this':1,'enabled':1,'as':1,'so':2,'things':1,'small':1,'the':7},'sand-crab':{'takes':1},'larynx':{'.':1},'aquarium':{'.':1},'consists':{'almost':1,'of':11,'essentially':2,'chiefly':1},'flowering':{'plants':7,'plant':1,'plants.':1},'newt':{'or':1},'improve':{'the':1},'protect':{'the':3},'rhythms':{'.':1},'irregular':{'stretches':1,'speck':1},'jelly':{'about':1,'.':1},'threads':{'used':1,'secreted':3,'of':4,'.':1,'sink':1,'the':2,'are':1},'expense':{'to':1},'frequenting':{'forests':1},'diversity.':{'thus':1},'goodrich':{'evolution':1},'discolorations':{'produced':1},'starling':{'and':1},'majestic':{'spirals':1},'trust':{'.':1},'utilised.':{'indeed':1},'colour-scheme':{'of':1},'influence.':{'illustration':1},'phyllopteryx':{'has':1},'cockroaches':{'to':1,'.':1},'been':{'unified':1,'shot':1,'able':6,'pointed':1,'named':1,'profoundly':1,'attempts':2,'elevated':1,'mentioned':1,'wrought':1,'subjected':1,'written':3,'to':3,'detected':1,'going':3,'transformed':1,'attained':1,'emitting':1,'fancied':1,'unravelled':1,'secured.':1,'very':4,'familiar':2,'reconverted':1,'got':1,'vastly':1,'hitherto':1,'adventurous':1,'rotating':1,'lost':1,'banished':1,'dulled':1,'traced':2,'retrogressions':1,'solved':3,'slipping':1,'found':9,'discussing':2,'interbreeding':1,'achieved':1,'some':1,'briefly':1,'understood':1,'invaded':1,'added':2,'sifted':1,'estimated':1,'borne':1,'established':1,'shown':2,'said':4,'witnessed':1,'beaten':1,'expressed':1,'laid':1,'progress':1,'burned':1,'induced':1,'numerous':1,'blotched':1,'demonstrated':1,'recently':3,'opening':1,'analysed':1,'broken':1,'drawn':1,'colonised':2,'christened':1,'suggested':4,'on':1,'great':1,'buckled':1,'many':1,'greatly':1,'introduced':1,'reached.':1,'examining':1,'raised':1,'followed':1,'adepts':1,'hewn':1,'explained':1,'one':3,'brought':1,'visible':1,'done':1,'capacious':1,'.':1,'given':1,'invented':1,'flaws':1,'weathered':1,'exposed':1,'noticed':2,'smelted':1,'much':2,'slowly':1,'taken':2,'fortuitous':1,'more':1,'life':1,'gaseous':1,'discovered':1,'enough':1,'successful':2,'registered':1,'tested':1,'part':1,'known':7,'suspected':1,'worked':1,'true':1,'chequered':1,'applied':1,'made':10,'abandoned':1,'impatiently':1,'regularised':1,'evolved':3,'pumped':1,'propounded':1,'making':1,'called':1,'and':1,'resolved':1,'proved':1,'indicated':1,'exhausted':1,'turned':1,'an':3,'as':2,'at':3,'in':4,'seen':1,'constricted':1,'clearly':1,'if':1,'different':2,'no':1,'emancipated':1,'that':2,'generally':2,'handed':1,'any':2,'hot':1,'speeding':1,'digged':1,'fostered':1,'used':2,'tried':2,'confirmed':1,'prepared':1,'moving':1,'throughout':1,'measured':1,'recent':1,'a':11,'stupendous':1,'described':2,'slightly':1,'calculated':2,'required':1,'becoming':1,'thought':1,'dissolved':1,'so':4,'the':7},'legend':{'of':1},'were.':{'the':1},'spread':{'and':1,'from':1,'of':3,'over':2,'until':1,'underneath':1,'to':2,'through':2,'table':1,'public':1,'out':3},'expected':{'when':1},'poker.':{'they':1},'pallas':{'s':1},'pecked':{'at':2},'bladder':{'growing':1},'uncommon':{'on':1},'gaboon':{'in':2},'proportional':{'to':1},'catch':{'this':1,'small':1,'the':1},'own--a':{'fore-limb':1},'ancestors.':{'given':1},'deeps':{'the':1,'3':1,'are':1},'5a':{'merychippus':1},'lessen':{'the':1},'n':{'is':1,'.':5},'ape':{'and':2,'frequenting':1,'or':1,'for':1,'.':1,'s':1,'s.':1,'man':2,'agree':1,'at':1},'fallow':{'deer':1},'gave':{'off':6,'of':1,'rise':2,'most':1,'place':1,'the':3},'precede':{'the':1},'natives':{'of':1},'cyclones':{'.':1},'cast':{'.':1,'aside':1,'by':2},'jellyfishes':{'the':1,'swimming-bells':1,'worms':1},'expenses':{'including':2},'experts':{'should':1},'decanter':{'for':1},'www.pglaf.org.':{'section':1},'significance--called':{'the':1},'containing':{'a':3,'meat':1,'liquid':1,'very':1,'say':1,'the':1,'more':1},'headley':{'life':1},'circumventing':{'the':1},'suggest':{'the':4,'that':3},'underwood.':{'boiling':1,'the':1},'sollas':{'w':1},'linked':{'to':1,'together':1},'forehead':{'and':2,'a':1,'the':1,'without':1,'beetling':1},'utilitarian':{'in':1},'complex':{'and':2,'fur':1,'of':2,'problems':2,'.':3,'forms':1,'as':1,'nucleus':1,'brains':1},'gambian':{'mud-fish':2},'advances':{'the':3,'that':1,'but':1,'came':1,'in':2},'scapula':{'or':1},'snow-line':{'.':1},'several':{'millions':1,'colours':2,'kinds':1,'centuries':1,'cells':1,'sometimes':1,'human':1,'times':1,'hours':2,'enregistered':1,'complex':1,'printed':1,'molecules':1,'cases':1,'years':1,'thousands':1,'other':1,'transparent':1,'more':1},'satellite':{'of':1},'peaks':{'.':1},'pick':{'them':1,'up':2,'out':1},'constantly--either':{'spontaneously':1},'mouse-pupil':{'with':1},'characters':{'even':1,'of':1,'is':1,'.':1,'such':1,'swarming':1},'darwin.':{'illustration':1},'cycle':{'thread':1},'mentioning':{'birds':1},'tassel':{'being':1,'discharged':2,'branches':1,'electrified':2,'strikes':1},'staving':{'off':1},'paralysed':{'and':2},'possessed':{'of':1,'by':1,'in':2},'boxes':{'golden':1,'similar':1,'difficult':1},'rock-pool':{'where':1},'wide-awake':{'more':1},'mother':{'and':7,'digs':1,'for':1,'places':1,'that':1,'may':1,'of':1,'orang':1,'spider':1,'carey':2,'s':2,'so':1,'are':1,'tramps':1,'earth':1,'.':2},'unification':{'but':1},'jean':{'brownian':1},'photosphere.':{'above--that':1},'possesses':{'.':1,'an':1},'seasonal':{'colour-change':2,'change':1},'food-supply':{'.':2},'departed':{'from':2},'mending':{'of':1,';':1},'harmonise':{'with':2},'eye-hole':{'of':1},'partridge':{'sitting':1},'foundation.':{'-':1},'rivulets':{'and':1},'tailless':{'cat':1},'insectivore':{'stock':1},'evolution.':{'we':1,'metcalf':1,'parasitism':1,'this':1,'hutchinson':1,'illustration':1,'mccabe':1,'v':1,'the':1,'darwin':1,'iii':1,'osborn':1},'vibration':{'increased.':1,'of':1,';':1,'.':1},'master-key':{'that':1},'leibnitz':{'s':1,'who':1},'triangular-shaped':{'piece':1},'apart':{'and':1,'from':14,'of':3,'continuing':1,'.':2,'the':2},'interprets':{'be':1},'humanity':{'of':1,'into':1,'.':1},'foot.':{'there':1},'casting':{'themselves':1},'tracheae':{'.':1},'breaks':{'making':1,'off':2,'up':1,'across':1,'under':1},'sussex':{'and':1,'weald--hinted':1,'in':1},'vulture':{'is':1},'chitin':{'which':1,'.':1},'flattish':{'web':1},'expels':{'vitiated':1},'descending':{'element':1},'judge':{'the':1,'animals':1},'burns':{'the':1,'without':1},'advanced':{'and':1,'again':1,'life':1,'knowledge':1,'.':1,'to':1,'than':1},'foster-parent':{'to':1},'melting':{'ice.':1,'ice':1},'appearing':{'and':1,'on':1,'more':1},'angoras':{'and':1},'gift':{'follows':1},'55':{'cubic':1},'57':{'photo':2},'gifted':{'a':1},'50':{'states':1,'000':1},'53':{'the':1},'52':{'inches':1},'specific':{'gravity':2,'permission':1},'gristly':{'fishes':2,'rod':1},'mosquito':{'is':1,'introduces':1},'fixity':{'of':1},'56':{'photo':2,'lb':1},'outpour':{'of':1},'over-anxious':{'on':1},'successfully':{'applied':1,'by':1},'sponge':{'121':1,'illustration':1,'.':1,'to':1,'densely':1,'which':1,'has':1,'or':2},'clawed':{'mammals':1},'cessation':{'of':1},'finger-posts':{'for':1},'indirect':{'consequential':1,'interference':1,'in':1},'guess':{'and':1,'what':1},'tracheate':{'arthropods':1},'intellect':{'who':1,'which':3},'rapidity':{'and':1,'of':1,';':1,'illustrating':1,'.':1},'first--began':{'to':1},'drowned':{'himself':1},'proceeding':{'to':1,'is':1,'in':1},'rhine':{'and':1},'hibernates':{'but':1},'self-effacing':{'flat-fishes':1},'ear':{'and':1,'a':1,'of':2,'well':1,'marked':1,'to':1,'below':1,'which':1,'in':1,'has':1,'160':1,'came':1},'ice':{'and':1,'when':1,'is':1,'ages':4,'it':1,'.':2,'age.':2,'age':5,'287':1,'travel':1},'everything':{'and':1,'appeals':1,'that':1,'is':1,'as':1,'depends':1,'in':1,'not':1,';':1,'teemed':1},'loins':{'of':1},'select':{'a':1,'the':3},'seals.':{'almost':1},'cord':{'and':1,'lies':1,'the':1,'then':1},'core':{'to':2,'is':1,'254':1,'illustration':1,'left':1},'antiquity--perhaps':{'30':1},'disappeared':{'and':1,'from':1,'leaving':1,'somewhat':1,'.':1,'with':1},'littoral':{'animals':1,'haunts':1,'zone':1,'area':3},'permitted':{'by':2},'chapter':{'on':1,':':1,'give':1,'is':1,'in':7,'one':1,'to':1,'how':2,'.':1,'has':1,'was':1,'more':1},'limitation':{'of':2,'set':1,'permitted':1,'in':1},'attacks':{'the':1},'plum':{'and':1},'spikelet-bearing':{'axis':1},'burbank':{'such':1},'plunging':{'into':1},'coiled':{'round':1,'up':1},'steadily':{'accumulating':1,'through':1,'radiating':1,'decreasing':1},'efforts':{'project':1,'of':1,'and':1,'her':1},'alga':{'like':1,'which':1},'sept':{'.':1},'osborn':{'h':2,'s':4,'points':2,'calls':1},'antique':{'types':1},'primitive':{'animals':1,'nebulae':1,'instrument':1,'insects':1,'constituents':1,'men':3,'mammals':2,'.':3,'forms':1,'bushmen':1,'heat':1,'races':1,'bolt':1,'culture':1,'peoples':1,'mammal':1,'collaterals':1,'creatures':1,'type':1,'types':2,'man':2},'cracking':{'the':1},'presence':{'of':4,'.':1},'orders':{'of':2,'families':1,'like':1},'puzzle':{'in':1},'visible':{'and':2,'on':2,'all':2,'from':1,'266':1,'light':1,'radium':1,'spots':1,'.':2,'to':3,'surface':3,'suspended':1,'in':1,'tens':1,'by':1,'at':2},'bath':{'nor':1},'finely':{'developed':1},'bats':{'certainly':1,'for':1,'.':2,';':1,'volplaning':1,'or':1,'involves':1},'existed':{'.':1},'rely':{'to':1},'weald--hinted':{'at':1},'outbreaks':{'on':1,'of':1},'indispensable':{'as':1,'role':1,'sociality':1,'if':1},'sneezing':{'and':1},'transform':{'mechanical':1},'sunlight':{'and':1,'for':2,'is':2,'reflected':1,'to':2,'can':2,'which':3,'in':2,'has':1,'into':1,'are':1,'he':1},'why':{'a':1,'do':1,'we':1,'animals':1,'they':1,'for':1,'this':1,'is':2,'there':1,'some':1,'it':2,'should':4,'most':1,'so':1,'iron':1,'not':1,'our':1,'the':2,'he':1},'stuck':{'together':1},'tacks':{'of':2},'partridges':{'respond':1},'metabolism':{'.':1},'synthesis':{'the':1},'round.':{'c':1,'in':1},'head':{'and':2,'weighted':1,'from':1,'just':1,'157':1,'of':6,'is':2,'after':1,'downwards':1,'to':1,'when':1,'65':1,'they':1,'the':1,'with':1,';':1,'shows':1},'medium':{'and':1,'on':1,'we':1,'that':1,'of':3,'called':1,'through':1,'a':1,'you':1,'throughout':1,'with':2,'or':1},'amateur':{'knows':1},'hydrogen--which':{'consists':1},'java.':{'2':1},'wireless':{'he':1,'telegraphy':1},'heat':{'and':9,'because':1,'being':1,'is':4,'as':1,'are':1,'in':2,'our':1,'.':9,'is--substitutes':1,'rays':1,'from':4,'for':1,'to':2,'there':1,'had':1,'continually':1,'how':1,'only':1,'radiated':1,';':3,'has':1,'energy':12,'that':1,'becomes':1,'introduce':1,'heat':1,'radiations':1,'by':1,'like':2,'on':2,'would':1,'of':4,'could':1,'chiefly':2,'so':1,'light':1,'the':1,'changes':1,'or':2},'silvery-looking':{'light':1},'hear':{'a':1,'about':1,'the':1,'it':1},'satisfactorily':{'accounted':1},'heap':{'it':1},'manoeuvres':{'she':1},'removed':{'all':1,'in':1,'from':1,'.':1},'donate.':{'international':1},'luxuriant':{'vegetation':1},'admiration':{';':1},'indo-china':{'china':1},'portions':{'and':1,'reached':1,'of':1},'consequences':{'may':1,'.':2,'to':1,'as':1,'follow.':1,'have':1},'born':{'a':1,'and':1,'like':1,'of':1,'in':1,'.':1,'as':1,'so':1,'child':1},'bids':{'fair':1},'vivo':{'as':1},'meteorites.':{'every':1},'undeniable':{'endeavour':1,'apartness':1},'disturbances':{'and':1,'of':3,'we':1,'are':1,'man':1},'prematurely':{'and':1},'brightly':{'illumined':2,'but':1,'coloured':3},'furs':{'.':1},'roamed':{'many':1},'escape':{'the':4,'.':1,'from':3,'between':1},'everest':{'would':1},'0.62':{'7700':1},'scotia':{'voyage':1},'universes.':{'illustration':1},'shines':{'through':1},'entellus':{'venture':1},'furl':{'if':1},'constructed':{'to':1,';':1,'from':1},'looked':{'a':1,'upon':1,'at':1,'like':1},'planets--venus--is':{'there':1},'inborn':{'inspirations':1,'predispositions':2,'novelties':1,'engrained':1,'repertory':1,'capacities':2,'pre-arrangements':1,'efficiencies':1,'impulse':1,'in':1,'not':1,';':1,'changes':1,'or':1,'powers':1},'no':{'atmosphere':1,'less':3,'lack':1,'resistance':1,'commoner':1,'hibernation':1,'facts':1,'nearer':1,'glimpse':1,'effort':1,'better':1,'tail':1,'other':3,'warrant':2,'real':1,'sound':1,'return':1,'animal':1,'descendants':1,'trees':1,'figment':1,'instinctive':2,'difference':2,'twilight':1,'bigger':1,'particle':1,'success':1,'yucca':1,'cry':1,'eel':1,'indication':1,'nerves':1,'bulky':1,'scenery':1,'right':1,'hard':1,'idea':1,'sign':1,'cost':2,'escape':1,'employment':1,'bacteria':1,'enemies':1,'blue':1,'living':2,'thoroughfare':1,'steadfast':1,'opening':1,'definite':2,'spur':1,'kidneys':1,'movement':1,'body':1,'noise':1,'cleverer':1,'power':1,'parental':1,'attention':1,'use':3,'twinkling':1,'difficulty':2,'reason':4,'chapter':1,'restrictions':2,'great':1,'actual':1,'feelers':1,'certainty':1,'transition':1,'motion':1,'connection':1,'place':1,'nervous':1,'successors':1,'transit':1,'one':16,'such':6,'sounds':1,'scent':1,'ether':1,'landscape':1,'exertions':1,'jugglery':1,'additional':1,'union':1,'discrimination':1,'doubt':28,'positive':1,'interest':1,'more':5,'remedies':1,'life':2,'tissues':1,'way':1,'reaction':2,'training':1,'direct':2,'adult':1,'true':1,'plants':2,'animals':2,'conception':1,'cells':1,'air':1,'individual':1,'risks':1,'chlorophyll-possessing':1,'proof':2,'larger':3,'deliberation':1,'lock':1,'modern':3,'mind':1,'mining':1,'evidence':4,'chin':1,'sense':1,'ready':1,'floating':1,'organs':1,'check':1,'winter':1,'depth':1,'chemical':1,'vital':1,'branch':1,'intelligent':1,'plant':1,'star':1,'crowding':1,'trace':3,'backbone':1,'vicious':1,'prohibition':1,'pouch':1,'representations':1,'slums':1,'man':1,'diffusion':1,'longer':8,'rotting':1,'light':2,'shore':1,'fresh':1},'whereas':{'on':1,'lead':1,'these':1,'in':2,'others':1,'the':3},'tip':{'of':5,'t':1,'to':2,'.':1},'perfected':{'on':1,'scientific':1,'by':1},'tin':{'with':1},'setting':{'apart':3,'forth':1,'in':1},'sobral':{'brazil':1,'brazil.':1},'globigerinid':{'foraminifera':1},'investigations':{'in':1},'papers':{'and':1,'the':1},'pipa':{'the':1,'americana':2},'picture':{'represents':1,'these':1,'of':11,'is':1,'acts':1,'an':1,'the':2,'with':1,'shows':1},'ceasing.':{'where':1},'worm-types.':{'among':1},'toad':{'and':1,'winds':1,'s':1,'pipa':3,'looks':1},'preceding':{'state':1,'neanderthal':2,'the':1},'uniformly':{'around':1},'emission':{'came':1},'flower-perfumed':{'nor':1},'leonard':{'johnson':2},'ridges':{'and':3,'the':2,'which':1},'dullest':{'red':1},'discharge':{'takes':1,'of':3,'travels':1,'through':1,'in':4,'with':1},'suffused':{'with':3},'thorax':{'.':1},'buller':{'s':1},'to-day':{'and':2,'is':2,'as':1,'are':2,'in':1,'there':1,'.':13,'attack':1,'recapitulates':1,':':1,'mostly':1,'that':2,'very':1,'after':1,'but':1,'such':1,'by':1,'104':1,'a':2,'about':1,'of':2,'shall':1},'longer':{'be':2,'what':1,'redolent':1,'than':7,'in':1,'deny':1,'or':1,'to':3,'because':1,'at':1,'waves':1,'the':1,'.':1,'emit':1},'n.':{'america.':1},'1800':{'of':1},'vigorously':{'.':1,'continued':1,'for':1,'that':1},'changed':{'and':1,'by':1,'from':1,'but':1,'.':1,'in':1,'the':3,'its':1},'hypohippus':{';':1},'serious':{'and':1,'errors':1,'business':1,'nervous':1,'friction':1,'responsibilities':1,'difficulties':1},'nuclei':{'then':1,'within':1},'undoubted':{'but':1},'remarkable':{'plants':1,'and':2,'bony':1,'physical':1,'knowledge':2,'success':2,'habit':2,'appearance':2,'metamorphosis':1,'combination':1,'results':1,'discovery':2,'except':1,'power':3,'exuberance':1,'perfection':1,'words':1,'locomotor':1,'.':2,'sucking':1},'varying':{'forms':2,'nature':1,'notably':1,'magnitude--and':1,'degrees':1,'situation':1,'with':1},'rod':{'which':1,'.':1},'focus':{'of':1,'whence':1,'within':1},'leads':{'to':2,'one':1,'us':2,'on':1},'inspirations':{'of':1},'computation':{'.':1},'coyote':{'.':1},'jointed-footed':{'invaders':1,'animals':1},'dragon-flies':{'and':2,'are':1},'displaying':{'the':1,'performing':2,'or':1},'tucking':{'it':1},'injure':{'their':1},'doom':{'by':1},'books--an':{'outline':1},'essentials':{'of':1},'ascidians':{'and':1},'fahr.':{'due':1},'metallurgists':{'and':1},'passage':{'from':6,'of':3,'is':2,'onward':1,'direct':1,'in':2},'environment':{'and':4,'we':2,'adaptations':1,'where':1,'acts':1,'.':3,'to':1,'113':1,'which':1,'making':1,';':1,'education':1,'with':1},'charge':{'and':1,'on':1,'anything':1,'for':1,'was':1,'of':3,'to':1,'a':3,'with':1},'promoting':{'the':1,'free':1},'discovering':{'new':1},'hammers':{'on':1,'until':1,'it':1},'ulna':{'of':1,'bone':1},'advantage':{'for':1,'may':2,'of':7,'over':2,'here':1,';':1,'was':1,'is':1},'coot':{'swims':1},'exalted':{'powers--man':2},'inspiriting':{'picture':1},'fleece':{'cutting':1},'untenable':{';':1},'nesting':{'behaviour':1},'refractive':{'granules':1},'regular.':{'now':1},'roving':{'animal':1},'cool':{'and':1,'mass':1,'gas':1},'annihilated':{'distance':1},'clouds':{'of':3,'which':1,'in':1},'impressive':{'triumphs':1,'picture':1,'nebula':1},'level':{'and':1,'on':3,'of':5,'is':1,'there':1,'up':1,'.':3,'at':1,'the':1,';':1,'man':1},'sedimentary':{'rocks':6},'hawaii':{'to':1},'cloudy':{'precipitate':1},'standards':{'is':1,'are':1},'starlit':{'night':1},'slouching':{'gait':1},'vicissitudes':{'due':1},'quick':{'to':5,'or':1},'lever':{'against':1},'accumulation':{'of':2},'bull-terrier':{'called':1},'illustrating':{'the':5,'walking':2,'animal':1},'trend':{'of':3},'becquerel':{'brought':1,'was':1},'obsolete':{'old':1},'inland':{'and':1,'the':1,'than':1},'widened':{'and':1},'invaded':{'age':1,'by':1},'dried':{'and':1,'up':4},'hair.':{'the':1},'trent':{'the':1,'291':1,'290':1,'an':1},'danger-note':{'.':1},'bacteria':{'and':1,'serving':1,'that':1,'of':2,'though':1,'.':1,'can':1,'have':1,'in':1},'substitute':{'the':1},'spectral':{'lines':1},'water-plants':{';':1},'stands':{'about':1,'unique':1,'by':2,'apart':1},'stomach.':{'4':1},'structure--the':{'remains':1},'extinct.':{'unfortunately':1,'others':1},'paragraph':{'1.f.3':3,'1.e.1.':1,'to':1,'1.e':1,'f3':1,'1.e.8':1,'1.c':1,'1.e.8.':1,'1.e.1':1},'goes':{'on':6,'back':1,'leaving':1,'down':1,'to':4,'as':1,'without':1,'through':1},'bearers':{'and':1},'illimitable':{'.':1},'morgan':{'observed':1,'s':1,'who':1,'was':1},'intelligent.':{'sec':1},'ninety-nine':{'cases':1},'mean--matter':{'ether':1},'evolution-idea':{'to':1,'is':2,'has':1},'water':{'and':15,'brightly':1,'because':1,'furnished':1,'being':1,'is':5,'spider':1,'held':1,'as':2,'owing':1,'through':1,'are':1,'in':5,'earth':1,'out':2,'even':1,'will':1,'from':4,'would':2,'to':8,'remains':1,'began':1,'that':4,'28':1,'.':28,'how':1,'only':1,'offers':1,'which':2,';':5,'gets':1,'was':1,'into':2,'do':1,'than':1,'though':1,'may':1,'but':3,'gently':1,'flows':1,'came':1,'rises':1,'with':2,'by':1,'nor':1,'a':2,'on':3,'periodically':1,'has':1,'animals':1,'for':4,'you':1,'fills':1,'did':1,'of':2,'seldom':1,'vigorously':1,'occurs':1,'sometimes':1,'where':1,'near':1,'became':1,'so':1,'can':2,'were':1,'at':3,'beneath':1,'disappears':1,'or':2,'comes':1,'first':1},'meteorites':{'is':1,'it':1,'every':1,'are':1,'have':1,'enter':1,'or':1},'generation.':{'the':1,'they':1},'twentieth':{'trial':1},'groups':{'of':4,'are':2,'drifting':1},'cyril':{'crossland':1},'dissipated':{'as':2,'the':1,'.':1},'cork':{'she':1,'out':1},'f.r.s.':{'conservator':1},'one--of':{'protective':1},'pearly':{'nautilus':7,'nautilus.':1},'bygone':{'ages':1},'thirty':{'miles':1,'million':4,'stars':1,'deep':1,'years':4},'healthy':{'lives':1},'chalmers':{'mitchell':1},'blotch':{'on':1},'sex--beginning':{'of':2},'stomachs':{'of':1},'descended':{'and':1,'from':6},'weird':{'ways':1,'peaks':1},'illustrations.':{'1':1},'say--of':{'various':1},'emerge':{'the':2,'before':1,'from':1,'as':1,'in':1},'credited':{'with':1},'threes':{'and':1},'semang':{'and':1},'swallowed':{'and':1,'by':1,'one':1},'crisis':{'in':1},'wings.':{'vi':1},'bulbs':{'on':1},'russell':{'has':1,'sons.':2},'atom.':{'how':1,'the':1,'like':1,'an':1},'percept':{'of':1},'prey':{'of':1,'by':1,'working':1,'.':3},'memory':{'of':1},'negroes':{'and':1},'lycosa':{'lying':1},'australian':{'and':1,'mudfish':1,'race':1,'more-pork':2,'frilled':2,'the':1,'species':1},'diagrams':{'of':1},'conductor':{'of':1},'bristle-tails':{'show':1},'fuel':{'.':1},'flapping':{'their':1},'southwards':{'following':1,'.':1},'sequoia':{'or':1},'cases':{'is':2,'within':1,'it':4,'purely':1,'at':1,'in':3,'yet':1,'its':1,'out':2,'no':1,'rather':1,'there':2,'two':1,'.':3,'to':1,'supplanted':1,'much':1,'which':1,'under':1,'relatively':1,'be':1,'we':2,'that':2,'stow':1,'however':4,'they':1,'measured':1,'than':1,'like':1,'especially':1,'e.g':3,'this':1,'of':3,'the':9,'where':3},'andalusia':{'arabia':1},'autumn':{'gales':1,';':1,'or':1,'they':1},'diagram.':{'the':1},'collision':{'with':2},'thousands':{'being':1,'of':17,'but':1},'reflux':{'of':1},'modified':{'and':1,'for':2},'means.':{'sec':1},'handle.':{'in':1},'districts':{'here':1,'.':1},'jetsam':{'that':1},'female-producing':{'egg':1},'wrong:':{'hence':1},'fauna':{'of':5,'is':1,'there':1,'namely':1,'.':1,'contemp':1,'as':2,'does':1,'bodily':1},'attain':{'a':1},'streak':{'of':1},'hutchinson':{'h':1},'wrist-bones':{'with':1},'stream':{'and':1,'sometimes':1,'gripping':1,'seeking':1,'of':7,'there':1,'some':1,'.':1,'relative':1,'that':1,'going':1,'the':1,'with':1,'or':1,'ought':1,'through.':1},'irruption':{'of':1},'supra-renal':{'and':1,'.':1},'and--it':{'smells':1},'coal--dissipation':{'of':1},'amalgams':{'and':1},'stroke':{'of':4},'performed':{'viewed':1},'octopus.':{'shifts':1},'flora.':{'the':1},'provoke':{'new':1,'them':1},'hydrogen':{'and':3,'uniting':1,'19':1,'travel':1,'atom':1,'gas':4,'.':2,'to':1,'rising':2,'at':3,'were':1,'so':1,'was':1},'requirements':{'of':1,'we':1,'are':1,'.':1},'white-hot.':{'they':1},'mole':{'and':1},'secured':{'in':1},'eloquent':{'vestige':1,'anticipation':1,'detail':1,'instance':1,'in':1,'than':1},'innumerable':{'tons':1,'methods':1,'minute':1},'fishes--a':{'very':1},'ginkgos':{'and':1},'vital':{'and':1,'activities':1,'processes':2,'power':1,'importance':2,'inter-relations':2,'than':1,'to':1,'connection':1,'interest':1,'activity':1,'laboratory':1,'process':1,'sounds':1,'economy':1},'fourth':{'and':1,'great':2,'haunt':1,'ice':1,'state':3,'printing':1,'millennium':1,'glacial':1},'speaks':{'of':1},'reactions.':{'3':1},'secures':{'the':1},'unutterably':{'stupid':1},'information':{'is':2,'about':6,'can':1},'digesting':{'intruding':1,'them':1},'larmor':{'suggested':1},'eighty':{'figures--bison':1,'distinct':1,'different':1,'miles':1,'million':1},'unawares':{'.':1},'apprenticeship':{'and':2,'often':1,'of':1,'since':1,'.':1,'to':1,'at':1,'in':1,'during':2,'the':1},'eighth':{'printing':1},'branches':{'and':1,'down':1,'still':1,'that':1,'of':6,'in':1,'.':2,'will':1,'gives':2,'firmly':1,'at':1,'hanging':1,'must':1,'come':1,'or':2,'out':1},'drained':{'swamps':1},'commodity':{'on':1},'joint':{'to':1},'enemies.':{'when':1,'if':1},'branched':{'and':2},'lagoon':{'and':1},'water-oceans.':{'in':1},'lamented':{'the':1},'imagining':{'how':1},'estuary':{'and':1},'furnished':{'the':1,'them':1,'an':1},'constituents':{'may':1,'and':1,'.':1,'of':1},'mainly':{'composed':1,'among':1,'arboreal':1,'vegetarian':1,'to':1,'in':2,'vertical;':1,'by':1},'discharging':{'them':1,'sepia':1},'ocean-troughs':{'and':1},'furnishes':{'a':2},'ducklings':{'catch':1},'motions':{'would':1,'of':2,'can':1,'which':1,'along':1,'are':1},'weather.':{'there':2},'side--a':{'mobility':1},'pre-eminent':{'as':1,'e.g':1},'pterodactyls':{'varied':1,'could':1,'had':1,'birds':2,'by':1,'gave':1},'supplemented':{'the':1},'emmer':{'which':1},'wallace':{'maintained':1,'was':1,'darwinism.':1},'organisation':{'than':1},'mantle':{'of':1,'as':1},'offers':{'to':2,'the':1,'grave':1,'an':1},'marvels':{'the':1},'meridian':{'while':1,'.':1},'whirlpool':{'of':1,'or':1},'employment':{'of':2},'pre-dravidians.':{'the':1},'obtaining':{'a':2,'considerable':1},'motion.':{'the':2},'photograph.':{'illustration':2},'evolution':{'and':2,'particularly':1,'is':13,'states':1,'as':1,'are':1,'in':8,'home':1,'if':2,'from':1,'no':1,'remains':1,'there':3,'.':12,'current':1,'to':4,'that':2,'going':11,'fig':1,'which':2,';':1,'has':6,'was':6,'real':1,'we':1,'led':1,'theory':3,'means':1,'but':3,'quite':1,'not':1,'animals':1,'1917':1,'chequered':1,'a':1,':':1,'implies':1,'especially':1,'practically':1,'of':54,'introductory':1,'53':1,'element':2,'will':1,'so':1,'agoing.':1,'though':1,'the':4},'delighted':{'darwin.':1},'underneath':{'things':1,'the':2,'her':1,'.':1},'expertness':{'the':1},'conquer':{'every':2,'for':1},'browns':{'and':1},'sowing':{'and':1,'but':1},'term':{'race':1,'commensalism':1},'name':{'given':1,'from':2,'for':1,'of':1,'cock-paidle':1,'electrons':1,'which':1,'mare.':1,'associated':1,'primates':1},'civilisation':{'of':1,'is':1,'there':1,'here':1,'.':1,'depends':2,'the':1,'more':1},'advent':{'of':1},'possibilities':{'and':1,'of':3,'.':1,'are':1,'in':1,'probably':1},'realise':{'of':1,'the':3,'what':1,'that':3},'telegraphic':{'and':1},'individually':{'and':1},'weighted':{'with':1},'gape':{'and':1,'two':1},'woodpeckers':{'are':1},'sprinkle':{'iron':1},'catching':{'and':2,'small':4,'the':2,'with':1,'some':1},'begun':{'to':1,'before':1,'some':1,'.':1},'distributor':{'under':1},'tumultuous':{'surging':1},'y.s.':{'which':1,'.':1},'ultimately':{'composed':1,'the':1,'dispensed':1},'intercourse':{'and':1,'.':1},'factors':{'and':1,'would':1,'that':2,'of':2,'which':1,'in':5,'the':1},'profit':{'a':1,'by':2,'501':1},'these--which':{'illustrate':1},'attracted':{'to':1,'one':1},'parallax':{'the':1},'kent':{'dating':1,'but':1,'cro-magnon':1},'picture-logic':{'which':1},'overflowing':{'waters':1},'eagle':{'lifts':1,'or':1},'--the':{'mind':1,'planets--venus--is':1},'performing':{'distributing':1,'other':1,'displaying':1,'chimpanzee':1,'copying':1},'theory':{'is':7,'as':1,'sec':1,'in':1,'bears':1,'.':1,'which':3,';':1,'has':1,'was':1,'more':1,'we':1,'provides':1,'that':5,'1796':1,'but':2,'vividly':1,'nor':1,'a':1,'implies':1,'of':16,'or':1},'stimuli.':{'animals':1},'interpose':{'when':1},'ascertain':{'how':1},'electrified':{'270':1,'and':1,'the':1,'with':1,'will':1},'gizzard--certainly':{'the':1},'explorers':{'of':1},'reptiles--snakes':{'lizards':1},'importance.':{'difficulties':1,'sec':1},'www.pgdp.net':{'updated':1,'illustration':1},'corroborating':{'individual':1},'motion':{'and':2,';':2,'would':1,'was':1,'whether':1,'of':3,'is':2,'within':1,'or':1,'to':1,'as':2,'than':1,'in':1,'into':1,'the':1,'.':3,'ever':1,'kinetic':1,'are':1},'turn':{'on':1,'form':1,'stiff':1,'of':3,'is':1,'it':1,'the':2,'to':4,'are':1,'in':1,'into':1,'making':1,'white':1,'with':1,'round':1,'becomes':1,'once':1},'butterflies':{'allied':1,'are':3},'place':{'and':2,'is':1,'inaccessible':1,'it':1,'itself':1,'in':1,'end':1,'for':3,'remains':1,'there':2,'favouring':1,'preventing':1,'to':4,'work;':1,';':1,'let':1,'by':1,'a':1,'on':1,'of':9,'work':1,'sea-anemones':1,'the':1,'where':1,'or':1},'retreating':{'forehead':1},'swing':{'of':1,'to':1},'deep-sea':{'life':1,'animals':2,'fish':3,'sponge':2,'corals.':1,'are':1,'fishes':2,'fauna':1},'gradually.':{'when':1},'close-set':{'eyes':1},'saucers':{'.':1},'weakling':{'it':1},'origin':{'and':3,'of':19,'is':1,'there':1,'direct':1,'are':1,'the':1},'pelican':{'s':2},'surviving':{'the':1,'symbol':1},'revenue':{'service':1},'faculty':{'in':1,'if':1},'greatest.':{'v':1},'soaring':{'upward':1},'them--':{'melanocetus':1},'array':{'of':1},'field-voles':{'perhaps':1},'george':{'h':1},'millions':{'of':39,'the':1,'is':1,'.':1},'gertrude':{'white':1},'given':{'because':1,'over':1,'sense-presentation':1,'as':2,'in':1,'.':1,'to':8,'illustrations':1,'conditions':1,'variability':1,'away--you':1,'sufficient':1,'rise':1,'but':1,'part':1,'an':2,'by':2,'a':5,'off':1,'up':1,'us':2,'place':2,'the':3},'necessarily':{'be':1,'progressive':1,'keep':1,'progressive;':1,'cooling':1,'difficult':1},'persons.':{'the':1},'marine.':{'in':1},'croaking-sacs':{'which':1},'trillion':{'100':1,'miles':5,'revolutions':1,'molecules':1,'waves':1},'tides--origin':{'of':1},'plastic':{'and':3,'appreciation':1,'stock--some':1},'stimulation':{'proves':1},'hardwood':{'forests':1},'returns':{'to':1,'.':1},'virgil':{'refers':1},'fortuitous':{'.':1},'legally':{'required':1},'white':{'and':1,'polar':1,'one':2,'hair':1,'ermine':1,'in':1,'dress':1,'surfaces':1,'winter':1,'except':1,'.':2,'surroundings':1,'combine':1,'stars':2,'cross':1,'save':1,'body':1,'then':1,'star':1,'of':1,'but':1,'pigment':1,'heat':2,'wake':1,'pelage':1,'background':1,'remarks':1,'with':1,'by':1,'card':1,'plumage':1,'fur':1,'coat':1,'colour':1,'will':2,'s':1,'mass':1,'light':9,'blackbird':1,'the':1,'or':1,'blood':1},'anguilla':{'vulgaris':1,'vulgalis':1},'farthing--contains':{'an':1},'gives':{'a':7,'rise':1,'up':1,'us':5,'.':1,'place':1,'the':2},'sex-call':{';':1,'.':1},'million.':{'there':1},'hug':{'the':1},'aurelia':{'.':1},'centipedes':{'and':2,'millipedes':1,'spiders':1},'hum':{'comparable':1},'circulated':{'round':1},'released':{'from':1},'suspended.':{'the':1},'freeze':{'throughout':1},'holder':{'found':1,'the':1,'.':1,'your':1,'on':1},'intrinsically':{'too':1},'population':{'consists':1,'of':5,'could':1,'contains':1,'.':1},'eohippus':{'about':1,';':1},'unfortunately':{'the':1,'we':1},'require':{'a':1,'extension':1,'no':1,'fifty':1,'to':3,'much':1,'such':1,'intelligent':1},'pigmy':{'representatives':1},'modelled':{'by':6},'computer':{'virus':1,'codes':1},'ooze':{'likewise':1,'so':1,'of':1},'aesthetic':{'reasons':1},'proteins':{'e.g':1},'1.e.9.':{'1.e.8':1,'1.e.3':1},'earth.':{'a':1,'we':1,'is':1,'it':1,'illustration':1,'making':1,'the':1,'establishment':1},'and':{'discards':1,'all':10,'pheasant':1,'consider':1,'caused':1,'stems':1,'results':1,'foul':1,'four':1,'crocodile':1,'avalanche':1,'debris':1,'broader':1,'dainty':1,'go':3,'honour.':1,'nematodes':1,'decisions':1,'causes':2,'skeleton':1,'hold':4,'depend':1,'hunting':1,'educable':1,'shrinkage':1,'father':1,'young':4,'send':1,'squirrels':2,'to':29,'finally':5,'reptiles':1,'skill.':1,'stable':1,'portentous':1,'hammers':1,'cochroaches':1,'sent':1,'ulna':1,'activities':1,'protective':1,'presently':1,'club-moss':1,'very':4,'einstein--the':1,'miners':1,'wave':1,'interglacial':1,'coal-measures':1,'fall':2,'mixing':1,'more.':1,'soles':1,'monkeys':2,'minute':2,'respiratory':1,'baking':1,'parrot':1,'ceased':1,'tear':1,'michael':1,'joined':1,'culminating':2,'large':1,'these':13,'sand':1,'guiding':1,'small':2,'venus':1,'mammoth.':1,'snails':1,'round':1,'degeneracy':1,'favoured':1,'smaller':2,'illustrating':1,'ten':1,'concise':1,'imagination.':1,'becquerel':1,'measurable':1,'seas.':1,'second':2,'notwithstanding':1,'further':1,'nests':1,'perish':1,'even':12,'established':2,'what':10,'stood':1,'constitution':2,'voluminous':1,'giving':1,'storks':1,'fingers':1,'emotions':1,'hereditary':1,'white-hot':1,'salamanders':1,'above':2,'new':5,'3a':1,'cycad':1,'guinea-pigs':1,'bird':2,'alertness':1,'scenery':1,'brain-case':2,'toes':5,'malaria':1,'gathered':1,'concepts':1,'here':2,'hundreds':2,'water':8,'reported':1,'humidity.':1,'let':3,'others':12,'lull.':2,'strong':2,'anchoring':1,'extreme':1,'dry':3,'great':1,'substance':1,'broken':1,'technical':1,'employees':2,'whine':1,'36':1,'animals--the':1,'apes':5,'credit':1,'smoke':1,'browsing':1,'bettered':1,'weird':1,'otters':1,'makes':1,'beautiful.':1,'sticking':1,'control':1,'adjustable':1,'love':2,'waves--light--what':1,'family':1,'distributed':2,'bathers':1,'feelings':1,'peahen':1,'retires':1,'preparatory':1,'comets--millions':1,'sugar':1,'herring':1,'select':1,'ape':1,'standing':1,'use':1,'from':10,'takes':1,'working':1,'distinct':1,'positive':1,'continuous':1,'give':3,'two':6,'trilobites.':1,'distributing':1,'ocean-basins.':1,'live':2,'touched':1,'untie':1,'therefore':6,'taken':2,'tell':1,'more':23,'brings':2,'habits--the':1,'about':1,'chimpanzee':2,'jellyfishes':1,'magnesium.':1,'carrying':2,'big':1,'rabbit':1,'lawlessly':1,'hjort':1,'tearing':2,'must':1,'swooping':2,'metazoa':1,'animals':15,'fro.':1,'this':23,'work':2,'sucks':2,'london':1,'guards':2,'diverse':1,'crickets':1,'can':2,'mr':1,'knocked':1,'making':2,'fauna':1,'scatter':2,'mud-fishes':1,'beautiful':1,'sinking':2,'squat':1,'escapes':1,'of':27,'share':1,'purposes':1,'accept':1,'pieces':1,'parachute':1,'heard':1,'rise':1,'masterfulness':1,'bones':1,'every':4,'provoke':1,'hydrogen':1,'offspring':2,'salts':5,'firmly':1,'sir':1,'winter':2,'decaying':1,'telephonic':1,'rather':1,'breaking':2,'gannets':1,'oligocene':1,'species':1,'fishes--a':1,'cycads':2,'hot':1,'occasionally':1,'aerates':1,'animal':1,'elephant':1,'relinquished':1,'willing--has':1,'expresses':1,'oceans':1,'maternal':1,'utilise':3,'inconceivably':2,'may':7,'digesting':2,'burrowing':1,'after':3,'southern':2,'permanent':2,'produce':1,'space.':1,'curiosity':2,'coming':1,'such':2,'flourish':2,'grow':2,'lids':1,'man':4,'a':67,'short':1,'calves':1,'remember':1,'third':2,'pithecanthropus':1,'light':6,'register':1,'descends':1,'think':1,'eye':2,'perhaps':5,'complexity':2,'gloomy':1,'so':35,'silence':1,'back--till':1,'reflux':1,'first':1,'moulton.':1,'make':1,'furnish':1,'grasshoppers':1,'digested':1,'help':1,'furnished':1,'unpalatable':3,'indeed':1,'over':5,'altogether':1,'orang':1,'soon':1,'years':2,'produced':1,'bounding':1,'toads':3,'thinner':1,'including':1,'looks':1,'drifters':1,'cuts':3,'mottlings':1,'still':1,'its':17,'roots':1,'before':2,'chemical':2,'26':1,'27':1,'curly':1,'thence':1,'willow':1,'mites':1,'coarser':1,'forms':2,'saturn--the':1,'absence':1,'dogfish':1,'marsh':1,'dwarfs':1,'hind-limb':1,'societies':1,'admirable':1,'no':12,'formosa':1,'finer':1,'then':22,'evening':1,'return':2,'fourth':1,'seeking':1,'africa.':1,'saltatory':1,'inter-relations':1,'kin.':1,'giraffe':2,'elephants.':1,'they':26,'not':5,'now':1,'lifelong':1,'smoothness':1,'down':2,'obviates':1,'bluffing':1,'rocky':1,'oxygen':1,'mathematician':1,'hunterian':1,'proteins':1,'identified':1,'composition':1,'explode':1,'did':1,'someone':1,'habits':2,'2a':1,'realise':1,'each':3,'veins':1,'feeds':1,'higher':4,'erratic':1,'lively':1,'enigmatic':1,'reactions':1,'clams':1,'matthew.':2,'snakes':3,'weight':1,'elephants':3,'there':42,'energy':8,'hard':1,'prolonged':1,'tobogganing':1,'unlock':1,'catching':4,'fewer':1,'primates':1,'year':2,'our':4,'beyond':2,'primitive':4,'conspicuous.':1,'out':2,'living':1,'opened':1,'present':2,'since':3,'research':1,'looking':1,'transforming':1,'laid':1,'mate':1,'pool':1,'got':4,'get':1,'receiving':1,'cause':1,'caucasian':1,'red':1,'shows':2,'buds':1,'turning':1,'inert':1,'telescoped':1,'horse':2,'decay.':1,'quite':1,'backboneless':1,'reason':1,'complicated':1,'splashes':1,'besides':1,'backed':2,'animals;':1,'cattle':1,'steering':1,'swimming':2,'lifts':1,'delight':1,'importance.':1,'organic':1,'mortar':2,'could':2,'put':3,'success':1,'keep':1,'motion':3,'turn':1,'butterflies':1,'massive':1,'withering':1,'hence':1,'stone':1,'pterosaurs':1,'zoophyte':1,'throws':1,'south':3,'toads--it':1,'knots':1,'copper':2,'finest':1,'possessing':1,'waves':2,'delicately':1,'one':7,'feet':1,'will':4,'unexpected':1,'disappearing':1,'another':7,'carry':2,'gripping':1,'blows':1,'ways':1,'earthworms':1,'size':2,'sheep':1,'continental':1,'given':3,'tadpoles':1,'monkey':1,'similarly':1,'apple.':1,'opportunity':1,'caught':1,'relations':1,'plastic':1,'1a':1,'their':23,'2':6,'wasps':4,'motility':1,'democracy':1,'embryology':1,'anatomises':1,'dogs':3,'opening':1,'gives':1,'muscles':1,'imperfect':1,'starfish':1,'that':57,'brains':1,'needle':1,'screwing':1,'bees.':1,'folded':1,'part':2,'because':2,'cereal':1,'manipulation':1,'rivers':3,'white':3,'explodes':1,'lays':2,'distance':1,'kind':1,'legs':1,'meteors':1,'looting':1,'showed':1,'depressed':1,'sea-squirts':1,'vocal':1,'instincts--of':1,'project':1,'matter':1,'future':1,'magnesium':1,'iron':1,'arboreal':1,'starfishes':1,'hailstones':1,'proofread':1,'dusty':1,'anthropoid':2,'extracting':1,'manatees':1,'dust--that':1,'sea':1,'7a':1,'violets':1,'gate-posts':1,'modern':1,'mind':4,'lice':1,'bugs':1,'disguise--other':1,'gentle':1,'say':1,'have':4,'need':1,'vigorous':1,'fishes':1,'clearly':1,'relatively':1,'forced':1,'strength':1,'built':1,'-':1,'peculiarities':1,'also':8,'fitting':1,'internal':1,'take':1,'which':5,'deepening':1,'swims':1,'foot--an':1,'surfaces':1,'begin':1,'shallow':1,'lion':1,'though':2,'any':5,'proving':1,'who':1,'fishermen;':1,'falls':2,'creek':1,'most':5,'microbic':1,'eight':1,'printed':1,'nothing':1,'foothold':2,'measured':2,'why':4,'behaviour.':1,'mineral':1,'feminine':2,'mobile':2,'pulled':1,'backwards':1,'sometimes':5,'hungry':1,'absorbing':1,'solemn':1,'dissolved':1,'reflecting':1,'electrons':3,'punting':1,'hurled':1,'distinctive':1,'velocity':1,'europe.':1,'physics':1,'molluscs':1,'repeatedly':1,'precise':3,'saying':2,'permeable':1,'selection':1,'one-eighth':1,'show':1,'insects':3,'disappear.':1,'scattered':1,'fifty':2,'discovered':1,'bring':2,'attempts':1,'fiord':1,'seaweed':1,'carefully':2,'corner':2,'continually':1,'find':1,'slow.':1,'sea-snakes':1,'sharks':1,'nearer':1,'judgments':1,'quaint':1,'varied':1,'heavily':1,'grotesque':1,'gouging':1,'should':1,'surroundings':2,'only':4,'going':1,'black':1,'deepest':1,'molecules':4,'germs':1,'uppermost':1,'pegged':1,'rice':1,'local':1,'do':2,'his':5,'means':1,'beat':1,'tissues':1,'leisure':1,'famous':1,'explosively':1,'rest':1,'lighter':1,'swiftest':1,'combinations':1,'instinctive':1,'thomson':1,'dr':1,'falling':1,'endless':1,'birds.':1,'playful':1,'evolution':1,'progressive':1,'alacrity':1,'exactitude':1,'kidneys':1,'rowing':1,'mathematicians':1,'eyebrow':1,'segregating':1,'she':1,'quaternary':1,'eventually':3,'through':1,'fixed':1,'farther':3,'body':1,'bars':1,'official':1,'predicts':1,'seas':2,'intelligence':1,'radium':2,'bears':1,'bolivia.':1,'decided':1,'cenozoic':1,'sea-serpents':1,'snow-capped':1,'violet':2,'collects':1,'frequency':1,'pliocene':1,'best':1,'sameness':1,'pebbles':1,'closes':1,'combustion':1,'brave':1,'inequalities':1,'plasticity':2,'rugged':1,'pattern':2,'away':1,'trilobite':1,'stealthy':1,'gaseous.':1,'weapons':1,'north-west':2,'3':5,'mind.':1,'various':1,'gases':1,'closed':1,'between':2,'progress':1,'open-sea':1,'timber':1,'birds':4,'beasts':1,'crookes':1,'we':37,'men':1,'explosive':1,'parental':1,'importance':1,'sole':2,'industrious':1,'craters':2,'fishermen':1,'saturn':4,'death':3,'drew':1,'energy--may':1,'proterozoic':1,'invisible':3,'carbon':1,'carnivorous':1,'come':2,'bronze':1,'c':2,'enables':3,'cox':1,'mongol':1,'borneo':1,'according':2,'attributed':1,'sea-urchin':1,'became':2,'figures':1,'wringing':1,'everything.':1,'loose':1,'comes':1,'unconvincing':1,'wade':1,'stretches':1,'diversity.':1,'simple':3,'structure':2,'fitness':1,'ganymede':1,'america':1,'lake':1,'moreover':1,'extinct':1,'suppressing':1,'ether':1,'better':1,'steamships':1,'described':1,'raise':2,'one-celled':1,'travailing':3,'fro':2,'three':3,'been':1,'jerks':1,'immense':1,'willing':2,'slowly':1,'sponges':1,'likewise':1,'degrees':1,'herbage':2,'spacious':1,'6a':1,'caterpillars.':1,'partly':5,'success.':1,'lakelets':1,'turned':2,'conifers':1,'mammals.':1,'amphibians':2,'drainpipes':1,'made':3,'kids':1,'demand':1,'sifting--the':1,'worked':1,'left-handed':1,'food-canal':1,'mammals--with':1,'spain':1,'inconspicuous':2,'plants':3,'tide':1,'heavier':2,'uncertain':1,'caucasians':1,'frozen':1,'leave':1,'sex':1,'as':16,'morley':1,'air':1,'growth.':1,'calcium':1,'while':1,'lichen':1,'cannot':3,'many':11,'wild':1,'valleys':1,'voice':1,'toothed':1,'leaves':1,'at':6,'comets':2,'streams':1,'palings':1,'almost':2,'soil':1,'is':33,'thus':7,'it':79,'expenses':2,'weighed':1,'trilobites':1,'against':2,'knocks':1,'in':42,'beaver':1,'vanish':1,'currents':1,'if':13,'different':1,'feebler':1,'cools':1,'inquire':1,'muscle-cells':4,'granted':1,'bat':1,'fading':1,'cultivated':3,'unity':1,'complex':1,'grand':1,'vegetable':1,'joy.':1,'gorging':1,'engravings.':1,'day':1,'difficult':2,'development':1,'alertness.':1,'used':1,'see':2,'planting':1,'comprehensive':1,'blue-greens':1,'blue':2,'hotter':1,'drives':1,'flows':1,'hand':1,'director':1,'much':1,'moving':1,'purpose':1,'dark':3,'brussels':1,'timid':1,'climb':1,'warming':1,'cycle':1,'poultry':1,'race-continuing':1,'narrow':1,'off':1,'modes':1,'cliff-loving':1,'changes':2,'variety':1,'neptune':2,'without':4,'severe':1,'rome':1,'trains':1,'position':1,'the':357,'chemistry':2,'drawing':2,'heaps':1,'indigo':1,'birth':1,'just':2,'flesh':1,'being':1,'uranium':1,'licensed':1,'distribute':3,'adjusted':1,'actions':1,'disguise':1,'violent':1,'radio-activity':1,'distant':1,'circling':1,'human':3,'touch':1,'useful':1,'skill':1,'yet':11,'captured':1,'addresses':2,'migration':1,'superficial':2,'enters':1,'evolution.':1,'legitimately':1,'far-reaching':1,'had':2,'melanocetus':1,'undulating':1,'crocodiles':1,'lets':1,'potential':1,'4':2,'easy':1,'hind':1,'usage':1,'hydrosphere.':1,'has':3,'5a':1,'peanuts':1,'good-humoured':1,'australia':1,'rodents':1,'depends':2,'transitional':1,'bristle-tails':1,'babylonia':1,'discontinue':1,'absorptive':1,'regard':1,'early':1,'sparrows':1,'ultra-violet':1,'facial':1,'dreamt':1,'grape-sugar':1,'redistributing':1,'string':1,'apart':2,'loss':1,'phenomena':1,'tail':1,'stingless':1,'lost':1,'ill':1,'cooler':1,'beyond-blue':1,'reduces':1,'sizes':1,'tend':1,'loses':1,'harmonising':1,'donations':3,'electro-magnetic':1,'night':2,'nerves':1,'downward':1,'disorder':1,'dentition':2,'newton':1,'portuguese':1,'performing':1,'old':1,'often':8,'habitat':1,'scents.':1,'hair-like':1,'difficulties':1,'some':15,'back':3,'pacific':3,'mosquitoes':1,'ideals':1,'understood':1,'therein':1,'towards':1,'jupiter':2,'convex':1,'duration':1,'diving':2,'bruising':1,'recognition':1,'feeling':1,'einstein':1,'dimensions':1,'for':5,'broad':1,'ice':1,'moon':5,'when':13,'critical':1,'passion':1,'meaningful':1,'conquering':1,'starch':1,'27-1':1,'nose':1,'limitations':2,'be':1,'depressions':1,'novelties':1,'selecting':1,'combative':1,'lakes':1,'expansion':1,'pressure':1,'enregistering':1,'fullest':1,'although':2,'become':6,'drawn':3,'stows':1,'repair':1,'by':14,'hearing':2,'on':9,'mammoths':1,'energetically':1,'would':1,'branch-gripping':1,'temper':1,'reappear':2,'theirs':1,'moths':1,'side':1,'cockroaches':2,'whence':1,'spreads':1,'three-quarter':1,'piled':1,'little-changed':1,'gamma':3,'plan':1,'heavy':1,'rats':1,'baboons':1,'sea-grass':1,'trademark':1,'into':2,'good':1,'habituations':1,'intellectual':1,'negative':7,'chemists':2,'spinal':1,'everyone':3,'bats':2,'rapid':1,'sow':1,'formidable':1,'financial':1,'error':5,'cross-fertilisation':1,'mental':2,'arctic':2,'deep-violet':1,'sticklebacks':1,'expositor':1,'chrysanthemum':1,'well-developed':1,'flying':4,'vigour':1,'fast':1,'reflectors':1,'rushes':1,'mudstones':2,'bees':5,'caterpillars':1,'physicists':1,'stars':3,'spring':1,'molecular':1,'wonderfully':1,'was':3,'fish':1,'naturally':1,'endeavour.':1,'deepened':1,'form':4,'kittens':1,'mammals':14,'spirit':1,'magnetism':1,'analyse':1,'within':2,'wireless':1,'mysterious':1,'heat':5,'brain':1,'competition':1,'flexible':1,'fastened':1,'ear':1,'with':15,'eat':1,'he':14,'balancing':1,'pull':1,'swamp':1,'places':1,'whether':1,'dangerous':2,'two-spined':1,'hind-limbs':2,'social':2,'up':1,'sticklebacks.':1,'foresight':2,'placed':2,'growth':1,'those':4,'shape':1,'how':7,'acting':1,'distribution':2,'piece':1,'similar':5,'professor':3,'storing':2,'proud':1,'constant':2,'mimicry--the':1,'taste':1,'certain':1,'measure':1,'porcelain':1,'deep':1,'an':11,'proper':2,'female':1,'senses':1,'periods':2,'planets':1,'crystals':2,'domesticated':1,'are':16,'struggled':1,'again':1,'functions':1,'ancestors':1,'readjustments':1,'entirely':1,'charitable':1,'mantises':1,'thither':2,'power':1,'other':21,'5':1,'adventure':1,'holding':3,'becomes':1,'u':1,'you':4,'smell':1,'chemist':1,'horsetails':1,'gaining':1,'consequent':1,'formed':1,'ordovician':1,'accidental':1,'shelter':1,'uniformly':1,'inherently':1,'planarian':1,'runs':3,'walton':1,'insect':1,'marshes':1,'scores':1,'lasso':1,'stocks':1,'carries':1,'died':2,'began':5,'your':1,'independently':1,'breaks':2,'faster':1,'sperm-cells':3,'practically':3,'controlled':1,'dog':1,'mme':1,'persistent':1,'walked':1,'gorilla':2,'ensuring':1,'redivides;':1,'conveying':1,'time':1,'fresh':1,'indirectly':1,'chimpanzee--and':1,'4a':1},'sea-gooseberries':{'which':1},'spectroscope:':{'it':1},'froth':{'which':1},'silvanus':{'p':1},'ant':{'to':2,'the':1,'has':1,'where':1,'.':1},'spectroscope.':{'we':1},'fall.':{'we':1},'mates':{'.':1},'any':{'woodwork':1,'money':2,'alternative':1,'snout':1,'hint':1,'alternate':1,'had':1,'permanent':1,'very':1,'pigment':1,'provision':1,'day':1,'condition':1,'sufficiently':1,'bad':1,'inherent':1,'disclaimer':1,'nitrogenous':1,'people':1,'idea':1,'rate':2,'distributor':1,'living':2,'mud':1,'body':1,'scientific':1,'use':3,'understanding':1,'protection':1,'collection':1,'monkey':1,'on':1,'substance':3,'country':1,'length':1,'suggestion':1,'copper':1,'statements':1,'point':1,'character':1,'one':3,'learning':1,'fees':1,'quality':1,'given':1,'additional':1,'zoologist':1,'cooling':1,'way':3,'suit':1,'white':1,'waste':1,'type':1,'more':2,'files':1,'hydrosphere':1,'muscles':1,'corresponding':1,'statement':1,'form':1,'ordinary':1,'apparent':2,'direct':1,'part':2,'virtue':1,'particular':2,'copy':1,'case':8,'kind':4,'word':1,'hour':1,'work':2,'project':3,'record':1,'of':3,'age':1,'sense':1,'influence':1,'defect':1,'agent':1,'rigorous':1,'in':1,'binary':1,'angle':1,'member':1,'other':16,'you':1,'star':1,'trace':1,'rain':1,'purpose.':1,'moment':2,'purpose':1,'necessity':1,'conscious':1,'light':1,'colour':1,'person':1,'time':1,'representation':1,'volunteers':1,'irregularity':1},'confirmation':{'of':2},'transcription':{'errors':1},'ideas':{'and':4,'meant':1,'what':1,'of':8,'is':1,'when':1,'but':2,'.':4,'are':1,'in':3,';':1,'or':1},'form-resemblance':{'for':1},'sciences':{'study':1,'forcing':1},'emphasis':{'on':1},'mesohippus':{'about':1,';':1},'fracture':{'of':1},'thermometer':{'seem':1},'resembling':{'a':1,'in':1},'shafts.':{'then':1},'primaries':{'pr':1},'inky':{'darkness':1},'sure':{'on':1,'that':2,'of':1,'but':1,'.':2,'effectiveness':1},'multiple':{'of':1,'pedigree':1},'nebulae--the':{'birth':1},'azores':{'or':1},'indelible':{'stamp':2},'harmonious':{'mingling':1},'clearer':{'to':2},'falls':{'on':1,'about':1,'of':4,'obliquely':1,'as':1,'they':1,'the':2,'286':1,'more':1},'hincks':{'astronomy':1},'boiling':{'a':2,'of':1,'point.':1,'ocean':1},'donation':{'methods':1},'multiply':{'quickly':1},'cleared':{'off':1},'spectroscopist':{'is':1},'dried-up':{'and':1},'study.':{'i':1},'thigh-bone':{'and':2,'indicates':1},'considered':{'what':1,'opaque':1,'only':1,'.':2,'also':1,'as':1,'they':1,'by':1},'proud':{'as':1,'.':1,'that':1},'science.':{'these':1,'the':1,'bibliography':1,'it':1,'illustration':1},'hungry':{'sharp-eyed':1,'hermit-crabs':1,'animals':1,'eyes':1},'idea.':{'what':1},'vulgaris':{'200':1},'prout':{'suggested':1},'quantity':{'of':7,';':1,'.':2},'detective':{'story':1},'pans':{'of':1,'as':1},'permeable':{'materials':1,'so':1},'spaced':{'from':1,'with':1},'solar':{'atmosphere':1,'observer':1,'system.':4,'phenomena':2,'prominences':4,'eclipse':3,'system':34,'surface':1,'system--regions':1,'electrons':1,'envelope':1,'spectrum':3,'system--with':2,'tides':1},'radiation.':{'that':1},'inshore':{'waters':1},'hustler':{'given':1},'homology':{'essential':2},'protrusion':{'of':2},'gulf':{'was':1,'in':1},'richness':{'of':1},'gull':{'with':1},'written':{'a':1,'confirmation':1,'recently':1,'explanation':2,'.':1,'in':2,'with':1,'by':1},'crime':{'and':1},'double-breather':{'dipnoan':1,'showing':1},'wood':{'jones':1,'of':1,'or':3,'but':1},'believing':{'that':1},'dreaded':{'it':1},'lighted':{'gas':1},'closed':{'the':1,'with':1,'in':1},'ink-bags':{'are':1,'.':1},'masking':{'the':1,'for':1},'expectation':{'of':2},'space.':{'many':1,'the':1},'bolometer':{'which':1},'radiations':{'the':1,'he':1},'vive':{'ready':1},'space;':{'and':1},'antler':{'or':1},'telescopes.':{'telescopes':1},'reveal':{'to':1,'the':1,'his':1},'reality--the':{'life':1},'aluminum':{'in':1},'floods':{'to':1,'or':1,'of':1},'naked':{'eye':2,'with':1,'body.':1},'scots':{'name':1},'bison':{'and':2,'delicately':2,'above':1,'.':1},'big-brained':{'modernised':1,'skulls':1,'extremely':1,'chimpanzee':1},'pouch;':{'while':1},'fainter':{'of':1},'borings':{'might':1},'orioles':{'.':1},'discussing':{'telescopes':1,'.':1},'ignored':{'.':1},'beholding':{'they':1},'encourages':{'us':1},'foetal':{'membrane':1,'membranes':1},'stars--or':{'rather':1},'1920':{'in':1},'1921':{'attention':1,'176-177':1,'.':4,'in':2,'the':1,'meeting':1},'1922':{'by':1,'third':1,'sixth':1,'seventh':1,'ninth':1,'twelfth':1,'second':1,'eleventh':1,'fourth':1,'tenth':1,'eighth':1,'fifth':1},'disarranged':{'.':1},'enregistered.':{'in':1},'obliging':{'in':1},'collects':{'a':1,'pollen':1,'some':1},'violates':{'the':1},'encouraged':{'by':1},'surfaces':{'and':1,'hooky':1,'for':1,'of':2,'reflect':1,'in':1,'such':2},'fails':{'to':1},'invoked':{'to':1},'crystal':{'we':1,'between':1},'federal':{'tax':1,'laws':1},'subsequent':{'research':1,'eras':1,'stage':1},'birds--intelligence':{'co-operating':1},'weapons':{'and':1,'or':1},'north-west':{'australia':2},'outside':{'and':1,'we':1,'his':1,'scientific':1,'these':1,'of':2,'it':1,'himself':1,'influences':1,'our':1,'nothing':1,'world':2,'the':6},'ages.':{'illustration':1},'hiss':{'.':1},'crookes':{'and':1,'sir':1,'experimented':1,'talked':1,'tube.':1,'tube':1,'had':1,'preferred':1,'247':1,'used':1,'but':1,'in':1,'really':1,'tubes':1,'at':1},'multiplied':{'by':1},'tylor':{'e':1},'hundredth':{'but':1},'originated':{'a':1,'from':1,'by':1,'in':1},'one-mile':{'thickness':1},'densely':{'packed':1},'kea':{'or':1,'parrot':1},'multiplies':{'by':1,'in':1},'coma':{'berenices':2},'oxalic':{'acid':1},'cities':{'150':1,'because':1,'.':1,'to':1,'of':1},'come':{'and':1,'nearest':1,'into':4,'back':3,'in':2,'mysteriously':1,'out':2,'from':2,'for':1,'next':1,'to':13,'under':1,'more':1,'up-stream.':1,'presently':1,'nutritive':1,'those':1,'a':1,'about':2,'up':2,'together':3,'near':2,'.':1},'reaction':{'of':2,'between':1,'at':1,'or':1},'pests':{'were':1},'successes':{'but':1,'.':1},'primus':{'berry':1},'23':{'photo':2,'saturn':1,'1914':2,'000':1},'water-ouzel--a':{'bird':1},'quiet':{'upper':1,'unobtrusive':1},'contract':{'.':1,'except':1,'it':1},'energies':{'light':1},'berry':{'the':1},'equatorials':{'and':1,'.':1},'railway':{'siding':1,'trucks':1},'utterance':{'to':1},'surface.':{'this':1,'open-sea':1},'radio-activity':{';':1,'has':4,'we':1,'were':1},'afterwards':{'found':1,'recommence':1,'it':2,'words':1,'requires':1},'bricks':{'of':2,'out':1,'are':2,'each':1},'course.':{'this':1},'employee':{'of':1},'colony':{'of':10,'is':2,'.':1,'are':1,';':1,'south':1},'period':{'often':1,'is':2,'as':1,'including':1,'in':2,'before':2,'perhaps':1,'there':2,'when':1,'.':1,'peopling':1,'which':1,'reptiles':1,';':1,'has':1,'was':7,'we':2,'that':5,'rise':5,'during':1,'a':1,'land':1,'showed':1,'e.g':1,'of':16,'either':1,'through':1,'the':5,'90':1,'first':2},'6.':{'enregistered':1},'satisfaction':{'and':1,'in':1,'.':1},'61':{'diagram':1,'a':1},'62':{'feet':1,'inches':1},'64':{'from':1},'straws.':{'the':1},'67':{'miles':1,'000':2},'68':{'photo':1},'69':{'green':1,'reproduced':1,'proterospongia':1},'pod':{'.':1},'skeletons':{'of':5,'are':1},'noisy':{'with':1},'song-thrush':{'when':1,'takes':1},'blend':{'into':1},'pilgrims':{'for':1},'deposited':{'as':1,'in':1},'cords':{'stretched':1,'.':1},'hardly':{'even':1,'be':6,'needs':1,'necessary':2,'pauses':1,'conceive':1,'seems':1,'change':1,'imagine':1,'counts':1,'tenable':1,'inferior':1,'too':1},'500':{'pounds':1,'000':4,'to':1,'miles':1,'fathoms':3,'yards':1,'extinct':1,'deg':1},'501':{'c':2},'6a':{'hipparion':1},'direction':{'towards':1,'whereby':2,'that':1,'of':6,'is':1,'when':1,'.':2,'as':1,'contrary':1,'in':4,'taken':1,';':1},'forecloses':{'the':1},'robbed':{'of':1},'radiates':{'heat':1},'tiger':{'begins':1,'the':1},'implied':{'a':3,'getting':1,'many':1,'.':4,'including':1,'in':2,'an':3,'was':1,'warranties':1},'sea-horses':{'phyllopteryx':1},'eaters':{'in':1},'attentive':{'persistent':1},'squirrels':{'quickly':1,'which':1,'.':1},'robber':{'crab':1},'paying':{'any':1,'copyright':1},'specialised':{'member':1,'instincts':1},'caucasians':{'we':1,'include':1},'mount':{'on':1,'wilson':16,'hermon':2,'everest':1},'twigs':{'very':1},'life;':{'precise':1},'premature':{'to':1},'vegetation--an':{'awkward':1},'slippery':{'bridge':1},'life.':{'origin':1,'wallace':1,'similarly':1,'many':1,'there':1,'wherever':1,'it':1,'illustration':1,'sec':2,'they':1,'volunteers':1,'if':1},'mound':{'.':1},'hunts':{'small':1,'vigorously':1},'focussed':{'on':1},'trackless':{'waste':1},'another--to':{'pass':1},'person.':{'besides':1},'someone':{'not':1,'said':1},'anti-bodies':{'which':1},'unsounded':{'i.e':1},'uncatchable':{'in':1},'meals.':{'there':1},'helmet':{'or':1,'.':1},'revolutions':{'a':1,'round':1},'author':{':':1},'alphabet':{'of':2,'the':1},'granted':{'tax':1,'but':1},'skips':{'the':1,'about':1},'knowable':{'way':1},'motley':{'crowd--we':1,'into':1},'a-b.':{'newer':1},'buys':{'a':1},'implement.':{'on':1},'generated':{':':1},'status':{'of':2,'with':1,'by':1},'wall-like':{'formation':1},'males':{'six':1,'especially':1,'that':1},'disadvantages':{'for':1},'pays.':{'when':1},'nest':{'and':2,'or':2,'to':1,'else':1,'of':3,'into':1,'191':1,'.':2,'how':1,'while':1,'which':2,'in':5,';':1,'several':1,'with':2,'the':6,'is':1,'out':1},'insects.':{'whether':1,'mesozoic':1,'devonian':1},'tree-toad':{'whose':1},'drives':{'off':2},'weed':{'120':1,'.':1},'director':{'of':1,'gbnewby':1},'persons':{'bearing':1,';':1,'is':1},'arose':{'and':1,'what':1,'we':1,'.':1,'as':1,'races':1,'various':1,'the':3,'or':1},'changing':{'natural':1,'energy':1,'process':1,'colour':1,'conditions':1,'its':1},'implements':{'a':1,'instruments':1,'were':1,'or':1,'.':1},'marsh.':{'the':1,'six':1},'perennial':{'tendency':1},'safely':{'be':1,'away':1},'shift.':{'we':1},'magical':{'glass':1,'way':1},'without':{'saying':1,'seeing':1,'being':2,'intelligence':1,'ceasing.':1,'an':2,'as':1,'at':1,'further':1,'domesticated':1,'any':6,'heat--forms':1,'trying':1,'thinking':1,'there':1,'.':4,'doing':1,'charge':1,'much':1,'too':1,'fatiguing':1,'prominently':1,'reading':1,'measuring':1,'mentioning':1,'them':2,'committing':1,'permission':1,'sufficient':1,'significance':1,'noticing':1,'free':1,'heat':2,'a':3,'supposing':1,'disparagement':1,'complying':1,'trouble--an':1,'conspicuous':1,'sacrificing':1,'paying':2,'wide':1,'that':1,'getting':1,'stimulus':1,'this':1,'fertilisation':1,'the':7,'having':1},'model':{'of':2,'is':1,'by':4,'seen':1},'reward':{'and':1,'of':1},'bodies':{'and':1,'certain':1,'held':1,'are':3,'in':1,'whose':1,'would':1,'had':1,'.':1,'behave':1,'which':1,'has':1,'we':1,'dependent':1,'acquire':1,'but':1,'fall':1,'represented':1,'i.e':1,'with':1,'like':1,'considered':1,'of':2,'up':2,'the':2,'having':1},'justify':{'themselves':1,'the':2,'all':1},'clog':{'the':1},'when':{'and':1,'this':4,'all':1,'full-grown':1,'dealing':1,'it':34,'competition':1,'one':3,'appropriate':1,'jupiter':1,'something':1,'human':1,'in':2,'seen':1,'cold':2,'abundant':1,'its':1,'even':1,'compared':2,'to':1,'observing':1,'caught':2,'there':6,'young':2,'sunlight':1,'birds':2,'needed':1,'only':3,'bombarded':1,'sponges':1,'lizzie':1,'tens':1,'you':3,'he':9,'resting':1,'we':31,'his':1,'scientific':1,'parental':1,'liberated':1,'however':2,'atoms':1,'water':1,'moving':2,'two':2,'they':16,'put':1,'an':7,'with':1,'man':3,'a':19,'great':1,'revolved':1,'animals':1,'these':2,'of':1,'professor':1,'applied':1,'she':2,'baits':1,'enough':1,'small':1,'hot.':1,'the':82,'grass':1,'at':1},'guided':{'astronomers':1},'actions':{'and':4,'among':1,'show':1,'becoming':1,'but':1,'.':4,'cease':1,'are':1,'which':2,'living':1,';':1},'violent':{'and':1,'death':1,'end':3,'disturbances':1,'agitation':1,'motion':3,'discharge':1,'movement':1},'cease':{'to':1,'is':1,'in':1,'using':1},'anamnia':{'the':1},'mongoose':{'riki-tiki-tavi':1},'differentiation':{'of':1,'.':1},'polish':{'wife':1},'colonise':{'the':2},'captured':{'a':2,'arm':1,'for':1,'.':1},'blow':{'from':1},'gentleness':{';':1},'widest':{'and':1,'array':1,'variety':1},'hint':{'of':5},'--from':{'unicellular':1},'rose':{'and':1,'on':1,'above':1,'in':1},'favouring':{'certain':1,'the':1},'except':{'about':1,'for':3,'that':6,'electricity':1,'when':1,'in':8,'upon':1,'to':1,'as':1,'red':1,'violet':1,'the':7,'those':1,'man':1},'great.':{'illustration':1},'lets':{'it':1},'interested':{'in':1},'samples':{'of':1},'hind':{'part':1,'end':1,'.':1},'engulfed':{'.':1},'stagnant':{'lifeless':1},'nekton':{'and':1},'sociality':{'.':1},'men-of-war':{';':1},'kingdom':{'we':1,'of':1,'.':2,'not':1,'the':1,'where':1},'crustaceans':{'and':3,'lamp-shells':1,'insects':1,'insect':2,'can':1,'which':2,';':1},'confines':{'the':1},'action.':{'what':1},'confined':{'to':2,'so':1,'our':1},'characteristically':{'vital':1},'shore-haunts.':{'following':1},'accepted':{'theory':1,'that':1,'it':1,'but':1,'which':1,'in':1},'left-hand':{'photograph':2,'side':1},'acute':{'senses':1,'especially':1},'standstill':{'that':1},'particle':{'that':1,'of':8,'is':1,'which':1,'becomes':1,'was':1},'harmonising':{'the':1},'patrick':{'sheriff':1},'reduces':{'to':1,'friction':1},'multifarious':{'tasks':1},'sieves':{'with':1,'by':1},'sternly':{'regulated':1},'petrie':{'has':1},'donations':{'received':1,'from':2,'1':1,'to':4,'can':1,'in':2,'or':1,'are':2},'always':{'new.':1,'human':1,'being':1,'have':1,'in':5,'ring':1,'giving':1,'regarded':1,'had':1,'tend':1,'presents':1,'to':2,'setting':1,'black':1,'going':2,'receiving':1,'that':1,'clear-cut':1,'refused':1,'lives':1,'recognise':1,'put':1,'envelops':1,'aiming':1,'present':2,'a':1,'on':1,'turns':1,'or':1,'overlappings':1,'remain':1,'points':1,'so':1,'hobbled':1,'the':2,'think':1},'tower':{'above':1},'reduced':{'to':3,'the':1,'from':1,'for':1,'.':1},'burdens':{'of':1},'competition':{'e.g':1,'is':1,'but':1,'.':1,'in':1,'or':1},'deduce':{'more':1},'respect':{'most':1,'with':1},'oftener':{'than':1},'intact':{'ones':1},'leadbeater.':{'an':2},'chewing':{'a':1},'provided':{'to':1,'you':1,'that':1,'by':1,'in':1},'mood':{'at':1},'prolific':{'and':2,'multiplication':2,'early':1,'have':1,'though':1},'defenceless':{'weaponless':1},'legal':{'fees':2},'moon':{'and':4,'because':1,'exert':1,'28':1,'is':5,'newton':1,'it':1,'as':1,'at':2,'entering':2,'------':1,'32':1,'are':1,'passes':1,'from':1,'takes':1,'would':1,'began':1,'when':1,'.':15,'to':1,'of':1,'fig':1,'mars':1,';':1,':':1,'was':6,'split':1,'do':1,'we':1,'nearer':1,'may':1,'showing':1,'were':2,'took':1,'but':7,'crosses':2,'gets':1,'by':1,'partially':1,'has':2,'turns':1,'s':6,'act':1,'the':2,'makes':1,'farther':1},'depletion':{'of':1},'moot':{'point':1},'provides':{'the':3,'means':1},'out-side':{'influences':1},'freed':{'from':2},'lop-eared':{'forms':1},'ovaries':{'and':1},'nails':{'and':1,'in':1},'stereotyped':{'routine':1,'was':1,'bee':1},'communicate':{'some':1},'voracious':{'and':1,'insect':1},'journeyman':{'.':1},'resurrection':{'of':1},'affording':{'food':1,'most':1,'as':1},'on':{'all':1,'minced':1,'september':1,'isolated':1,'disguise':2,'through':1,'human':2,'earth':5,'its':31,'apace':1,'dividing':1,'true':1,'young':1,'better':1,'to':21,'board':2,'stable':1,'photographs':1,'brown':1,'them':3,'his':4,'around':1,'returning':1,'possible':1,'trees':2,'firmer':1,'sea-lettuce':1,'five':1,'probably':1,'radio-active':1,'one':5,'jupiter.':1,'evolution':3,'likeness':1,'january':1,'sufficiently':1,'sand':2,'each':5,'small':1,'them.':1,'entirely':1,'page':1,'saturn.':1,'transcribe':1,'some':4,'biology':1,'yerkes':2,'individual':1,'entering':1,'our':2,'special':1,'creatures':1,'what':1,'for':2,'god':1,'mars.':1,'ice':3,'various':1,'affecting':1,'progress':1,';':2,'receiving':1,'red':1,'can':1,'columbus':1,'wheat':2,'whose':1,'evolving':1,'atoms':1,'water':1,'by':3,'dry':4,'both':2,'backwards':1,'repeating':1,'leaves':1,'american':1,'islands':2,'passing':2,'or':1,'this':11,'striking':1,'hearing':1,'another':3,'einstein':1,'trust':1,'from':2,'her':3,'their':10,'top':1,'there':1,'two':1,'.':12,'183':1,'moisture':1,'mars':10,'until':1,'life':1,'clever':1,'that':3,'mammals':1,'exactly':1,'back':1,'bipedal':1,'with':1,'those':1,'must':1,'plants':2,'account':2,'these':4,'mount':2,'up':1,'air':2,'three':1,'under':1,'and':3,'withered':1,'gate-posts':1,'in':9,'surpassing':1,'slowing':1,'an':10,'protective':1,'planets':1,'further':1,'floating':1,'any':1,'different':3,'inborn':1,'wits':1,'radiation':1,'snow':1,'close-packed':1,'other':1,'sandy':2,'animal':1,'accumulating':1,'towards':1,'lanky':1,'it':8,'herbs':1,'itself.':1,'occasion':1,'such':1,'intrinsic':1,'parallel':1,'a':63,'land':6,'to-day':1,'decaying':1,'we':1,'which':18,'green':2,'every':4,'the':294,'berries':1,'again.':1},'beavers':{'who':1},'discussed':{'elsewhere.':1,'separately':1,'in':2},'chamberlin':{'and':1,'s':1,'says':2},'shrimp':{'net':1},'20417.zip':{'this':1},'whence':{'the':3,'man':1,'is':2,'they':2,'he':1},'stop.':{'illustration':1},'stand':{'in':1,'out':1,'alone.':1},'prism--a':{'triangular-shaped':1},'discrimination':{'of':1,'with':1,'between':1},'gregory':{'b':1},'investigators':{'professor':1,'.':1},'or':{'partial':1,'suns':1,'four':3,'nursery':1,'go':2,'layers':1,'brackish':1,'hunting':2,'electricity':1,'unenforceability':1,'young':2,'to':10,'under':1,'teaching':1,'division':1,'devonian':1,'fall':1,'animals':2,'whirlpools':1,'elevations':1,'squids':1,'alevins':1,'redistribute':1,'corpuscles':1,'clouds':1,'die':1,'frozen':1,'glaciations':1,'greenish':1,'small':1,'mammal':1,'autotomy.':1,'caries':1,'upper':1,'frog-mouth':1,'pass':2,'further':1,'even':16,'what':1,'adds':1,'fitnesses':1,'pipes':1,'paddle':1,'access':1,'above':1,'new':3,'thereabouts':1,'movement':1,'segmentation':1,'men':1,'water':1,'protection':1,'along':1,'extreme':1,'sending':1,'thirty':2,'brilliant':1,'wherever':1,'experience':1,'patagium':1,'formation':1,'threes':1,'feelings':1,'semang':1,'total':1,'herring':1,'tertiary':1,'engrain':1,'use':2,'from':5,'two':4,'distributing':3,'almost':2,'more':8,'becomes':1,'envelope':1,'about':1,'train':1,'rabbit':1,'breach':1,'glad':1,'must':1,'flagellum':1,'strain':1,'averaged':1,'can':1,'nothing.':1,'marble':1,'mud-fishes':1,'proprietary':1,'brown':1,'pulling':1,'something':1,'serum':1,'axis':1,'disappearing.':1,'six':3,'chemical':2,'how':2,'fourth':1,'re-use':2,'stock':1,'gonads':1,'communicating':2,'after':3,'eighty':1,'mankind':1,'a':33,'elusive':1,'light':2,'hypotheses':1,'coal':2,'so':4,'deterioration':1,'playing':1,'foetal':1,'refund':3,'sperm-cell':1,'evolutionary':1,'self-destructively':1,'rottenness':1,'double-breather':1,'hypertext':1,'years':1,'lumpsucker':1,'secondaries':1,'pterodactyls':2,'group':1,'lateral':1,'destroyed':2,'animal':1,'pglaf':1,'repulsive':1,'they':1,'weeds':1,'not':2,'detach':1,'adventurous':1,'bubbles.':1,'magnitude':1,'fitness':1,'beneath':1,'mental':1,'agriculture':1,'out':1,'dying':1,'cause':1,'alevin':1,'shut':1,'approached':1,'siege':1,'eternal':1,'rotifer':1,'duck-billed':3,'telescopes':1,'nebulae':1,'rearrangements':1,'wanderers':1,'audacity':1,'disturbed':1,'lemurs':1,'stone':1,'unborn':1,'zoophyte':3,'south':1,'emotion':1,'blown':1,'another':1,'flagella':1,'foraminifera':2,'monkey':1,'pelagic':1,'anyone':1,'their':2,'185':1,'white':1,'muscles':1,'immediate':1,'sea-scorpions':1,'egg-producer':1,'patches':1,'meteors':1,'grey':1,'actively':1,'iron':1,'were':1,'providing':2,'sea-gooseberries':1,'chrysalis':1,'shell':2,'have':2,'cleverness':1,'organs':1,'any':9,'built':1,'lumps':1,'camouflage':1,'gunnel':1,'take':1,'online':3,'destroy':2,'spawns':1,'primaries':1,'easygoing':1,'centres':2,'breaking':1,'invertebrate':1,'successive':1,'measured':1,'darkness':1,'sea-butterflies':1,'nostrils':1,'later':3,'dissolved':1,'electrons':1,'salt':1,'planetary':1,'distributed:':1,'nest-building':1,'bright':1,'archimedes':1,'seaweed':1,'entity':3,'find':1,'only':3,'wood':1,'black':1,'employee':1,'shepherding':1,'fossil':1,'get':1,'eel-fare':1,'fronds':1,'cannot':1,'preparing':1,'instinctive':2,'primates':1,'stone.':1,'devoured':1,'amid':1,'parasitic':1,'remove':1,'twice':1,'steam':1,'kernel':1,'seventeen':1,'ebb':1,'intelligence':1,'testing':1,'computer':1,'are':2,'corrupt':1,'eoliths':1,'federal':1,'away':1,'rings':1,'waltzing':1,'its':1,'weapons':1,'mud':1,'between':1,'nestor':1,'across':1,'deletions':1,'incarnation':1,'creating':2,'sole':1,'podargus':2,'invisible':2,'1.e.9.':2,'sperm-producer':1,'many':3,'region':1,'water-ouzel--a':1,'strains':2,'expense':1,'expression':1,'experimental':1,'mutating':1,'among':1,'adjusted':1,'mutations':3,'whatever':1,'extinct':2,'late':1,'gregarious.':1,'one-celled':1,'create':1,'three':5,'protoplasm':1,'thrice':1,'rather':1,'general':1,'else':1,'elvers':1,'homes':1,'solid':1,'dendrites':1,'replaced':1,'argonaut':1,'wild':2,'layer':1,'diaphragm':1,'is':1,'squid':2,'it':5,'cluster':1,'to-morrow':1,'anti-bodies':1,'in':14,'if':1,'damaged':1,'perhaps':1,'cromagnard':3,'shorter':1,'dermis':1,'double-breathers':1,'big':1,'mud-skipper':2,'prominences':1,'foam':1,'infinite':1,'staving':1,'reflection':1,'charges':4,'well':1,'command':2,'comes':1,'mother':2,'the':23,'left':1,'less':14,'cromagnards':1,'distribute':2,'egg-cell':1,'obtain':1,'fishing':1,'anamnia':1,'multiples':1,'vibration':1,'absorption':1,'killed':1,'dipper':1,'irresponsive':1,'humanity':1,'photographed':1,'tracheae':1,'early':1,'possibly':1,'gyrating':1,'five':2,'using':1,'modifications':1,'appearing':1,'feral':2,'post-glacial':2,'incidental':1,'eel':1,'vortex':1,'ctenophores':1,'often':1,'crown':1,'dead':1,'sponge':1,'indirect':1,'bruising':1,'for':2,'memories':1,'does':1,'glacial':1,'disproved--e.g':1,'enregistering':1,'by':10,'on':5,'limitation':3,'chaff':1,'central':1,'of':11,'20417.zip':1,'octopus':2,'sea-grass':1,'down':1,'because':3,'determine':1,'protozoa':1,'additions':1,'her':1,'camouflaging':2,'incipient':1,'sneezing':1,'was':2,'pinna':1,'some':3,'amongst':1,'heat':1,'shoulder-blade':1,'trying':1,'with':3,'whether':1,'dangerous':1,'variations':2,'frugivorous':1,'associated':1,'taste':1,'an':3,'as':3,'furl':1,'again':1,'dimly':1,'inborn':1,'when':3,'other':8,'dies':1,'casque':1,'nucleus':2,'pycnogon':1,'sneeze':1,'vice':1,'vehicles':1,'implied':1,'indirectly':3},'amber':{'trade':1},'cambridge':{'university':1,'manual':1,'.':3},'columbia.':{'the':1,'fig':1},'communication':{'that':1,'between':2},'charts':{'we':1},'spinal':{'canal':1,'cord':4},'clams':{'in':1},'accounts':{'for':1},'determine':{'the':3,'what':1,'survival':1},'cro-magnon':{'in':1},'speculated':{'on':1},'theoretically':{'a':1,'that':1},'buds':{'out':1},'pycnogon':{'walking':1},'whales':{'and':1,'great':1,'.':1,'which':1,'largely':1},'distinctions':{'except':1},'strictly':{'marine':1},'there':{'and':1,'emerge':1,'exists':2,'being':1,'had':4,'is':259,'191':1,'results':2,'one':1,'diverged':2,'are':142,'have':7,'in':3,'.':5,'any':2,'seemed':1,'emerges':1,'rises':1,'appear':1,'would':2,'seems':7,'been':2,'actually':1,'may':10,'only':1,'other':1,'probably':2,';':1,'has':12,'was':42,'ought':1,'be':1,'life':2,'an':1,'intervened':1,'some':1,'took':1,'illustration':1,'soon':1,'depressing':1,'cannot':1,'lives':1,'arose':2,'they':1,'not':5,'now':1,'comes':1,'depended':1,'a':3,'on':1,'are.':1,'should':3,'could':2,'will':5,'remain':2,'must':7,'can':11,'evolved':4,'were':26,'the':1,'might':1,'makes':1,'came':3},'disposed':{'to':2},'dispersion':{'is':3,'can':1},'strict':{'liability':1,'sense':3},'world--weighs':{'nearly':1},'house':{'of':1,'.':2,'to':1,'against':1,'on':1},'macaques':{'and':1,'the':1},'fish':{'and':2,'is':4,'it':2,'117':1,'at':1,'118':1,'firmly':1,'takes':1,'lizards':1,'flying':1,'when':1,'.':2,'to':2,'which':4,'probably':1,'has':1,'arges':1,'stock':1,'that':1,'ceratodus':1,'chiasmodon':2,'with':2,'like':1,'of':1,'larger':1,'grows':1,'the':3,'male':1,'makes':1,'called':1},'eoanthropus':{'expresses':1},'relic':{'of':3,'were':1},'kittens':{'or':1},'account.':{'since':1},'troubles.':{'another':1},'amongst':{'fishes':1,'the':8,'themselves':1,'them':1,'all':1},'instrument.':{'a':1},'strenuous':{'life.':1,'life':3,'conditions':1,'time':2},'promote':{'variability':1},'faster':{'and':1,'than':4,'.':2},'applying':{'severe':1},'bullet':{'and':1,'thirty':1,'leaves':1,'illustration':1,'one':1,'itself':1,'does':1,'the':1},'multiplicity':{'.':1},'electroscope':{'is':1},'centenarian':{'tortoise':1},'grasp':{'begins':1,'probably':1,'the':1,'an':1},'grass':{'and':2,'gathering':1,'forming':1,'the':1,'was':1,'he':1},'creeping':{'of':1,'about':1,'upwards':1},'strongly':{'developed':1,'illumined':1},'accentuated':{'by':1},'words:':{'bone':1},'stock.':{'every':1},'taste':{'do':1,'may':1,'of':1,'seems':1,'which':1,'in':1},'yacht':{'and':1},'lingula':{'of':1},'tactics--self-effacement':{'on':1},'britain':{'and':2,'do':1,'we':1,'just':1,'it':1,'has':1,'having':1},'curly-or':{'wavy-haired':1},'diverged':{'far':1,'the':2,'from':1},'orchards':{'descended':1},'corresponding':{'ratio':1,'magnetic':1,'to':10,'bright':1,'stages':1,'hump':1},'russel':{'wallace':1},'operation':{'of':1,'to-day':1},'collared':{'lashed':1},'deserve':{'for':1},'discerned':{'in':1},'shore-haunt':{'and':2,'littoral':1,'as':1,'are':1,'exhibits':1},'compel':{'the':1},'erecting':{'standing':1},'spring-tails':{'and':1},'blackish-grey':{'.':1},'f.z.s.':{'seasonal':1,'professor':1,'banded':1,'rock':1,'the':3,'woodpecker':1},'meteorites--pieces':{'of':1},'cock-pigeon':{'very':1},'deviation':{'it':1},'briefly':{'the':1,'discussed':1,'outline':1},'separate':{'and':1,'animals':1,'study.':1,'engines':1,'tuft':1,'whirling':1,'off':1,'entity':1,'universes--':1,'threads':1,'molecules':1,'existence':1,'genus':1},'manipulate':{'puzzle-boxes':1},'symbol':{'of':1},'carnegie':{'institution':2},'includes':{'not':1,'information':1,'all':2,'thousands':1,'the':2},'gutenberg':{'web':1,'associated':1,'license':3,'is':3,'ebook':4,'literary':13,'are':1,'you':1,'volunteers':1,'appears':1},'nucleus':{'and':2,'then':1,'we':1,'gr':1,'rather':1,'of':5,'is':1,'but':1,'.':4,'to':1,'are':1,'in':1,'into':1,';':1,'has':1,'or':3},'recognise':{'a':1,'both':1,'them':1,'that':1,'these':1,'an':1,'as':2,'progress':1,'the':6,'accessory':1},'fasten':{'themselves':1},'included':{'a':1,'was':1,'with':2,'.':2,'in':2,'the':1,'has':1,'numerous':1},'stocks':{'began.':1,'of':3,'began':1,'within':1,'it':1,'but':1},'irretraceable':{'course.':1},'bustard.':{'such':1},'atromaculatus':{'121':1,'in':1},'missed':{';':1},'meadow':{'it':1},'bilateral':{'symmetry.':1,'symmetry':2},'calls':{'of':1,'the':3,'it':1,'adaptive':1},'wife':{'took':1},'splendour.':{'they':1},'environment.':{'1':1,'sec':1},'eighty-odd':{'chemical':2},'migrated':{'to':1,'from':2},'all':{'opinions':1,'over':3,'mending':1,'four':1,'thoughtful':1,'through':3,'its':2,'except':2,'monkeys':1,'forms':1,'to':3,'only':1,'reptiles':2,'easy':1,'circle':1,'his':5,'liability':2,'they':1,'day':2,'processes':1,'50':1,'these':6,'works':1,'cells':1,'mean':1,'angles--that':1,'because':1,'energy':1,'hard':1,'phenomena':1,'are':1,'our':3,'shoots':1,'enemies':1,'respects':1,'space':1,'access':1,'outside':1,';':3,'be':1,'we':1,'scientific':1,'here':1,'atoms':2,'magnetism':2,'directions.':1,'members':1,'clues':1,'directions':3,'along':1,'likelihood':3,'things.':1,'mingled':1,'of':7,'round':3,'speeds':1,'probability':2,'point':1,'three':1,'chemists':1,'references':2,'sounds':1,'use':1,'her':1,'flying':1,'copies':2,'.':7,'scions':1,'conceivable':1,'molecular':2,'was':1,'life':2,'that':3,'but':2,'cases':2,'white':3,'those':2,'inconspicuous':1,'animals':2,'this':4,'originally':2,'appearance':2,'air':1,'matter':7,'were':1,'meet':1,'stages':2,'at':2,'and':1,'associated':1,'sorts':6,'is':3,'modern':2,'it':1,'as':1,'manner':1,'walks':1,'perhaps':3,'things':4,'make':1,'when':2,'detail':1,'how':1,'other':1,'which':1,'creatures':1,'higher':2,'kinds':1,'moving':2,'such':1,'in':2,'attaining':1,'time':1,'the':81,'bodies':2},'lack':{'of':2},'muscle-fibres':{'grow':1,'in':1},'son.':{'the':1,'alsatian':1},'seals':{'and':1,'.':1},'light-waves':{'and':1,'into':1,'.':2,'are':1,'which':1,'the':2},'disc':{'and':1,'for':1,'of':4,'.':2,'eight':1,'was':1},'dish':{'and':1},'follow':{'sir':1,'that':1,'it':1,'however':1,'till':1,'the':4,'with':1,'their':1},'disk':{'or':1},'decisions':{'were':1},'synthetic':{'chemists':2,'chemist':1},'glimpse':{'of':8,'the':1,'in':1},'deliberateness':{'and':1,'.':1},'meteorites--a':{'great':1},'subjected':{'.':1},'extraneous':{'source':1},'presentation':{'of':1},'tethered':{'on':1},'activities':{'and':1,'influenced':1,'may':1,'of':1,'.':1,'implying':1,'as':1},'belonging':{'to':1},'means--light':{'without':1},'worse':{'to':1,'for':1,'.':1},'devonian':{'a':1,'age':1,'period':4,'seas.':1,'lung-fishes':1,'foot-print':1,'the':1,'red':1},'song':{'of':1},'infringement':{'a':1},'combustible':{'material':1},'educative':{'process':1},'induce':{'fresh':1},'psychologist':{'whom':1},'sons':{'new':1,'first':1},'fan':{'or':1,'like':1,'by':1},'hatching':{';':1,'out':2,'.':1},'awful':{'possibility--involution':1},'time--wherein':{'to':1},'soles':{'with':1},'rhodeus':{'amarus':2},'corpuscles':{'and':1,'called':1,'form':1,'.':1},'morley':{'tried':1},'stimulus':{'almost':1,'of':1,'.':1,'travels':1,'to':2,'such':1},'eye-sockets':{'the':1},'list':{'may':1,'of':3,'is':1,'to':1},'prolonged':{'training':1,'period':1,'ice':1,'youthfulness':1,'ante-natal':1,'the':1,'trying':1,'drought':2,'exposure':1},'rods.':{'2':1},'indemnity':{'-':1},'familiarly':{'seen':1},'dexterity':{'and':1,'until':1,'besides':1,'.':1},'lightner':{'witmer.':1},'rats':{'and':4,'learn':1},'depths.':{'a':1,'illustration':1},'ten':{'and':1,'pounds':3,'of':1,'thousand':3,'times':1,'hours':2,'to':1,'straws':1,'unseen':1,'moons':1,'hours--a':1,'our':1,'years':1,'minutes':2},'foreground':{'holding':1},'fringing':{'the':1,'teeth':1},'tea':{'or':1},'reins':{'at':1,'in':1},'breakers':{'.':1},'000-50':{'000':1},'rate':{'a':1,'from':2,'that':1,'of':15,'which':1,'than':1},'invention':{'and':1,'of':1,'.':1,'first':1,'that':1},'1904-5':{'in':1},'s-beak':{'jaws':1},'functioning':{'properly':1,'throughout':1,'.':1},'remarkably':{'representative':1},'toe.':{'illustration':1},'paralyse':{'and':1},'babylonia':{'egypt':1,'greece':1},'what':{'origin':1,'this':3,'all':1,'right':1,'followed':3,'is':49,'it':4,'evidence':1,'are':10,'in':1,'peter':1,'causes':1,'before':1,'happens':2,'sir':1,'would':1,'matter':1,'electricity':1,'agency':1,'does':1,'goes':2,'resulted':1,'new':1,'you':1,'has':4,'might':5,'energy':1,'crookes':1,'sort':1,'then':2,'we':20,'elements':2,'electric':1,'may':5,'mammals':1,'of':1,'looks':2,'took':1,'mimics':1,'heat':1,'fruit':1,'mankind':1,'they':9,'satellites':1,'an':1,'come':1,'appears':1,'those':1,'man':1,'a':7,'great':1,'animals':1,'these':1,'was':8,'professor':1,'osborn':1,'more':1,'she':2,'were':1,'happened':1,'about':1,'the':18,'gives':1,'makes':1,'could':1,'bond':1},'necessary.':{'a':1},'imported':{'from':1},'advantageous':{'to':1,'than':1,'power':1,'for':1},'sun':{'and':22,'compare':1,'already':1,'often':1,'produces':1,'is':20,'in':5,'constitute':1,'ceased':1,'as':3,'itself':2,'sec':1,'looks':1,'uranus':1,'year':1,'------':1,'our':1,'are':2,'before':1,'mercury':1,'passes':1,'from':1,'would':5,'seems':1,'.':23,'to':4,'must':2,'without':1,'which':4,'dying':2,';':1,'has':4,'was':2,'into':1,'photographed':2,'we':4,'goes':1,'that':4,'may':1,'forming':1,'obscures':1,'however':1,'but':2,'cannot':1,'every':1,'here':1,'somewhat':1,'not':1,'with':2,'nearly':1,'like':2,'a':1,'whose':1,'19':1,'18':1,'could':1,'sweeps':1,'or':1,'s':35,'became':1,'flame':1,'can':1,'have':1,'were':2,'at':2,'the':7,'called':1,'thanks':1},'sum':{'up':1},'ticks':{'of':1},'crust':{'and':2,'of':3,'.':3,'brought':1,'has':1,'with':2,'by':1},'brief':{'moments':1,'outline':1},'version':{'posted':1},'for--may':{'have':1},'maze--which':{'they':1},'discern':{'the':2,'that':1},'heat-measuring':{'instrument':1},'cheetahs':{'or':2,'occur':1},'segmentation':{'of':1},'toes':{'and':1,'a':1,'scrambling':1,'form':1,'shorten':1,'.':3,'as':1},'tags':{'of':2},'ceratodus':{'which':1},'berthelot':{'that':1},'behaviour':{'and':2,'show':1,'is':5,'reaches':1,'depends':1,'sec':1,'are':1,'had':1,'.':8,'may':3,'which':6,'was':1,'we':1,'that':1,'very':1,'but':2,'diagram':1,'76':1,'on':1,'both':1,'of':15,'without':2},'inverse':{'ratio':1,'order':1},'compressed':{'body':1,'marked':1},'directions':{'and':1,'becoming':1,'within':1,'.':3,'as':1,'indicative':1,'at':2,';':1},'steamships':{'to':1},'observing':{'carefully':1,'all':1,'the':1},'water-shed':{'to':1},'chlorophyll-possessing':{'plants':1},'29.46':{'73000':1},'difficulty':{'of':1,'is':1,'about':1,'in':3},'1843':{'had':1},'1842':{'.':1},'allows':{'life':1,'for':1},'1845':{'of':1},'miniature':{'frogs':1,'solar':1,'.':1},'extremes':{'of':1,'are':1,'to':1},'reshufflings':{'or':1},'m.f.':{'near':1},'2163':{'--':1},'cataract':{'gives':1},'sticking':{'out':3},'disposition':{'taking':1},'suddenly':{'seized':1,'fired':1,'attacked':1,'this':1,'lights':1,'into':1,'perceive':1,'being':1,'so':1,'in':1,'rising':1},'semites':{'nordics':1},'bathers':{'are':1},'screens':{'in':1},'mme':{'.':1},'color':{'of':1},'1908':{'33':2,'notice':1,'the':1},'rainbow-tinted':{'colours':1},'know.':{'the':1},'1907':{'by':2},'coatings':{'is':1},'1905':{'22':1,'illustration':1},'herring':{'and':1,'illustrations':1,'the':1,'family':1,'would':1},'1900':{'by':1,'that':1},'1901':{'but':1},'unthinkably':{'long':1},'pervades':{'everything--so':1},'proceed':{'to':1,'from':2,'at':1},'degree.':{'until':1},'faint':{'and':2,'indications':1,'star':1,'.':1,'to':2,'impressions':1,'or':1},'unthinkable':{'on':1},'minor':{'chapter':2,'invasions':1,'alterations':1,'ones':1,'idiosyncrasies':1,'speculated':1},'horses':{'and':5,'a':1,'or':1},'flat':{'forehead':1,'on':2,'as':1,'spider':1,'skull':1},'darting':{'hither':1},'knows':{'his':1,'for':1,'that':1,'of':1,'but':2,'to':1,'only':1,'how':1,'the':1,'monkeys':1},'light-years':{'polaris':1},'definition':{'is':1},'coating':{'and':1},'text.':{'illustration':3},'screen.':{'the':1,'now':1},'flit':{'by':1},'stick':{'might':1,'with':1,'so':1,'to':1,'it':1},'known':{'and':5,'sources':1,'as':10,'human':1,'in':2,'from':1,'excepting':1,'approximately':1,'.':4,'bird--evidences':1,'to':15,'only':2,'easy':1,'between':1,'bird--too':1,':':1,'type':1,'bird':4,'then':1,'that':4,'but':2,'atom':1,'predecessors':2,'on':1,'about':2,'attempt':1,'of':3,'amphibian':1,'the':1,'fact':1},'glad':{'to':1},'presumed':{'evolution':1},'primate':{'stem':2,'stock':2},'sense-presentation':{'and':1},'lung-fish':{'inside':1},'v':{'the':1,'.':2},'--jupiter':{'and':1},'excursion':{'in':1},'tennis':{'ball.':1},'computers':{'including':1,'.':1},'hormones--itself':{'of':1},'brown':{'and':2,'plants':1,'that':1,'colour':1,'variety':1,'box':1,'bear':3,'plumage':1,'ones':2,'seaweed':1,'in':1,'variable':1,';':1,'on':1,'stoat':1},'bright--the':{'light':1},'joints':{'in':1},'locating':{'sounds':1},'abandonment':{'of':1},'moorhens':{'was':1,'which':1},'protects':{'its':1},'imitation':{'counts':1,'so':1,'two':1,'but':1,'.':1},'arise':{'mysteriously':1,'from':3,'take':2,'directly':1},'pond':{'and':3,'of':1,'is':1,'it':1,'to':1,'nor':1},'air-dome':{'.':1},'mother-of-pearl':{'or':1},'terrestrial':{'plants':2,'mountains':1,'life':3,'animals':3,'rather':1,'support':1,'haunt':2,'standards':1,'dinosaurs':1,'journeyman':1,'animal':3,'backboned':1,'dragons':2},'influenced':{'all':1,'by':4},'court':{'maze':2,'maze--which':1},'goal':{'is':1},'unavailable.':{'what':1,'the':1},'breaking':{'on':2,'up':3,'down':5,'diverse':2,'down.':1,'the':1},'84.02':{'31900':1},'occasionally':{'with':1,'however':1,'in':1},'influences':{'such':1,'shutting':1,'from':1,'they':1},'extinguished':{'at':1},'shoulder-blade':{';':1},'hers.':{'illustration':1},'mould':{'so':1,'opening':1},'simplicity':{'and':1,'of':1},'sea-squirt':{'and':1},'orbits':{'.':1,'with':1,'at':1,'round':1},'trial-and-error':{'method':1,'methods':1},'twenty-thousandth':{'of':1},'moult':{'and':2},'pupae':{'tend':1,'less':1},'adventure':{'and':1,'the':1,'which':4,'.':1},'infects':{'him':1},'prospecting':{'for':1,'in':1},'concentrating':{'always':1},'profited':{'by':1},'dissolving':{'out':1},'short':{'a':1,'summer':1,'we':1,'and':2,'stump-like':1,'of':1,'powerful':1,'tail':1,'lists':1,'.':1,'list':1,'length':1,'folk':1,'words':1,'time':7,'the':1,'sojourn':1,'excursion':1,'to':1,'distance':3},'chiefly':{'on':1,'used':1,'from':1,'of':1,'through':1,'in':2,'sounds':1,'with':1},'dispersion--that':{'is':1},'prefers':{'a':1},'life-histories':{'and':1,'of':1},'departure':{'of':1,'in':1},'height':{'and':1,'of':8,'.':1,'so':1,'in':1,'the':1,'was':1},'shore':{'and':2,'area.':1,'is':4,'scene':1,'inland':1,'1921':1,'as':1,'starfishes':1,'at':1,'in':1,'.':3,'to':1,'varies':1,'hatch':1,';':1,'life':1,'seaweeds':1,'but':1,'they':1,'others':1,'come':1,'must':1,'animals':2,'of':9,'according':1,'the':1,'something':1},'conjugal':{'affection.':1},'kippax':{'call':1},'shade':{'of':2},'iron-mines':{'saturated':1},'encased':{'in':2},'plaice':{'and':2,'or':1},'indebted':{'climatic':1},'september':{'of':1,'1922':1,'29':2,'7':1},'developed':{'and':1,'on':1,'from':1,'for':1,'is':1,'except':1,'vocal':1,'.':3,'through':1,'collar-bone':1,'in':1,'along':1,'striped':1,'than':1,'more':1},'universals.':{'intelligent':1},'mission':{'of':4},'cross':{'upon':1,'x':1,'with':1,'was':1,'from':1},'gauged':{'from':1},'unfitting':{'that':1},'scientist':{'galileo':1,'is':1},'concentric':{'regions':1,'lines':1},'emphasized':{'by':1},'thirtieth':{'case':1,'forty':1},'variability--evolution':{'of':1},'style':{'.':2},'forwards':{'as':1,'for':1},'call':{'radio-activity':1,'magnetic':1,'mind':1,'life':2,'as':1,'electrons.':1,'our':2,'living':1,'gravitation':1,'them--or':1,'electro-magnetic':1,';':1,'into':2,'nebulae.':1,'neolithic':1,'himself':1,'them--which':1,'it':1,'helping':1,'them':1,'white.':1,'canals':1,'white':2,'a':2,'light':1,'ozone':1,'of':1,'the':4,'perceptual':1,'reason.':1},'susceptible':{'to':1},'fairbanks':{'ak':1},'example.':{'the':1},'obscure--sometimes':{'environmental':1},'harmless':{'from':1,'snakes':1},'strange':{'animals':2,'animal':1,'amalgams':1,'nest':1,'rings':1,'state':1,'to':2,'as':1,'objects':1,'colouring':1,'lowly':1,'spectacle':1,'creations':1,'conditions':1},'combination-boxes':{'where':1},'non-plastic':{'efficiency':1},'partitions':{'se':1},'might':{'on':1,'be':17,'almost':1,'injure':1,'speak':1,'see':1,'therefore':1,'have':2,'take':2,'happen':1,'hasten':1,'think':1,'possess':1},'alter':{'the':2},'pre-human':{'ape-man':1,'ancestor':1,'ancestors':1,'pedigree':1},'return':{'and':2,'from':1,'later':1,'to':10,'as':1,'the':1,'or':2},'sucking':{'tongue':1},'alighting':{'only':1},'hunter':{'with':1},'chalones':{'which':1},'2.--the':{'milky':1},'communities':{'and':1},'hunted':{'out':1},'adventurous':{'and':1,'life-history':1,'experiment':1,'worms':1},'bigger':{'and':1,'than':2},'instructions':{'to':1},'subtler':{'demands':1},'intricacy':{'of':1},'bolts':{'and':1},'mastered':{'the':1,'so':1,'.':1},'man':{'all':1,'over':1,'discovered':1,'whose':3,'had':3,'except':1,'forms':1,'to':3,'has':9,'noticing':1,'coloured':1,'represents':1,'did':1,'found':1,'photographically':1,'works':1,'bone':1,'often':1,'past':1,'homo':2,'sec':1,'are':2,'thinks':1,'established':1,'plays':1,'stands':2,'since':1,'does':2,'got':1,';':2,'we':2,'sprang':1,'alone':2,'appears':1,'on':2,'would':1,'of':12,'could':1,'s':48,'or':4,'first':1,'appeared':1,'171':1,'asks':1,'.':18,'too':1,':':2,'was':4,'himself':2,'knows':1,'that':1,'exterminated':1,'took':1,'but':2,'to-day':1,'167':1,'with':3,'161':1,'he':1,'plants':1,'grew':1,'these':1,'type':1,'will':2,'values':1,'were':2,'and':22,'153':1,'type.':1,'157':1,'is':11,'it':1,'an':1,'reconstructed':1,'as':2,'lived':1,'have':1,'in':5,'saw':1,'occur':1,'perhaps':2,'interferes':1,'1':1,'how':1,'a-b.':1,'interfered':1,'pursues':1,'nearer':1,'may':1,'preceding':2,'who':3,'prepared':1,'73':1,'included':1,'man':1,'a':1,'off':2,'pithecanthropus':1,'m':1,'the':7,'possesses':1,'came':1},'inherent':{'biological':1},'difficult':{'chapter':1,'on':1,'word':1,'for':3,'of':1,'question':1,'theories':1,'environment':1,'to':14,'not':1,'situation':1,'speculation':1,'conditions':1,'than':1},'saturn.':{'the':1},'constructing':{'its':1},'weighs':{'1':1,'about':3,'nearly':1},'weight':{'for':1,'of':6,'is':1,'two':1,'.':1,'they':1,'than':1},'needless':{'to':2},'generation':{'and':1,'people':1,'of':1,'is':1,'after':1,'to':3,'that':1,'have':1,'in':1,';':1,'if':1},'female--first':{'one':1},'notochord':{'is':2,'.':2},'recapitulate':{'racial':1,'in':1},'culminating':{'with':2,'in':2},'scratching':{'swimming':1},'inflated':{'and':1,'balloon.':1},'croaking':{'of':2},'wondered':{'why':1,'idly':1,'at':1},'induces':{'a':1},'progressive;':{'everything':1},'health':{'and':1,'which':1,'.':1},'hill':{'cave':2,'in':1},'absorb':{'either':1},'celebes':{'lay':1},'induced':{'to':2},'caucasian':{'arose':1,'.':1},'regards':{'many':1,'their':1,'sight':1,'wave-lengths':1,'the':4,'its':2,'size':1},'note--that':{'of':1},'exertions':{'and':1,'running':1},'lesser':{'degree':1},'coco-palms':{'has':1},'rotifer':{'is':1},'monotony':{'.':1},'tassels':{'on':1},'fuller':{'embodiment':2,'well-being.':1},'teach':{'her':1},'colonised':{'by':1,'at':1},'generate':{'heat':1,'thousands':1},'lag':{'behind':1},'thrown':{'a':1,'on':2,'dust':1,'off':1,'upon':1},'preliminary':{'training':1,'scaffolding':1},'thread':{'of':1,'needles':1},'e.g':{'.':38},'decipiens':{'and':1},'77':{'photo':1,'reproduced':1},'light--we':{'have':1},'circuit':{'of':2,';':1,'generates':1,'.':1},'twenty':{'thousand':1,'million':2,'years':5,'hours':2,'to':1,'miles':1,'or':2},'lemurs':{'and':1,'there':1},'experimenter':{'or':1},'fallen':{'and':1,'sufficiently':1},'throws':{'light':1,'it':1},'solidly':{'frozen':1},'sperm-cell':{'and':1,'adapted':1,'with':1},'sheep-driving':{'competition':1},'limestone':{'canyon':2,'which':1},'feel':{'and':1,'sure':1,'for':1,'over-anxious':1,'quite':1,'dare':1},'radical':{'difficulty':1,'changes':1},'churning':{'water':1},'linking':{'generation':1,'of':1},'well-known':{'case':1,'elements':2,'that':1,'mudfish':1,'examples':1,'soft-shell':1,'carpo-metacarpus':1},'sympathy':{'which':2},'sailor':{'expressed':1},'brave':{'self-forgetful':1},'defects':{'such':1},'fees':{'to':1,'.':1,'or':1,'that':1},'says':{'and':1,'a':1,'no.':1,'do':1,'that':3,'professor':1,'meteorites':1,'sir':1,'can':1,'the':2,';':1},'vapour-like':{'matter':1},'whale':{'and':2,'what':1,'showing':1,'there':1,'reaches':1,'.':1,'rushes':1,'the':1,'has':1,'118':1,'is':1,'must':1},'earthworms':{'and':1,'which':1,'centipedes':1,'many':1,'began':2,'have':1,'in':1},'fossil-bearing':{'rocks':1},'passes':{'a':1,'from':2,'into':1,'to':1,'near':1,'through':4,'directly':2,'between':1,'along':2,'the':1,'out':1},'story':{'of':19,'is':1,'when':1,'.':1,'will':1,'simply':2,'in':2,'the':1,'has':1,'went':1},'birgus':{'latro':2,'which':1},'temperature':{'and':3,'is':1,'it':1,'reaches':1,'say':1,'at':2,'in':1,'would':2,'seems':1,'.':7,'which':1,';':1,'was':1,'day':1,'then':1,'we':1,'falls':1,'rises':1,'than':1,'must':1,'of':10,'could':1,'allows':1,'will':1,'the':2},'redistributing':{'project':1,'or':1},'kin.':{'the':1},'leading':{'to':3,'peculiarities':1,'from':1,'authority':1},'coasts':{'but':1},'brisker':{'flow':1},'hangs':{'over':1},'swarm':{'of':3,'sometimes':1,'like':1,'has':1},'storm':{'note':1,'petrel':4,'effects':1,'they':1},'pitted':{'against':1},'soddy.':{'it':1},'aristocracy':{'and':1},'store':{'of':3,'the':1},'fire-mists':{'such':1,'would':1},'imperfect':{'core':2,';':1,'telescope':1,'the':1},'fish-lizards':{'and':1},'pump':{'.':1},'information:':{'dr':1},'convinces':{'us':1},'tugs':{'at':1},'sea-scorpions':{'belonged':1},'treasures':{'behind':1},'rifle':{'and':1,'bullet':3,'.':1},'convinced':{'of':1,'that':2},'explodes':{'without':1},'king':{'of':1},'kind':{'and':2,'we':2,'enable':1,'from':2,'whereas':1,'that':2,'of':34,'taking':1,'express':1,'upon':1,'.':2,'will':1,'set':1,'in':3,';':2,'throughout':1,'or':1,'present':1},'earth--as':{'a':1},'wonder-world':{'of':2},'double':{'this':1,'streaming':1,'blowhole':1,'fold':1,'that':1},'instruction':{'and':1},'indifferent.':{'they':1},'dispensed':{'with':1},'risks':{'and':2,'to':1,'are':1,'of':2},'coast.':{'illustration':1},'earth--an':{'electric':1},'tongues':{'of':2},'unrestricted.':{'animals':1},'7a':{'the':1},'outstanding':{'events':1},'greenwich':{'observatory':1},'disguise--other':{'kinds':1},'gale':{'bringing':1},'alike':{'of':1,'in':1},'cleaned':{'artificially':1},'shrews':{'tree-shrews':1},'cases--marvellous':{'apparatus':1},'cobras':{'brightly':1},'blowhole':{'or':1},'check':{'on':1,'the':2,'comes':1,'vegetation.':1},'interferes':{'is':1},'cropped':{'up':1},'port':{'knows':1,'in':1},'middlemen':{'is':1},'moist':{'winds':1,'and':1,'climate':2,'internal':1,'air':1},'finding':{'their':1},'interfered':{'but':1},'added':{'a':2,'to':4,'up':1},'electric':{'current':15,'power':2,'bells.':1,'bell':1,'charges':2,'shock':1,'phenomena':1,'charge':3,'magnet':1,'tram':1,'terminals':1,'dynamo.':1,'circuit':1,'trams':1,'discharge':6,'spark':8,'furnace':1},'bands':{'it':1,'140':1},'intervened':{'the':1},'instance.':{'organic':1},'measures':{'of':1,'about':1,'on':1,'the':1,'three':1},'reach':{'a':2,'and':1,'about':1,'us.':1,'us':1,'.':1,'their':1,'only':1,'but':2,'the':7,'upward':1,'out':1},'react':{'effectively':1,'on':1},'cigarette':{'and':1},'attempt':{'to':2,'at':1,'too':1},'74':{'diagram':1},'73':{'okapi':1},'72':{'photo':2,'earthworm':1,'reproduced':1},'enduring':{'satisfaction':1},'nothing':{'happens':1,'appeals':1,'like':1,'solid':1,'of':1,'had':1,'but':3,'.':6,'better':1,'more':1,'at':1,'which':1,'in':2,'colder':1,';':1,'out':2,'was':1,'gives':1},'measured':{'and':2,'cube':1,'in':2,'drop':1,'only':1,'fall':1,'the':2,'by':1,'movements':1},'achievement':{'and':1,'is':1},'constitution':{'of':10,'could':1,'which':1,'.':1},'equatorial':{'regions':1,'forests':1},'22.--a':{'nebular':1},'mineral':{'particles':1},'coincides':{'with':1},'chemical':{'reaction':3,'processes':3,'elements':3,'energy':2,'substances':1,'science':1,'screen':3,'conditions.':1,'messengers':6,'element':2,'leave':1,'transformation--the':1,'analysis':1,'routine':1,'action':1,'.':1,'changes':1,'compounds':1,'element.':1,'level':2},'zealand.':{'some':1},'amphibian':{'foot-print--an':1,'mind':1,'race':1,'in':1},'wood-snails':{'but':1},'notch':{'next':1},'artemia':{'salina':1},'institutions':{'.':1,'were':1},'lying':{'on':2,'head':1,'inert':1,'over':1,'upon':1,'beside':1,'low':3},'stones':{'and':3,'on':1,'from':1,'of':2,'.':1,'so':1,'in':1,'probably':1,';':1,'where':1,'or':1},'copy':{'and':1,'a':1,'of':2,'is':1,'upon':1,'it':2,'or':1,'in':1,'display':1,'if':1},'journeys':{'undertaken':1,'.':1},'pennies':{'and':1,'from':1},'wayside':{'.':1},'to-day.':{'as':1,'illustration':1,'an':1},'shares':{'with':1},'gilded':{'boxes':1},'securing':{'a':1,'change-provoking':1,'the':2},'mudfish':{'may':1,'of':1,'is':1,'or':1},'fishes--the':{'mind':1},'moulting':{'immature':1},'grotesque':{'delusions':1},'betray':{'themselves':1},'hip':{'joint':1},'birnam':{'when':1},'hit':{'a':1,'and':1,'upon':1,'by':1},'gains':{'of':2,'that':1},'assumed':{'on':1},'furnaces':{'as':1,'with':1},'whistle':{'is':1},'explosively':{'from':1},'longest':{'for':1,'of':1,'feathers':1,'are':1,'waves':2,'or':1,'pinions':1},'instinctive':{'aptitudes':5,'activities':1,'repertory.':1,'capacities.':1,'rather':1,'capacities':5,'due':1,'actions':1,'element':1,'behaviour':10,'obligations':1,'registration.':1,'ants':1,'capacities--limited':1,'routine':2,'capacity':2,';':1,'.':1,'awareness':1,'behaviour.':1},'shreds.':{'whenever':1},'stone.':{'and':1,'nearly':1},'eye-piece':{'magnifies':1,'.':1,'its':1,'at':1},'expositor':{'.':1},'thereabouts':{'.':1},'nibbles':{'at':1},'arges':{'that':1},'investigate':{'the':1},'ninety-two':{'elements--we':1,'.':1},'activity':{'and':1,'we':1,'which':1,'for':2,'almost':1,'heretofore':1,'is':1,'in':2,'s':2,'.':3,'also':1,'as':2,'besides':1,'of':3,'known':1,';':1,'where':1},'rischgitz':{'collection.':6},'engraved':{'on':2},'nibbled':{'away':1},'bars':{'of':1,'have':1,'which':1},'art':{'of':1,'expressing':1,'in':1},'achieved':{'.':2},'intelligence':{'and':9,'on':1,'--the':1,'deteriorates':1,'cooperated':1,'of':2,'is':2,'when':1,'what':1,'.':7,'will':1,'to':3,'increases':1,'are':1,'a':1,'in':3,'seen':1,'the':2,'--a':1,';':2,'co-operating':1},'arc':{'in':2},'bare':{'head':1},'are':{'limited':1,'all':9,'scooped':1,'caused':1,'landlocked':1,'commoner':1,'illustrated':3,'particularly':3,'poorly':1,'particles':2,'certainly':1,'concerned':3,'to':9,'preserved':1,'under':1,'worth':1,'activities':1,'comparatively':1,'seized':1,'returned':1,'sitting':1,'very':25,'trillions':1,'foul':1,'vastly':1,'vast':2,'dim':1,'clouds':1,'large':2,'quick':3,'smaller':1,'specially':1,'dealing':1,'likely':1,'further':1,'estimated':1,'giving':1,'hereditary':2,'fossil':1,'ever':1,'led':1,'loose':1,'here':3,'hundreds':5,'met':1,'others':1,'persecuted':1,'strong':3,'observing':1,'great':2,'thirty':1,'vibrating':1,'descended':5,'usually':4,'conveniently':1,'composed':2,'mimicked':1,'suddenly':1,'merely':5,'explained':1,'marked':2,'highly':1,'brought':1,'visible':2,'hard-and-fast':1,'from':1,'recalling':1,'two':11,'few':1,'wonderfully':1,'therefore':2,'taken':1,'themselves':1,'phosphorescent--they':1,'more':13,'separated':1,'staggering':1,'tested':1,'ignorant':2,'known':7,'mounted':2,'none':1,'vicissitudes':1,'excessively':1,'exceptions':2,'pent-up':1,'bent':1,'indicated':1,'oviparous':1,'tax':1,'allowed':1,'huge':1,'rather':1,'divided':1,'breaking':2,'entangled':3,'1':2,'located':2,'ordinary':1,'substances--':1,'tried':1,'undergoing':2,'inconceivably':1,'burrowing':1,'different':2,'waves':3,'such':5,'a':13,'free-swimming':1,'chiefly':2,'four':2,'crowded':1,'light':1,'so':13,'pulled':1,'minded':1,'over':1,'mainly':1,'produced':1,'held':1,'still':5,'its':2,'26':1,'interesting':1,'masses':1,'actually':2,'strange':1,'microscopic':1,'spoiling':1,'covered':1,'receptacles':1,'secondary':1,'split':1,'good':1,'locusts':1,'safe':1,'they':3,'not':35,'sorted':1,'now':11,'killed':1,'well-known':1,'always':2,'sufficiently':1,'each':1,'found':3,'entirely':1,'traces':1,'lifted':1,'doing':2,'sifted':5,'transmissible.':1,'borne':3,'living':1,'shown':2,'fundamentally':1,'content':1,'laid':2,'7':1,'induced':1,'red':1,'attended':1,'quite':4,'small':1,'put':1,'beginning':2,'cremated':1,'exhibited':1,'constantly':1,'adepts':1,'greatest.':1,'instances':1,'spots':2,'directly':1,'immensely':1,'mercury':1,'little':1,'ancient':2,'similarly':1,'unknown':1,'plastic':1,'their':3,'cooling':1,'2':1,'too':1,'wrapped':1,'legally':1,'white':1,'witnessing':1,'mostly':4,'that':1,'exactly':1,'predictable':1,'convinced':1,'peculiar':1,'double':1,'enabled':1,'extraordinarily':2,'matter':1,'determined':1,'supposed':1,'treated':1,'encumbered':1,'variable':1,'close':2,'seen':4,'clearly':2,'relatively':2,'built':3,'thoroughly':3,'speculative':1,'able':8,'also':11,'edge':1,'absorbed':1,'presently.':1,'most':1,'eight':1,'printed':1,'drought':1,'incursions':1,'extremely':1,'nutritive':1,'manifested':1,'especially':1,'considered':1,'clear':1,'sometimes':1,'repeated':1,'face':1,'short-lived':1,'points':2,'left':4,'normally':1,'molluscs':1,'shot':1,'sceptical':1,'supported':1,'scattered':1,'right-handed':1,'rotating':1,'unsurpassed.':1,'giant':1,'highest':1,'distributed':2,'outside':1,'buttons':2,'being':2,'only':5,'going':1,'employed':1,'thousands':1,'meant':1,'exceptional':1,'dependent':1,'closely':1,'altogether':1,'instinctive':1,'areas':1,'playful':1,'sheltered':1,'common':1,'rung':1,'doubles':1,'approaching':1,'set':2,'acquired':1,'observed':1,'sporadic':1,'luminous':1,'subject':1,'said':2,'prominent.':1,'circulating':1,'continually':5,'jewels.':1,'luminescent':1,'unable':1,'various':2,'markedly':1,'probably':3,'prodigally':1,'numerous':3,'we':4,'gratefully':1,'invisible':3,'precious':1,'favourable':1,'many':16,'taking':1,'equal':1,'present':2,'tree-toads':1,'adapted':3,'among':1,'hollow':1,'learning':1,'deflected':1,'ether':1,'startling':1,'there.':1,'capable':1,'tremendous':1,'due':1,'.':3,'attaching':1,'immense':3,'much':4,'slowly':1,'likewise':1,'repelled':1,'painted':1,'suns.':1,'worked':1,'those':3,'stolen':1,'these':3,'awakened':1,'seven':1,'almost':2,'violently':2,'obtrusive':1,'obeying':1,'tell-tale':1,'in':26,'ready':1,'confirmed':1,'perpetually':1,'stimulated':1,'parts':1,'arguments':1,'mixtures':1,'played--for':1,'used':3,'temporary':1,'arctic':1,'constantly--either':1,'moving':1,'kept':2,'paralysed':1,'well':2,'without':2,'the':43,'charged':1,'just':4,'less':1,'increasingly':1,'offensive':1,'mistaken':1,'reincarnated':1,'human':1,'alternative':1,'revealed.':1,'corroborated':1,'thinking':1,'agile':1,'spread':1,'exempt':1,'resolved':1,'easily':1,'dark':1,'apt':4,'long-haired':1,'accepted':1,'redistributing':1,'ruled':1,'like':4,'complicated.':1,'shed':1,'right':1,'often':16,'some':9,'neutralised':1,'amongst':3,'born':3,'universes':1,'provided':1,'gradually':1,'dense':1,'asking':1,'pre-eminent':1,'palatable':1,'slight':1,'manufactured':1,'broken':1,'on':6,'about':6,'cautious':1,'carried':3,'getting':1,'of':7,'discussed':1,'greatly':2,'connected':1,'hatched':4,'flying':2,'attached.':1,'billions':1,'three':3,'authorities':1,'mere':1,'impressed':1,'strictly':1,'there':3,'disposed':1,'long':3,'stars':3,'deposited':1,'naturally':1,'lowest':1,'complete':2,'deaf':1,'but':3,'somehow':1,'curiously':1,'removed':2,'considerable':1,'directed':1,'made':5,'arranged':2,'characteristic':1,'placed':1,'called':11,'storing':1,'vehicles':1,'affectionate':1,'certain':1,'slowing':1,'general':1,'as':8,'definite':1,'at':7,'floating':2,'no':7,'generally':1,'other':8,'blackish-grey':1,'really':3,'separate':1,'suited':1,'included':1,'--a':1,'reflectors':1,'longer':2,'practically':3,'required':1,'utilised':1,'beds':1,'far':4,'undoubted':1,'restored':1},'walking-stick':{'insects':1},'chambers':{'perforating':1},'bark':{'and':1,'of':1},'arm':{'and':1,'spawn':1,'of':2,'is':1,'stretching':1,'.':1,'skips':1,';':1},'declined':{'and':1},'crunching':{'insects.':1},'youth':{'to':1,'from':1},'learns':{'a':1,'the':1},'discovered--pulling':{'and':1},'distinctive':{'features':1,'colour':1,'spectrum':3,'arrangement':1,'peculiarities':1,'fauna':1,'is':1},'anatomists':{'have':1},'misjudge':{'our':1},'universe.':{'this':1,'but':1,'sec':1,'illustration':1,'in':1,'our':1,'are':1},'contrary':{'to':1,'has':1},'nestor':{'parrot':1},'numerous':{'and':1,'hard':1,'locations':1,'parachutists--':1,'attempts':1,'lobes':1,'prehensile':1,'ways':1,'separate':1,'young':1,'microscopic':1,'muscles':1,'kinds':1,'that':1,'hundreds':1,'gas-bubbles':1,'types':1,'ribs':1,'colour-varieties':1,'variations':1,'as':1,'mutually':1,'tubercles':1,'appendages':1},'hairs':{'may':1,'of':2,'and':1,';':1,'which':1},'vitality.':{'illustration':1},'1.f.2':{'.':1},'recently':{'named':1,'said':1,'that':1,'regarded':1,'shown':1,'been':1,'erected':1,'discovered':2,'as':1,'learned':1},'creating':{'derivative':2,'the':2},'1.f.3':{'a':1,'this':1,'the':1,'.':1},'sole':{'of':2,'which':1,'have':1,'are':1},'outfit':{'for':1},'days.':{'there':1,'sec':1},'succeed':{'not':1,'and':1,'in':3,'but':1,'.':1},'head.':{'compare':1,'illustration':1},'prelude':{'to':1},'inertia':{'of':1},'bronze':{'second':1,'was':1,'age':1},'c':{'a':1,'that':1,'of':1,'there':2,'but':1,'.':16,'thirdly':1,'3':2,'others':1,'any':1},'license':{'available':1,'and':1,'terms':1,'especially':1,'for':1,'please':1,'when':1,'.':2,'as':1,'included':2,'apply':1,'the':1,'must':1},'attainment':{'at':1},'sheaths':{'of':1},'distinctively':{'new':1,'north':1,'marine':1},'1.f.5':{'.':1},'roman':{'galley':1},'became':{'useful':1,'heated':1,'an':2,'as':1,'in':1,'extinct':2,'gradually':1,'unavailable':1,'for':1,'restricted':1,'extinct.':1,'much':1,'too':1,'easier':1,'more':2,'aware':1,'suited':1,'a':3,'longer':1,'equal':1,'enregistered':1,'the':4,'essential':1},'cloud-like':{'effect.':1,'patches':1},'bond':{'of':1,'could':1},'finds':{'its':3},'peripatus':{'a':1,'83':1,'centipedes':1,'which':2},'sloth':{'s':1},'flies':{'to':2,'into':1,'at':1,'.':1},'flier':{'.':2},'distress':{'is':1},'reasons':{'and':1,'great':1,'have':1,'for':3,'is':1,'are':2,'which':1,'why':1},'sweet':{'sap':1,'odours':1},'sweep':{'of':1},'whelk':{'on':1,'the':1,'requires':1,';':1,'or':2},'regulated':{'then':1,'harmony':1,'by':1},'incandescent':{'may':1,'world-cloud':1,'atoms':1,'gas.':1},'fibres':{'come':1},'newbigin':{'m':1},'simpler':{'and':3,'elements':1,'animals.':1,'forms':2,'so':1,'fossil':1,'in':1,'still':1},'pr':{'are':1},'decline':{'europe':1,'of':1,'sometimes':1,'markedly':1},'there.':{'so':1,'it':1},'jugglery':{'with':1},'java':{'and':1,'ape':1,'ape-man':3,'at':1,'in':1,'man':2,'ape-man--an':2},'scented':{'with':1},'illumined':{'seaweed-growing':1,';':1,'green':1,'than':1,'surface':1},'pigmies':{'of':1},'dug':{'as':1},'whom':{'we':2,'you':1,'they':1},'reduction':{'of':3,'in':1},'pg':{'search':1},'--an':{'internal':1},'brick':{'you':1,'contains':1,'moves':1},'yolk-laden':{'portion':1},'attractive':{'phenomenon':1},'affectionate':{'and':1},'flight':{'and':1,'from':1,'also':1,'may':1,'brings':1,'is':2,'.':3,'brought':1,'most':1,'as':1,'so':1,'which':2,'of':3,'implies':1,'has':1,'was':1},'flints':{'with':1},'flinty':{'sponge':1,'needles':1,'skeleton':2},'precision':{'what':1},'defect':{'you':1,'in':2},'1864':{'by':1},'temperament':{'as':1},'1869':{'that':1},'1868':{'sir':1},'depends.':{'separate':1},'plants':{'and':24,'already':1,'begun':1,'is':1,'it':2,'at':1,'have':2,'in':3,'before':1,'stands':1,'for':1,'.':5,'to':3,';':2,'laboriously':1,'may':1,'upon':1,'but':2,'such':1,'with':1,'by':1,'flourished':1,'asexual':1,'can':1,'were':2,'the':4,'or':3,'are':2},'stolen':{'by':1},'conception':{'of':6,'the':1,'.':1,'to':1},'boast':{'with':1},'yellow-brown':{'the':1},'frozen':{'gas':1,'masses':1,'hard':2,'rigid':1},'compactness':{'of':1},'intercepts':{'great':1,'all':1},'64-6221541':{'.':1},'parents.':{'strangest':1},'lenard':{'and':1,'found':1},'dublin':{'high':1,'zoo':1},'obtrusive':{'rather':1},'obstacle':{'of':1,'race':1},'rid':{'of':3},'hare--with':{'human':1},'currents':{'within':1,'of':1,'there':1,'.':1,'needed':1,'at':1,'moisture':1},'peopled':{'than':1,'.':1},'away.':{'3':1,'it':1,'illustration':1},'chapter.':{'the':1},'twofold':{'process':1,'caution':1},'illustration:':{'the':1,'star':1},'lengths':{'.':2,'part':1,'which':1,'in':1},'muscle-cells':{';':1,'which':2,'.':1},'foretells':{'the':1},'undersides':{'of':1},'blood-relationship':{'with':1,'between':1},'stimulated':{'brain':1,'cells':1,'if':1,'by':2,'to':1},'dermis':{'and':1},'widely':{'separated':1,'distributed':1,'open':1},'peoples':{'with':1,';':1,'who':1,'to-day':1,'indeed':1},'9':{'a':1,'feet':1,'inches':1,'million':1,'looking':1,'000':1,'the':1,'saturn':1},'shirk':{'the':1},'yucca':{'moth':6,'flowers':2,'flower':3,'moths.':1},'higher':{'and':3,'vertebrates':2,'still':2,'reaches':2,'apes--gorilla':1,'pitch':1,'expressions':1,'education':1,'terrestrial':1,'forms':2,'apes':2,'power':1,'there':1,'note':3,'animal':1,'life':1,'degree':1,'insects.':1,'mammals.':1,'standard':1,'adventures.':1,'controlling':1,'faculty':1,'flowering':1,'than':1,'land':1,'animals':4,'level':3,'turn':2,'centres':1,'mammal':1},'current.':{'each':1},'chequer':{'hen':1},'mountain':{'ranges':2,'hare':4,'torrents':1},'ultimate':{'particles':1,'object':1,'service':1,'atoms':1},'flows':{'as':1,'in':1},'brooding':{'on':1,'it':1},'moving':{'and':2,'speck':1,'through':1,'at':1,'rapidly':2,'hoofed':1,'her':1,'away':1,'.':1,'particles':2,'how':1,'parts':2,'body':1,'very':1,'amongst':2,'atoms':1,'water':1,'objects':2,'molecules.':1,'with':5,'on':2,'about':1,'mass':1,'toward':1,'round':1},'mistake.':{'we':1},'sagacious':{'indeed':1,'when':1},'birch':{'alder':1},'vertical;':{'the':1},'263':{'professor':1,'reproduced':1},'lower':{'and':1,'side.':1,'vertebrates':1,'surface':1,'one':1,'in':1,'female.':1,'photograph.':1,'miocene':1,'jaw':6,'vertebrate':1,'orders':2,'eocene':1,'picture':1,'ends':1,'mammals':1,'levels':1,'jaw.':1,'than':3,'types':1,'temperature':2,'photograph':1,'diagram.':1,'animals':1,'level':1,'part':1,'side':1},'people.':{'no':1},'dancing':{'mice':1,'mouse':1,'or':1},'chickens':{'that':1,'incubated':1,'in':1},'outflame':{'of':1},'analysis':{'of':1,'showing':1,'would':1},'magnified':{'to':2},'solids':{'.':1},'edge':{'on':1,'or':1,'of':5},'length.':{'now':1},'b.c':{'.':2},'beautiful.':{'in':1},'muscle-fibre':{'m.f.':1},'266':{'the':1},'pollen':{'to':1,'from':2,'.':1},'abilities':{'come':1},'endeavour':{'to':1,'after':3,'associated':1,'or':1,'.':1},'unseen':{'occupies':1,'earthworms':1,'.':1},'mimicked':{'butterflies':1,'.':2,'by':1,'for':1,'are':1},'mood.':{'certain':1},'pigeons':{'and':2,'to':1,'it':1,'were':1},'competitive':{'.':1},'reincarnated':{'in':1},'intervals':{';':1},'inachis':{'from':2},'questions':{'and':1,'besides':1,'that':1,'of':3,'introduce':1,'have':1,'with':1},'inter-relations--the':{'subject':1},'reliance':{'on':1},'continent':{'of':1,'when':1,'fixes':1,'from':1},'tamed':{'.':1},'ravine':{'near':1},'wedge-shaped':{'piece':1},'corroborated':{'or':1,'by':1},'extracted':{'from':1},'workers':{'fastened':1},'tentatives--new':{'departures':1},'ocean':{'and':1,'for':1,'of':4,'is':2,'it':1,'.':2,'s':1,'home':1},'exclusively':{'of':1},'exhibition':{'of':2},'inducing':{'strange':1},'finder':{';':1},'turtle-backs':{'is':1},'associations':{'and':1,'established':1,'of':1,'between':1,'.':1,'were':1,'such':1,'with':1},'up-stream.':{'sometimes':1},'balloon.':{'photos':1,'running':1},'sensatory':{'nerve-fibre':1},'entangled':{'and':2,'in':2,'together':1,'air':1},'earth--making':{'a':2},'modifications':{'are':1},'rotate':{'and':1,'on':3,'all':1,'at':1,'round':1},'line--are':{'represented':1},'neanderthaler':{'.':1},'confront':{'us':1},'incidental':{'damages':1},'separately':{'is':1,'.':1},'collect':{'pennies':1,'half':1},'arthur':{'the':1,'thomson':5,'keith':7,'thomson.':1,'antiquity':1},'retires':{'to':1},'under-water':{'world':1},'foot--an':{'obvious':1},'table.':{'illustration':1},'essential':{'features':2,'similarity':2,'that':1,'vertebrate':1,'to':2,'oneness':1,'part':3,'independence':1,'in':1,'bones':1,'construction':1,'difference':1,'correlation':1,'identity':1},'engravings':{';':1},'hinted':{'at':2},'feet--the':{'largest':1},'men--races':{'of':1},'eluding':{'the':1},'streaming':{'motion':1,'from':2},'newsletter':{'to':1},'hjort':{'dr':1},'saucer':{'or':1},'aptitudes':{'many':1,'what':1,'which':1,'inborn':1,'then':1},'stately':{'and':1},'gradually':{'division':1,'slow':1,'from':1,'radiating':1,'out':1,'turned':1,'as':1,'reduced':1,'cooling':1,'settle':1,'eliminate':1,'evolved':2,'curved':1,'become':1,'increasing':1,'adapted':1,'regrown':1,'realised':1},'bushy-tailed':{'almost':1},'tends':{'to':6},'prof':{'.':7},'fragments':{'a':1,'and':1,'broken':1,'doubled':1,'of':2},'pieces--a':{'kind':1},'jumps':{'along':1,'from':1},'weir':{'confessed':1},'refused':{'to':1,';':1},'race--there':{'is':1},'intense':{'white':1,'disturbance':1,'competition':1,'activity':1},'vivid':{'idea':1},'cautious':{'and':1,'for':1},'mingled':{'with':4,'together':1},'age.':{'photograph':1,'sand-pit':1,'some':1,'as':1,'cenozoic':1,'they':1,'the':1},'row':{'of':1},'tortuous':{'path':1},'firing':{'the':1},'deepish':{'water':1},'forbears':{'long':1},'penetration':{'implies':1,'.':1},'lifeless':{'world.':1},'range':{'of':7,'became':1,'in':2},'wonders':{'of':4,'that':1},'fluttering':{'.':1},'gamma':{'rays':4},'naturalists':{'who':2,'have':1},'feed':{'and':1,'on':5,'for':1,'there':1,'some':1,'at':2,'in':1},'enregistration':{'of':1},'moss':{'and':1,';':1,'by':1},'conquest':{'of':8,'implied':1,'both':1},'attached.':{'methods':1},'flagellates':{'in':1},'canal':{'in':1,'system':1,'round':1},'impressed':{'on':1,'with':1,'by':1},'acquiesce':{'as':1,'in':1},'extremely':{'rapid':1,'interesting':1,'alert':1,'rarified':1,'delicate':1,'conservative':1,'fine':1,'thin':1},'question':{'and':2,'what':1,'rises':1,'to-day':1,'that':1,'whether':2,'of':3,'is':4,'had':1,'but':1,'to':2,'as':1,'which':1,'in':2,':':2,'than':1,'must':1},'cocoon--the':{'bag':1},'cuticle':{'or':1},'enregister':{'outside':1,'ready-made':1,'or':1},'conceivable':{'ages':1},'mimicry':{'and':2,'is':1,'serves':1,'.':1,'in':1,'called':1},'sections':{'of':1,'3':1,'.':1},'files':{'of':1,'containing':1},'mountains':{'and':1,'on':1,'like':1,'of':3,'.':1,'to':1,'are':2,'the':1},'potassium':{'pill':1},'glamour':{'of':1},'cloth':{'if':1,'packets':1,'in':1},'began--a':{'small':1},'energy--traceable':{'back':1},'crane':{'and':1,'the':1},'ring-armour.':{'illustration':1},'raising':{'the':1},'penguin':{'notice':1,'213':1},'section.':{'influence':1},'nonplussed':{';':1},'consist':{'of':1,'themselves':1,'in':1},'characteristic':{'style':1,'set':1,'fossils':2,'pelagic':2,'of':4,'endeavour':1,'.':1,'contingencies--the':1,'sharp':1,'self-preservative':1,'bird':1,'population':1},'seize':{'the':1},'117':{'photo':1,'ten-armed':1},'stalking':{'about':1,'we':1,'carnivore':1},'homo':{'neanderthalensis':1,'sapiens':1,'heidelbergensis':1},'redistribution.':{'start':1},'etc.':{'are':1,'gives':1},'called':{'protists':1,'appropriately':1,'luidia':1,'nototrema':1,'negative.':1,'spring':1,'is':1,'labyrinthodonts':1,'chalones':1,'differentiation':1,'salps':1,'planets':1,'protozoa.':1,'obelia':2,'pontobdella':1,'helium':1,'zostera':1,'triticum':1,'viviparity':1,'peter':1,'informal':1,'positive':1,'educability.':1,'muellerian':1,'spiral':1,'peripatus':2,'aerial.':1,'their':1,'without':1,'pretty':1,'hormones':1,'lycosa':1,'energy':1,'red':1,'kelts':1,'we':1,'which':1,'convergences':1,'zoological':1,'glands':1,'the':23,'upon':1,'guanin':1,'learning':1,'phagocytes':1,'them':1,'amniota':1,'convergence':1,'batesian':1,'commensalism':1,'venus':1,'momentous':1,'a':5,'deeps':1,'into':1,'sun-spots':1,'chauliodus':1,'round':1,'cryptozoic':1,'physiological':1,'tropisms':2,'have':1,'were':1,'self-mutilation':1,'primitive':1,'cells':1,'experimental':1,'jasper':1},'x-ray':{'photograph':6,'spectra':1},'individuality':{':':1,'with':1},'freak':{'is':1},'sepia':{'from':2},'breast.':{'the':1},'problem.':{'1.f.4':1},'warning':{'colours':2,'note':1,'coloration':1},'reservoirs':{'of':1,'to':1},'trammels':{'of':1},'whirligig':{'beetle':2},'adams':{'10':1,'who':1},'knowledge.':{'astronomical':1},'rainbow':{'is':1,'.':1,'where':1,'in':1},'riot':{'in':1},'reason.':{'the':1,'sec':1,'what':1,'here':1},'tentative':{'men':3,'branches':1,'or':1,'experimental':1},'weight.':{'4':1},'endurance':{'patience':1},'peace':{'while':1,'or':1},'c.:':{'that':1},'reappearance':{'of':1},'club':{'can':1},'opalina':{'which':1},'income':{'.':2},'ferment':{'from':1},'intercrossing':{'or':1,'between':1},'generates':{'heat':2,'sufficient':1,'in':1},'backbone':{'and':1,'a':1,'of':1,'.':1,'which':1,'in':3,';':1},'problems':{'on':1,'that':1,'of':1,'but':1,'.':2,'which':1},'thirty-two':{'miles':1},'helping':{'to':1,'the':1},'develops':{'very':1,'into':1},'allowing':{'the':1,'elbow-room':1,'more':1},'-200':{'deg':1},'folds':{'its':1},'inventions':{'are':1},'vaseline':{'bottle':1},'fluorescence':{'on':1},'fan-like':{'cluster':1},'path.':{'there':1},'liquefy':{'air':1},'accumulations':{'of':1},'departments':{'of':1},'back.':{'the':1},'departs':{'209':1,'in':1},'appearance--an':{'epoch-making':1},'weights':{'or':1,'.':1},'well-being.':{'we':1},'hooky':{'surfaces':1,'that':1},'vue':{'gardens':1},'resistance':{'to':1,'.':1},'distributed:':{'this':1},'protuberant':{'the':1},'winds':{'rise':1,'from':1,'two':1},'open-minded.':{'the':1},'adjustment':{'to':1,'of':1},'contributions':{'and':1,'to':1,'from':3,'are':1},'magnifying':{'lens':1,'lens.':1},'tide-marks':{';':1},'copernicus':{'lower':1},'simon':{'newcomb':1},'e-mail':{'within':1},'disposal':{'however':1},'sparrow':{'to':1,'rise':1,'up':1},'deal.':{'the':1},'cradle':{'of':7,'whereas':1,'.':1,'in':1,'or':1,'is':1},'stable':{'kind':1,'lines':1,'crust':1,'.':1,'result':1,'curved':1,'stock':1,'equilibrium':1},'breach':{'of':2},'include':{'a':1,'all':1,'whales':1,'many':2,'one':1,'those':2,'the':2,'mediterraneans':1},'breathing':{'dry':1,'of':1,'by':2,'which':1,'movements':2},'wished':{'to':1},'wind.':{'in':1},'club-moss':{'forests':3},'talons':{'and':1},'alder':{'and':1},'sensation':{'of':4},'electron':{'and':3,'sir':1,'has':1,'theory':3,'theory--the':1,'is':4,'current':3,'when':1,'as':1,'.':2,'rotating':1,'to':2,'pump':1,'physicists':1,'in':1,';':1,':':1,'was':1,'merely':1,'sticks':1},'graphic':{'illustration':1},'dando':{'baby':1},'bounding':{'about':1},'posture':{'with':1},'redistribute':{'this':1},'ideas--the':{'living':1},'self-effacement':{'is':1,'often':1,'but':1},'fur':{'and':1,'of':2,'or':1},'notes':{'with':1},'phenomena.':{'sec':1},'agency.':{'yellow-crowned':1,'chimpanzee':1,'orang-utan':1,'penguins':1,'in':1,'baby':2},'deals':{'with':1,'.':1},'glaciations':{'and':1},'warranties':{'of':2,'or':1},'poisonous':{'snake':2,'species':1},'phoenix':{'electric':1},'moulding':{'effect':1},'blood-fluid':{'or':1},'noted':{'for':1,'that':4},'assemblage':{'of':2},'disclaimer':{'of':1,'or':2},'smaller':{'even':1,'and':1,'telescope':2,'cheek-bones':1,'constituents':1,'less':1,'.':1,'particles':2,'will':1,'electrons':1,'have':1,'globes':1,'magellanic':1,'particles.':1,'than':8},'gripping':{'grappling':1,'the':1,'them':1,'teeth':1},'possum.':{'the':1},'tides--another':{'instance':1},'coldrum':{'in':1},'euphrates':{'.':1},'chauliodus':{'a':1},'fold':{'of':3},'sea-anemones':{'and':1,'147':1,'we':1,'which':1,'on':2,'mask':1,'hermit-crabs':1,'they':1},'unsurpassed.':{'to':1},'protrude':{'greatly':1},'sifting-out':{'process':1},'fermenting':{'vegetation':1},'makers':{'of':1},'folk':{'or':1,'place':2,'two':1,'human':1,'in':1},'unavailable':{'the':1,'.':3,'heat':1,'energy':1,'having':1},'disentangle':{'these':1},'waiting':{'for':1},'chose':{'a':1,'compartment':2},'desires':{'.':1},'kangaroo':{'while':1,'carrying':2},'underwood':{'underwood.':2},'youngest':{'and':1,'.':1},'desired':{'.':1},'grilse.':{'in':1},'separation':{'of':2},'frilled':{'lizard':3,'lips':2},'fifteen-spined':{'stickleback':1},'--carrying':{'with':1},'fruit-eating':{'and':1},'little-brained':{'ants':1},'settling':{'on':1},'evolution--the':{'establishment':1},'survivor':{'of':1},'convolutions.':{'illustration':1},'mauer':{'near':2,'at':1},'ones.':{'various':1},'leaving':{'a':1,'no':2,'perhaps':1,'only':1,'the':2,'its':1},'suggests':{'the':3,'that':2,'motions':1,'.':1},'patagium':{'and':1,'is':1},'oar':{'reduces':1},'breeds':{'of':2,'it':1,'that':1},'hue':{'and':1,'is':1},'pent-up':{'reservoirs':1},'apple':{'.':1},'spy':{'in':1},'egypt':{'and':1,'crete':1,'the':1},'earth-moon':{'system.':1},'facilitating':{'their':1},'apt':{'to':9},'expect':{'great':1,'that':1,'very':1,'there':1,'it':1,'to':2,'much':1},'marmosets':{'and':2},'motor':{'nerve-fibre':2,'nerve-cell.':1,'nerve-cell':1,'nerve-fibres':1,'nerve-cells':2,'answer':1},'newby':{'chief':1},'apply':{'to':1},'repopulation':{'of':1},'segregating':{'their':1},'use':{'and':3,'some':1,'it':1,'at':1,'in':1,'its':1,'for':2,'to':3,'there':1,'when':1,'.':2,'their':2,'has':1,'was':1,'them':1,'unless':1,'very':1,'but':1,'part':1,'a':3,'this':3,'of':14,'carbonic':1,'the':5,'seaweed':1},'fee':{'of':1,'is':1,'as':1,'for':3,'or':2},'from':{'all':3,'being':7,'tip':2,'worms':3,'ignoble':1,'facts':1,'japan':1,'inshore':1,'its':16,'roots':2,'mingling':1,'outer':1,'electricity':1,'masses':1,'behind':1,'forms':1,'to':1,'crest':4,'photographs':2,'donors':1,'them':2,'his':1,'branch':1,'10':2,'very':1,'freezing':1,'within.':1,'five':1,'trough':1,'now':1,'monkeys':1,'sowing':1,'benevolent':1,'hawaii':1,'these':4,'slipping':1,'each':9,'where':1,'side':6,'view':1,'people':1,'generation':2,'intelligence':2,'fish':2,'some':3,'direct':1,'dead':1,'gumboil':1,'year':1,'our':4,'dawn':1,'what':3,'colour-varieties':1,'sun':1,'nebula':1,'asia':1,'your':1,'particles':1,'outside':2,'expressing':1,'public':1,'red':1,'scientific':6,'insects':1,'men':1,'seaweeds':1,'water':5,'protection':1,'great':1,'struggle':1,'others':1,'simpler':1,'both':1,'about':2,'actual':1,'experience':1,'stone':1,'railway':1,'osborn':4,'pre-human':1,'first':2,'among':1,'simple':2,'within':4,'inland':1,'one':23,'pole':2,'learning':1,'ether':1,'cloud':1,'millions':1,'ancient':1,'her':1,'body-cells.':1,'remains':2,'pre-existing':1,'three':2,'sunlight':2,'.':1,'uniting':1,'behind.':1,'which':12,'white':1,'injury':1,'specimens':1,'radium':6,'500':1,'gill-breathing':1,'elsewhere':1,'that':2,'mammals':2,'malay':1,'heat':1,'part':1,'another.':1,'body-cells':1,'atom':4,'infusorians':1,'knife-blade-like':2,'those':1,'fossil':1,'sponge':1,'animals':2,'this':7,'tree':3,'us':3,'air':2,'below':1,'diagrams':1,'more':1,'and':1,'egypt':1,'mexico':2,'certain':1,'modern':1,'india':3,'it':2,'an':2,'states':1,'collision':1,'something':3,'any':6,'sir':1,'different':1,'ancestors':1,'end':1,'negatively-electrified':1,'scotland':1,'innumerable':1,'other':5,'5':2,'copying':1,'ordinary':1,'several':1,'enormous':1,'star':1,'glands':1,'time':3,'hand':1,'eight':1,'two':2,'nothing':1,'such':3,'types':1,'man':2,'a':37,'ingersoll':2,'land':2,'natural':1,'age':3,'their':7,'without':5,'knipe':6,'not-living':2,'every':1,'the':256,'europe.':1},'figure':{'of':1,'is':2,'one':1,'2':1,'ninety-two':1,'in':1,'.':1},'animals--by':{'insects':1},'frog':{'about':1,'showed':1,'discriminates':1,'flying':1,'had':1,'catches':1,'answers':1,'192':1,'1':1,'s':1,'rhacophorus':1,'which':1,'rhinoderma':1,'the':1,'mouth.':1,'merged':1,'lays':1},'few':{'and':1,'insects':1,'years':1,'feet':2,'spiders':1,'protozoa':1,'offspring':1,'lessons':1,'things':3,'ticks':1,'opportunities':1,'astronomers':3,'rivals':1,'other':1,'black':1,'weeks':1,'hundred':2,'minor':1,'inches':1,'that':1,'thousand':1,'days.':1,'records':1,'representative':1,'yards':1,'cases':3,'now':1,'extremely':1,'conspicuous':1,'pounds':1,'of':3,'months':1,'days':4,'cases.':1,'corners':1,'exceptions':1,'minutes':1,'embryonic':1,'illustrations.':1},'apprenticeship--tentative':{'men--primitive':1},'gales':{'will':1},'diving-bell':{'to':1,'full':1},'eagles':{'gather':1},'possession':{'of':2},'grandest':{'and':1,'pictures':1,'as':1},'secretions':{'of':1},'humanly':{'impossible':1},'inclined':{'to':1,'pillar':1,'plane':6,'plane.':1},'rarest':{'type':1},'impress':{'him':1},'steadfastly':{'serving':1},'eagles.':{'similarly':1},'hilger':{'ltd.':2},'rabbit':{'and':1,'squirrel':1,'for':1,'when':1,'.':1,'which':1,'the':1},'scale.':{'sec':1,'if':1},'development--that':{'there':1},'women':{'show':1},'fro.':{'this':1},'us.':{'this':1,'the':1,'races':1,'sec':1},'getting':{'a':1,'on':4,'what':1,'thinner':1,'hotter':1,'into':3,'air':1,'possession':1,'farther':1,'wet':1,'rid':1,'out':1,'away':1,'transport':1,'at':1},'ice.':{'seeing':1},'overlappings':{'.':1},'anywhere':{'at':2,'else':1},'perched':{'on':1},'field--which':{'he':1},'three-chambered.':{'the':1},'dissolve':{'a':1,'the':1},'proof':{'of':12,'that':2},'have--there':{'is':1},'non-growing':{'non-moulting':1},'habitats':{'which':1},'proprietary':{'form':1},'mud-fish':{'protopterus':2},'thirsty':{'and':1},'calculation':{'suggests':1,'as':1,'ought':1},'inaccessible':{'to':1},'tax':{'returns':1,'deductible':1,'identification':1,'treatment':1,'exempt':2},'land-snails':{'representing':1,'for':1},'something':{'associated':1,'less':1,'is':1,'as':1,'beyond':1,'to':1,'which':1,'new':2,'has':1,'more':1,'corresponding':2,'that':3,'very':3,'new--a':1,'but':1,'else':1,'with':1,'simpler':1,'about':1,'like':6,'of':2,'could':1,'the':1},'serial':{'issue':1},'made':{'and':3,'among':1,'polished':1,'rudely':1,'it':5,'an':2,'visible':3,'incandescent':1,'in':6,'luminous':1,'their':1,'out':1,'perfect':1,'bridges':1,'till':1,'of.':1,'.':6,'1':1,'to':7,'pets':1,'man.':1,'lays':2,'do':1,'malaria':1,'that':2,'of':5,'possible':1,'but':1,'forbidding':1,'during':1,'with':1,'by':8,'a':5,'on':1,'great':1,'many':1,'clear':1,'no':1,'up':3,'large':1,'points':1,'so':2,'artificially':1,'january':2,'stone':1,'the':5,'more':1,'at':1},'sir':{'e.':1,'norman':3,'richard':1,'wm':1,'j':7,'william':8,'g':1,'arthur':7,'oliver':3,'w':3,'harry':1,'isaac':5,'ernest':6,'john':3,'george':1,'ray':4},'galls':{'on':1},'counting':{'the':1,'electrons':2},'decaying':{'vegetation--an':1,'leaves':1},'sit':{'on':1},'distinguishable':{'from':1},'justifiable':{'to':2},'past.':{'on':1,'one':1},'struggles':{'there':1,'upward':1},'moods':{'.':1},'fortunate':{'for':1},'brian':{'janes':2},'instead':{'of':8,'strong':1},'struggled':{'.':1},'substances--':{'phosphorescent':1},'tension':{'passes':1,'is':1,'grows':1},'cupboard':{'and':1},'attend':{'the':1,'too':1},'yolk-sac':{'y.s.':1},'slipher':{'of':1},'immersed':{'in':3},'masks':{'the':1},'tack':{'of':2,'however':1},'wrist':{';':1,'which':1},'understanded':{'of':1},'1887':{'michelson':1},'1885':{'another':1},'agglomerations':{'of':1},'superstitions':{'have':1},'are--measuring':{'them':1},'clauses.':{'experimentation':1},'inheritance':{'that':1,'of':1,'.':1,'which':2,'the':1,';':1},'interrupted':{'light':1},'polystomella':{'showing':2},'fortunately':{'fast':1},'ovipositor':{'inside':1},'locomotor':{'agility':1,'triumph':1,'activity':1},'summer.':{'there':1},'irregularity':{'in':1},'preparing':{'our':1,'the':2},'affection.':{'the':1},'spreads':{'sleeping':1,'out':1},'saturated':{'southwards':1},'farming':{'or':1},'minnow':{'and':1,'to':1,'could':1},'mentioned.':{'this':1,'illustration':1},'reptile':{'and':1,'from':1,'breathes':1,'but':1,'total':1,'95':1,'94':1,'at':1},'interpreted':{'to':1,'as':1},'whilst':{'its':1,'an':1},'mathematicians':{'upon':1},'130':{'000':1,'steps':1},'idiosyncrasies':{'crop':1,'.':1},'looks':{'a':1,'like':3,'less':1,'almost':1,'big':1,'after':1,'extraordinarily':1,'.':1,'as':4},'135':{'animal':1},'abstruse':{'speculations':1},'interpreter':{'.':1},'139':{'photo':1},'138':{'the':1,'protective':1},'ease.':{'more':1},'self-fertilisation':{'because':1},'primordial':{'substance':2},'choose':{'to':1},'orange':{'screen':1,'yellow':2},'clusters':{'of':1,'at':1},'receptacles':{'or':1},'forty-five':{'seconds':1,'degrees':1},'crowds':{'of':3},'refracting':{'telescope':3},'originator':{'of':2},'bumbling':{'bittern':1},'forty-one':{'years':1},'orthodox':{'head-on':1},'practice':{'however':1,'or':1},'flew':{'away':1,'round':1,'22':1},'impressing':{'other':1,'itself':1},'emerald':{'hue.':1},'satellites':{'of':3,'miles':1,'like':1},'attaining':{'a':1,'to':1,'various':1,'that':1},'successor':{'rather':1},'viscid':{'threads':2},'articles':{'will':1,'with':1,'are':1},'crumb-of-bread':{'sponge':1},'sleeve':{'.':1},'movements.':{'this':1},'profound':{'idea':1,'abysses':1,'practical':1,'.':1,'calm':1,'moulding':1},'tram':{'or':1},'seashore.':{'illustration':1},'transmitted':{'through':2,'.':1},'trap':{'formed':1,'.':1},'cocoon':{'flies':1,'when':1},'bills':{'and':1,'up':1,'upwards':2},'erratic':{'quantities':1,'scattered':1,'paths':1},'foot-print--an':{'eloquent':1},'fitting':{'their':1},'old-established':{'creature':1},'related':{'to':11,'half-monkeys':1,'fish':1,'which':1},'whitish':{'spots':1},'remove':{'the':1},'82':{'peripatus':1},'83':{'photo':1,'photograph':1},'80':{'per':1},'86':{'photo':1,'an':1},'87':{'animals':1},'ebooks':{'and':1,'unless':1,'.':1,'are':1,'in':1,'with':1},'respects':{'a':2,'very':1,'like':1},'loquacious':{'bird.':1},'cerebral':{'hemispheres':1,'advances':1},'blood-channels':{'and':1},'flattening':{'of':1},'exporting':{'a':1},'20.--comet':{'october':1},'carpo-metacarpus':{'bone':1},'supports':{'them':1},'dive':{'far':1,'neither':1},'despairing':{'of':1},'fun':{'but':1},'zoological':{'gardens.':1,'races':1,'park':1,'haunt':1,'park.':10},'pours':{'out':2},'mussels.':{'the':1},'maintains':{'that':1},'promptly':{'discovered':1},'york':{'and':1,'zoological':10},'waves--light--what':{'the':1},'obliteration':{'.':1},'tenant':{'.':1},'support.':{'project':1},'age-old':{'mystery':1},'weaves':{'its':1},'organic':{'evolution':9,'evolution.':3,'matter':1,'nature':1,'particles':1,'evolution--there':1,'dust':1},'g':{'notice':1,'.':10,'in':1},'musculature':{'integumentary':1},'curlews':{'both':1},'behaviour.':{'a':2,'evolution':1,'illustration':1,'comparing':1,'sec':1,'in':1,'the':2},'chisel-edged':{'teeth':1},'hence':{'a':1,'fall':1,'it':1,'appendicitis':1,'in':1,'the':2,'if':1},'pterosaurs':{'none':1},'californian':{'coast.':1},'incipient':{'race':1,'species':1},'embryo':{'-reptile':1,'there':2,'no':1,'-mammal':1,'is':2,'within':1,'.':3,'while':1,'of':2,'the':1,'has':1,'with':1,'-fish':1,'shows':1},'plainly':{'this':1,'how':1,'that':1},'arcturus':{'43.4':1},'pycraft':{'w':1},'echo':{'of':1},'bonnet':{'monkey':2},'foals':{'and':1,'to':1},'eleventh':{'printing':1,'moon':1},'placental':{'mammals':1},'representations':{'concerning':1},'imperial':{'war':4},'miles--in':{'itself':1},'dispersive':{'effect':1},'salient':{'aspects':1,'features':1,'examples':1},'droop':{'forward':1},'unknown':{'on':1,'gas':1,'but':1,'.':3,'to':1,'manner':1,'in':1,'until':1},'galley':{'hill':1,'.':1},'retreats':{'and':1},'their':{'distances':1,'interpretation':1,'perch':1,'orbits.':1,'boxed-in':1,'brain':1,'attempts':1,'relation':1,'salivary':1,'upturned':1,'speed':3,'lessons':2,'birthplace':2,'doom':1,'resemblance':1,'progeny':1,'masses':1,'possessors':2,'young':6,'opportunities':1,'wings':1,'environment':2,'surroundings':3,'neighbours':1,'bases':1,'parents':2,'marks':1,'resources':1,'appearance--an':1,'borrowed':1,'clutches':1,'fate':1,'distance':1,'food':4,'advances':1,'moons':1,'early':1,'smallness':1,'background':1,'hands':1,'slipperiness':1,'height':1,'day':1,'condition':1,'evolution':1,'success':1,'parrot':1,'course':1,'crops':1,'luminosity':2,'length.':1,'back-teeth':1,'activity':1,'distant':1,'bills':4,'soft':1,'breast-bone':1,'bond':1,'dwindled':1,'burrows':1,'old':1,'mental':1,'weight':1,'life-history':2,'appearance':1,'energy':3,'range.':1,'sifting':1,'relative':2,'rate':1,'individual':1,'year':1,'development':2,'foals':1,'enemies':3,'living':1,'constitution':1,'axes':1,'interference':1,'migrations':2,'artificial':1,'fellows':1,'colours':1,'wave-lengths.':1,'simplest':1,'approach':1,'bearers':1,'scaly':1,'body':2,'variability':1,'toes':1,'transparency':1,'power':3,'importance':1,'argument':1,'kindred':3,'limbs':1,'atoms':2,'behaviour':1,'host':1,'chances':1,'outlying':2,'substance':1,'allies':1,'brilliant':1,'dormancy':1,'insect':3,'discoveries':1,'motion':1,'turn':1,'length':2,'head':1,'youthful':1,'first':1,'origin':2,'golden':3,'own':9,'gizzard--certainly':1,'family':1,'presence':1,'reasons':1,'father':1,'bluish':1,'multiplication':1,'enlarged':1,'names':1,'passage':2,'size':1,'decline':1,'use':1,'palm-bones':1,'chisel-edged':1,'muddy':1,'destination':1,'secret':1,'thinnest':1,'prey':1,'predecessors':1,'way':7,'fixed':2,'repertory':1,'more':2,'function':1,'hue':1,'eyes':1,'tissues':1,'yolk-forming':1,'wits':2,'brains':1,'becoming':1,'back':1,'heat':2,'importance.':1,'lives':1,'adult':1,'impulse':1,'ring-armour.':1,'insect-visitors':1,'homes':1,'characteristic':1,'cells':3,'detachable':1,'ancestral':1,'lips':1,'vocal':1,'temperatures':1,'reproduction':1,'light':3,'photosynthesis':1,'remains':1,'parents.':1,'real':1,'furs':1,'modern':1,'mind':1,'discovery':2,'deep':1,'manner':1,'lifetime':1,'movements':2,'respective':1,'ancestors':1,'variety':1,'lengths':1,'ascent':1,'maximum':1,'arrangement':1,'pectoral':1,'field':1,'relatives':3,'numerous':1,'income':2,'tool':1,'contemporaries':1,'worldwide':1,'polar':1,'material':1,'cupboard':1,'mouths':1,'normal':1,'nest':1,'reach':1,'orbits':1,'counterparts':3,'visitors':1,'significance.':1,'strength':1,'mouth':1,'delicate':1,'ink-bags':2,'hair':1,'foothold':2,'coloration':1,'natural':1,'modes':1,'pigmy':1,'nostrils':1,'eggs':5,'life':3,'posterior':1,'incessant':1,'castings':1,'manipulative':1,'tentacles':1,'smooth':1,'mother':2,'reward':1,'wing':1,'bodies':3,'usual':1},'1500':{'west':1},'delusions':{'yet':1},'behind.':{'there':1,'illustration':1},'embryology':{'--these':1,'of':1},'unstereotyped':{'they':1},'invisibility':{'and':1,'may':1,'coloured':1,'does':1,'at':1,'.':1},'noteworthy.':{'penguins':1},'shell':{'and':3,'very':1,'of':11,'is':4,'tends':1,'against':1,'.':2,'were':1,'in':3,'not':1,'with':1,'or':1},'x-rays':{'and':2,'we':1,'ltd.':4,'were':1,'.':2,'discovered':1,'have':1,'so':1,'are':1,'they':1,'which':3,'not':1,'through':2,';':1},'bromogelatine':{'plates':1},'shelf':{'fringing':1,'around':1},'shallow':{'and':1,'there':1,'well-illumined':1,'.':1,'water':5,'trough':1,'water.':2,'pond':1,'areas':1},'reflecting':{'instrument':1,'telescope--the':1,'telescope':1,'others':1},'constituent':{'colours':1,'of':1,'element':1},'july':{'17':2},'reverses':{'its':1},'blind':{'flat-fish':1,'alley':1,'gut':2},'dynamical':{'principle':1},'succeeded':{'and':1,'sir':1,'or':1,'.':1,'every':1,'in':3,'by':1},'uninterested':{'to':1},'isolation':{'of':1,'from':1,'which':1},'richer':{'evolution':1},'instincts--of':{'insects':1},'dynamo':{'as':1,'does':1,'it':1,'which':1},'individualities':{'arise':1},'dusty':{'the':1},'varied.':{'a':1},'tracts':{'of':1},'safeguarded':{'the':1},'violets':{'would':1},'fowl':{';':1},'gate-posts':{'and':1,'green':1},'sifting.':{'but':1},'endeavour.':{'sec':1,'in':1},'mongolian':{'and':1},'germinal':{'changefulness':1,'variations':1},'siamang':{'.':1},'reaches':{'a':5,'on':1,'of':3,'it':1,'us':1,'which':1,'in':1,'such':1,'the':2,'its':3},'angle':{'and':1,'on':1,'to':2,'.':1},'pollen-tubes':{'grow':1},'agency':{'could':1},'olfactory':{'messages':1},'supplanted':{'by':1},'well-marked':{'chins':1,'breeds':1},'ungirt':{'loin':1},'which':{'all':9,'belong':2,'help':1,'just':1,'produces':2,'captures':1,'probe':1,'vary':1,'gulls':1,'leads':3,'stored':1,'thanks':1,'go':3,'still':1,'birds':1,'causes':4,'seemed':2,'bridges':1,'rapid':1,'depend':1,'had':6,'came':1,'actually':1,'forms':5,'simple':1,'only':1,'behave':1,'extends':2,'helps':1,'sulked':1,'under':1,'attained':2,'covered':1,'circle':1,'has':43,'alter':1,'happened':1,'grip':1,'eventually':1,'his':2,'means':3,'food':2,'breaks':1,'tends':1,'lurk':1,'floated':1,'confines':1,'feels':2,'cannot':5,'nearly':2,'they':19,'progress':1,'not':1,'during':1,'he':7,'now':2,'dr':1,'monkeys':1,'look':1,'indicate':2,'like':1,'did':1,'always':2,'generally':1,'modern':2,'make':4,'admitted':1,'travels':2,'this':5,'persisted':1,'she':1,'turns':1,'become':2,'speculation':1,'freshwater':1,'mount':1,'reaches':1,'often':1,'reference':1,'people':1,'sends':1,'ancestral':1,'some':4,'supplies':1,'recapitulate':1,'constitute':2,'individual':1,'lines':1,'are':66,'pass':1,'our':1,'kant':1,'parachuting':1,'even':1,'delivered':1,'plays':1,'opened':1,'lead':1,'constitutes':2,'rings':1,'its':1,'everything':1,'contained':1,'experiment':1,'huxley':1,'scientists':1,'probably':4,'learned':1,'dilutes':1,'roentgen':1,'can':2,'we':52,'led':4,'nature':2,'climbs':1,'never':2,'atoms':1,'water':2,'credits':1,'were':12,'sink':1,'lasts':1,'put':1,'from':1,'puzzled':1,'come':1,'by':5,'about':1,'enables':2,'rests':1,'deals':1,'could':4,'strikes':1,'contract':1,'mixes':1,'carries':2,'became':1,'stand':1,'professor':1,'swing':1,'usually':1,'disappears':1,'stimulate':1,'comes':1,'feed':2,'emerge':1,'radio-activity':1,'followed':1,'secure':3,'formerly':1,'supply':1,'suddenly':1,'seems':1,'habitual':1,'marked':2,'one':1,'brought':1,'lies':2,'spans':1,'comprises':1,'whalebone':1,'mark':1,'appeared':1,'presents':1,'differ':1,'light':1,'expresses':1,'takes':1,'would':8,'to':3,'there':11,'finally':1,'periodically':1,'rivals':1,'live':4,'spread':3,'slowly':1,'living':1,'grew':2,'was':18,'opens':1,'gives':1,'life':1,'enable':1,'arise':1,'molecules':1,'form':1,'afford':1,'becomes':1,'marks':1,'amphibians':1,'broke':1,'separates':2,'absorbs':1,'almost':1,'reverses':1,'must':4,'plants':2,'pull':1,'made':1,'animals':2,'unfortunately':1,'these':3,'prevents':1,'require':1,'work':1,'lessen':1,'will':7,'attacks':1,'remain':1,'lays':1,'many':1,'already':1,'meet':1,'circulate':1,'dr.':1,'hatch':1,'have':22,'bind':1,'give':3,'frogs':1,'again':1,'is':61,'occupies':1,'thus':1,'it':22,'eats':1,'helped':1,'case':1,'as':3,'lived':1,'protects':1,'at':2,'slip':1,'allowed':1,'regulate':1,'pit':1,'counteract':1,'granules':2,'lie':1,'date':1,'no':4,'suggest':1,'began':2,'holds':1,'when':2,'astronomers':2,'very':1,'take':4,'forces':1,'brings':1,'new':1,'you':2,'grows':1,'neolithic':1,'formed':2,'conveys':1,'attend':1,'though':1,'may':16,'dive':1,'faintly':1,'paid':1,'reflect':1,'most':1,'fell':2,'tackle':1,'two':1,'multiply':1,'infects':1,'grow':1,'man':8,'a':8,'demand':1,'land':2,'in':7,'i':2,'makes':7,'arrange':1,'mask':1,'lasted':1,'thought':1,'used':1,'eurypterids':1,'allow':1,'keeps':1,'masks':1,'the':57,'justify':1,'blend':1,'responded':1,'migrate':1,'once':1},'tree-frogs':{'are':2,'called':1},'spawns':{'in':1},'divers':{'come':1},'vegetation':{'marking':1,'that':1,'of':1,'only':1,'in':1,'probably':1,';':1,'lingering':1,'consisted':1},'hydrostatica':{'related':2},'centre':{'and':4,'of':4,'.':2,'to':1,'only':2,'at':1,'in':1,'or':1},'wind-blown':{'sand':1},'who':{'show':1,'is':3,'soon':1,'anticipating':1,'have':4,'estimated':1,'are':5,'intrude':1,'said':1,'described':1,'had':2,'does':1,'has':1,'lacks':1,'do':1,'knows':1,'found':1,'may':1,'came':1,'gnaw':1,'lives':1,'learns':1,'approach':1,'believe':1,'with':1,'by':2,'concentrated':1,'made':4,'to-day':1,'like':1,'was':1,'think':1,'will':1,'maintain':1,'can':1,'mounts':1,'desire':1,'agree':1,'restored':1,'notifies':1},'cohesion':{'of':1,'between':1},'1.d':{'.':1},'1.e':{'below.':1,'.':1},'microbic':{'or':1},'digestive':{'and':1,'filaments':1,'juice.':1},'1.a':{'.':1},'1.b':{'.':1},'1.c':{'below':1,'.':1},'emancipation':{'of':3,'from':1},'violet.':{'sorting':1},'class':{'a':1,'of':5,'we':1},'deny':{'a':1},'expert':{'opinion':1,'advice':1},'deccan':{'the':1},'wasp-like':{'impression':2},'.001':{'per':1},'pipe':{'to':1,'.':1},'different-lengthed':{'waves':1},'cloaked':{'by':1},'europe.':{'it':1,'illustration':1},'swarming':{'in':1},'goals':{'and':1},'unimpeded':{'five':1},'refund':{'set':1,'from':1,'of':3,'-':1,'.':2,'in':1,'described':1},'terrific':{'cold':1},'insulators':{'because':1,'for':1},'perceptions':{'and':1},'chances':{'of':1,'are':1},'sceptical':{'about':1},'agreed':{'to':1},'tidings':{'from':1},'chapters':{'of':1},'upright':{'forehead':1,'on':1,'nail':1},'purely':{'instinctive':2},'sabre-toothed':{'tiger':1},'seaweed':{'and':3,'for':1,'area':1,'of':1,'nest':1,'continues':1,'but':1,'.':1,'green':1,'nibbles':1,'each':1,'vegetation.':1,'or':1},'changeful':{'surroundings':1,'processes':1,'place':1},'utter':{'darkness--an':1,'sufficient':1,'darkness':1},'fear':{'of':2},'darkest':{'period':1},'feat':{'which':1},'agrees':{'in':1},'nearer':{'a':1,'and':1,'an':1,'to':3,'the':3,'.':1,'than':1},'cave-bear':{'became':1,'cave-lion':1},'implying':{'initiative':1},'cache':{'of':1,'after':1},'gouging':{'out':1},'surroundings':{'on':1,';':1,'like':2,'these':1,'many':1,'.':4,'admits':1,'their':1,'without':1,'including':1,'lighter':1,'in':1,'not':1,'the':4,'rests':1,'must':1},'postulated':{'by':1},'herald':{'the':1,'its':1},'inhabit':{'the':1},'local':{'influence':1,'drying':1,'changes':1,'thickness':1},'combe':{'capelle':1},'snow-capped':{'mountains':1},'dexterities':{'which':1},'helios':{'the':1},'cube':{'of':1},'skims':{'from':1},'watching':{'those':1,'in':1},'d.p.':{'it':1},'displayed':{'performed':1},'primeval.':{'the':1},'intensely':{'hot':1},'words':{'all':1,'as':1,'are':2,'what':1,'to':1,'true':1,'there':2,'.':1,'also':1,'written':1,'meant':1,'we':1,'signifying':1,'but':2,'indicative':1,'such':1,'with':1,'monkeys':1,'animals':1,'of':2,'became':1,'can':1,'positive':1,'become':1,'the':2,'or':1},'please.':{'it':1},'penetrate':{'everywhere':1,'the':1,'through':1},'spur':{'to':2},'burned':{'up':1},'ornithoscatoides':{'decipiens':1},'sweat':{'and':1},'prodigally':{'using':1},'belts':{'which':1},'monsters':{'1892':1},'insectivorous':{'and':1,'plant':1,'bats':1},'quaternary':{'at':1},'waterfalls':{'of':1},'sparrows':{'and':1,'to':1},'generations':{'reached':1,'afterwards--and':1,'yet':1,'to':1},'afterwards--and':{'suffering':1},'unison':{'with':1},'available':{'on':1,'.':1,'with':1,'for':1,'space':1},'ebb':{'of':1},'acquired':{'a':2,'an':1,'its':1,'dexterities':1},'monkeys--in':{'dogs':1},'distantly':{'related':1},'cross-fertilisation.':{'sec':1},'violet':{'then':1,'end':1,'light':1,'colour':1,'.':1,'will':1,'at':1,'the':1},'barrels':{'of':1},'this.':{'the':1},'responses':{';':1,'.':2},'closer':{'examination':1},'closes':{'with':1},'shore-frequenting':{'seals':1},'mentioned':{'that':1,'already.':1,'indicates':1,'part':1,'in':1,'the':1,'is':1},'monstrous':{'tortoise':1},'worship':{'and':1},'genius':{'a':1,'of':1,'.':1,'it':1,'than':1},'converted':{'almost':1,'into':1,'directly':1},'identification':{'number':1,'for':1},'colour-associations':{'.':1},'hebrides':{'southwards':1},'crude':{'flint':1},'limit':{'these':1,'to':1,'the':1,'.':1},'variability':{'on':1,'is':1,'.':1,'to':1,'along':1,';':1},'andromeda':{'messier':2},'ability':{'to':2,'.':1},'opening':{'and':1,'fir':1,'up':1,'to':1,'new':1,'the':2,'more':1},'joy':{'and':1,'.':1},'agencies':{'operating':1,'for':1,'.':1},'podargus':{'a':1,'190':1},'apes':{'and':6,'both':1,'from':1,'show':1,'though':1,'but':1,'.':3,'also':1,'as':2,'diverged':1,'can':1,'165':1,'monkeys':1},'hypothesis':{'that':1,'may':1,'.':3,'therefore':1,'which':1,'one':1,'apart':1},'probing':{'and':1,'its':1},'rhythm.':{'illustration':1},'air-bubble--air':{'entangled':1},'swift':{'stroke':1,'hardly':1,'runners':1,'stream':1},'commands':{'our':1,'such':1},'cliff.':{'energy':1},'acknowledge':{'as':2},'mentone':{'on':1},'grouse':{'and':2,'disease':2,'or':1},'april':{'1922':4},'grain':{'of':8,'contains':1,'planted':1,'.':1},'utilising':{'dry':1},'retrograde':{'direction':1},'canopy':{'over':1},'germ-cells':{'and':1,'do':1,'that':1,'perhaps':1,'is':1,'but':1,'are':1,'have':1,'has':1,'into':1},'mutating':{'mood.':1},'wall':{'of':7,'shown':1,'.':1},'wonder':{'of':2,'then':1},'walk':{'with':2},'walt':{'whitman':1},'subscribe':{'to':1},'heredity':{'is':1,'which':1},'stars--to':{'star':1},'animalcule':{'often':1,'is':1,'which':1,'the':1,'has':1,'or':1},'table':{'suggests':1,'colliding':1,'page':1,'.':2},'investigator':{'noted':1},'mesozoic':{'and':1,'is':1,'era':6,'three':1,'times':1},'provinces':{'and':1},'i.e.':{'eating':1},'cavities':{'in':1},'hunters':{'and':2,'fowlers':1},'trademark':{'and':2,'license':1,'copyright':1,'but':1,'.':3,'as':1,'owner':2},'window':{'.':1},'responds':{'to':1},'ant-eaters':{'lay':1},'reindeer':{'and':2,'wild':1,'men':1,'man':1},'cry':{'uttered':1,'for':1,'.':2},'735':{'years.':1},'bewildering':{'profusion':1},'twenty-nine':{'days':1},'conductors.':{'so':1},'remedies':{'for':1},'1.e.1.':{'1.e.7':1},'painted':{'on':1,'bison':1,'in':2},'sufficient':{'for':1,'supply':1,'of':1,'here':1,'to':6,'heat':1,'sounds':1,'quantity':1,'cause':1,'theoretical':1,'inducement':1,'if':1},'thrusting':{'their':2},'sub-aquatic':{'environment':1},'ensuring':{'that':1},'visible.':{'illustration':1},'present':{'features':1,'point':1,'is':4,'rate':1,'in':6,'our':1,'living':1,'unavailable':1,'when':1,'two':1,'.':2,'day.':1,'state':1,'form':2,'though':1,'after':1,'but':1,'standard':1,'purpose':1,'they':1,'trying':2,'with':1,'day':2,'stage':1,'whereby':1,'value':1,'time':1,'the':4},'inconspicuous':{'24':1,'among':2,'when':1,'against':2,'.':2,'as':1,'amidst':1,'in':2,'by':1},'interstices':{'they':1},'abandoned':{'by':1,'.':2},'unlike':{'the':2},'agreement.':{'illustration':1},'vanilla':{'ascii':2},'will':{'emerge':1,'learn':1,'deal':1,'supply':1,'almost':1,'cover':1,'pass':2,'replace':1,'say':1,'have':1,'measure':1,'radiate':1,'tend':3,'scent':1,'any':1,'select':1,'make':2,'again':1,'gradually':1,'detect':4,'proceed':1,'to':2,'prevail':1,'support':1,'show':1,'deal.':1,'.':1,'start':1,'finally':1,'suffocate':1,'take':2,'then':1,'hatch':1,'surprise':1,'confine':1,'cause':1,'tell':1,'dispute':1,'evolve':1,'notice':1,'enable':1,'return':1,'engender':1,'gnaw':1,'admit':1,'express':1,'stop':1,'rush':1,'bear':1,'intercept':1,'sink':1,'not':9,'last':1,'attract':1,'come':3,'throw':1,'summon':1,'knock':1,'do':3,'rotate':1,'give':2,'consist':1,'be':53,'science':1,'colour':1,'no':1,'liquefy':1,'spontaneously':1,'appear':1,'remain':2,'continue':2,'die':1,'become':1,'the':2,'tap.':1,'explain':1,'travel':1},'inequilibrium':{'results':1},'vastly':{'hotter':1,'greater':1,'more':3},'wild':{'plants':1,'horses':1,'life':1,'animals':1,'rock-dove':1,'nature':2,'mammals':1,'peoples':1,'dog':2,'.':1,'species':2,'wheat':1,'rabbit':1,'cattle':1,'boar':1,'life.':1,'fauna':1,'he':1,'or':2,'cabbage':1,'sheep':1},'2007':{'ebook':1},'tadpoles':{'of':1,'while':1,'are':1,'.':1},'layer':{'of':4,'is':1,'overpowering':1,'or':2,'.':2},'envelope.':{'thus':1},'zostera':{'form':1},'apprehend':{'the':1},'filaments':{'which':1,'in':1},'non':{'profit':1},'encouragement':{'to':1},'meteoritic':{'contributions':1},'life-forms':{'would':1},'perhaps':{'among':1,'all':1,'because':5,'stray':1,'is':2,'it':5,'an':3,'discovered':1,'are':1,'in':1,'25':4,'from':2,'to':1,'twenty':1,'sum':1,'there':2,'when':1,'next':1,'also':2,'too':1,'belong':1,'500':1,'we':1,'increased':1,'that':2,'300':1,'eight':1,'they':3,'100':2,'one':1,'beginning':1,'why':1,'a':6,'thirty':1,'this':2,'professor':1,'wild':1,'the':9,'came':1},'trailing':{'on':1},'cromagnard':{'representative':2,'in':1},'forceps':{'held':1,'the':1,'so':1,'.':1},'unite':{'with':1},'electro-magnetic':{'energy':1,'theory':1,'waves':2},'orionis':{'showing':1,'37':1},'unity':{'and':1,'of':1,'.':2,'at':1,';':1,'or':1},'exuberance':{'of':3},'geographical':{'barriers':1,'distribution':1},'largest':{'and':1,'in':1,'of':4,'flying':1,'refracting':1,'reflecting':1,'waves':1,'telescopes':2},'units':{'of':1,'the':1,'were':2,'or':1,'are':1},'gets':{'up':2,'worn':1,'will':1,'through':1,'the':1,'beyond':1,'its':2},'hammering':{'at':2},'firmament':{'is':1},'spirited':{'pictures':1},'elbows':{'.':1},'slave':{'of':1},'conceived':{'as':1},'overcrowded':{'or':1},'student':{'what':1,'but':1,'in':1},'vapour':{'layers':1,'shoot':1,'of':1,'to':1,'at':1,'out':1},'laborious':{'tasks':1},'collar':{'over':1,'round':1},'warming':{'the':1},'reached.':{'the':1},'banded':{'krait':3},'unpacked':{'the':1},'star-book':{'.':1},'electrified.':{'in':1},'spectator':{'after':1},'sound-waves':{'and':1},'undertaken':{'by':1},'realised':{'the':1,'in':2,'.':1},'tacchini':{'of':1},'heavily':{'armoured':1},'only.':{'3':1},'wren':{'.':1},'multitude':{'of':6},'obtain':{'a':3,'permission':2},'replenish':{'the':1},'batteries':{'of':1,'getting':1,'.':1},'fishing':{'farming':1},'rocked':{'from':1},'inturned':{'margin':1},'cuckoo-spit':{'147':1,'the':2,'on':1},'contractile':{'vacuole':1},'disturbance':{'around':2,'ceases':1,'being':1,'is':1,'which':1,'in':1,'such':1},'host.':{'illustration':1},'supply':{'will':1,'of':6,'the':4,'and':1,'our':1},'smith':{'woodward':1},'pitcher-plant':{'catching':1},'discuss':{'at':1},'book':{'and':1,'on':1,'of':2,'there':2,'it':1,'which':1,'the':1},'galloping':{'boar':2},'usage':{'spread':1,'had':1},'enacted':{'on':1},'unprecedented':{'development':1},'civilisation--coal':{'.':1},'knob':{'on':1},'wont':{'to':1},'diamond-like':{'eyes':1},'branch':{'and':4,'we':1,'after':1,'from':1,'of':3,'is':1,'within':1,'to':2,'at':1,'now':1,'or':1,'out':1},'community':{'at':1,'in':1},'facial':{'characteristics':1,'expressions':1,'expression':2},'denser':{'and':1,'along':1,'masses':1,'than':1},'press':{'professor':1,'copyright':1,'the':2,'agency.':7},'originative':{'stock':1},'feral':{'216':1,'it':1},'safest':{'coloration':1},'perpetual':{'unremitting':1},'loses':{'a':1,'weight.':1,'it':1,'least':1,'its':1},'colonising':{'of':1,'the':1},'vortex':{'may':1,'phenomena':1,'in':1},'james':{'ritchie':1,'s':8,'matter':1},'puzzle-boxes':{'and':2,'with':1},'smoothness':{'of':1},'herons':{'and':1,'storks':1},'exceed':{'20':1},'because':{'they':8,'mind':1,'it':7,'in':1,'sounds':1,'its':3,'to':1,'deeply':1,'there':1,'birds':1,'their':1,'many':2,'we':1,'some':2,'heat':2,'although':1,'he':2,'this':1,'light':1,'obviously':1,'of':8,'the':12},'ages--evolution':{'of':1},'vortices':{'or':1},'elevators':{'in':1},'scottish':{'history':1},'mosquitoes':{'which':2},'eventfulness':{'of':1},'flint-shelled':{'radiolarians':1},'116':{'a':1,'after':1},'113':{'the':1},'faraday':{'he':1},'119':{'sea-horse':1,'photo':1,'an':1},'118':{'greenland':1,'minute':1},'blood-vessel':{'nerve':1,'for':1},'gill-slits':{'of':1,'are':1},'lamprey--a':{'long':1},'leaf':{'and':1,'touches':1,'towards':1,'seventy-five':1,'is':1,'six':1,'when':1,'.':4,'near':1,'without':1,'in':2,'close':1,';':1,'before':1,'must':2},'lead':{'on':1,'has':2,'pencil':1,'these':1,'is':1,'us':3,'one':1,'.':3},'promotion':{'and':1},'high.':{'the':1},'mines':{'of':1},'philosopher':{'and':1,'professor':1},'instantaneous':{'abandonment':1},'arteries':{'of':1},'leap':{'and':2,'over':1,'due':1,'out':1},'glacial':{'climate':1,'time':1,'.':1},'repeopling':{'from':1},'trout':{'go':1,'we':1,'in':1,'or':1,'eluding':1},'locate':{'a':1},'obey':{'this':2,'an':1},'thoroughfare':{'for':1},'astounding':{'fact':2},'analysed':{'tons':1,'.':1,'in':1},'conveyed':{'by':1},'raise':{'a':1,'their':1,'the':2,'it':1},'rare':{'birds':1},'carried':{'to':2,'about':2,'by':3,'for':1,'back':1},'extension':{'of':2,'have':1},'unsurpassable':{';':1},'column':{'of':1},'universe':{'and':3,'transmitting':1,'is':13,'it':1,'an':1,'as':3,'sec':2,'are':1,'in':1,'even':1,'said':1,'opened':1,'remains':1,'tiny':1,'.':11,'how':1,'which':1,'has':1,'was':2,'comparable':1,'may':2,'why':1,'243':1,'than':1,'a':1,'of':1,'can':1,'were':2,'the':1,'or':1},'biscuit':{'from':1,'.':1},'eclipse.':{'this':1},'dependence':{'.':1},'urged':{'that':1},'sea-horse':{'is':1,'puts':2,'in':2},'carries':{'them':2,'many':1,'about':1,'in':1,'the':2,'its':1},'carrier':{'of':1,'pigeons':1,'pigeon':3},'places':{'on':2,'them':1,'for':1,'e.g':1,'of':2,'vary':1,'to':1,'have':1,'the':3,'where':1,'its':1},'wheats':{'.':1},'devouring':{'their':1,'potatoes':1},'warranty':{'or':1,'disclaimer':1},'splash':{'of':1},'own':{'and':3,'beautiful':1,'weight':2,'when':1,'mind':1,'invention':1,'in':1,'lambs':1,'.':7,'reward.':1,'before':1,'dispersive':1,'little':1,'sake':1,'distinctive':2,'definite':1,'system':2,'moon':1,'internal':1,'white':1,'was':1,'day':1,'then':1,'race':1,'that':1,'but':1,'atoms':1,'genealogical':1,'solar':2,';':1,'he':1,'kind':1,'enemies.':1,'planet':1,'circle':1},'polished':{'stones':1,'stone':2},'sugary':{'sap':2},'owe':{'to':3,'them':1,'it':1,'our':1},'habituations':{'and':1},'wearisome':{'reiteration':1},'promise':{'myriads':1,'that':1,'of':2,'is':1,'are':1,'considerable':1},'brush':{'and':1},'registration':{'of':3,';':1},'cell--a':{'fertilised':1},'to-morrow':{'might':1},'prompted':{'by':1,'reliance':1},'linnaeus':{'spoke':1},'van':{'was':1},'miles.':{'these':1},'transfer':{'energy':1,'her':1},'paperwork':{'and':1},'spiral':{'nebulae.':1,'facing':1,'nebulae':8,'nebula':11,'edge-on':1,'arms':2,'having':1,'arms.':1,'to':1,'than':1,'structure':1},'continental':{'islands':1,'masses':1,'elevation':1,'fish':1},'uniting':{'into':1,'with':1},'4.--the':{'great':1},'breeding':{'season':2,'only':1,'calls':1,'time':1},'phosphorus':{'is':1},'mouth.':{'everyone':1,'sec':1,'illustration':4},'limulus':{'may':1},'fundy':{'it':1},'dasypeltis':{'gets':1},'u.s.a.':{'this':1},'incursions':{'of':1},'volume':{'and':1},'larger':{'and':3,'animals':2,'particle':1,'variety':1,'rather':1,'of':1,'area':1,'parasite':1,'than':5,'supply':1,'in':1,'fifteen-spined':1,'.':1,'continent':1,'species':1},'counterparts':{'in':3},'millipedes':{'and':1},'shark-like':{'and':1},'tactics':{'of':1,'are':1},'instructive':{'case':1,'to':2,'because':1,'.':1},'whether':{'all':2,'gravitation':1,'hunting':1,'that':1,'these':1,'it':5,'bird':1,'we':1,'imitation':1,'they':1,'particular':1,'the':6,'astronomy':1,'similar':1,'or':1},'meeting':{'of':1,'the':1,'that':1},'fossilized':{'forests.':1},'moorhen':{'saw':1,'has':1,'dived':1,'in':1},'record':{'of':1,'is':1,'answers':1,'.':2,'how':1,'the':1,'tells':1},'below':{'and':1,'a':1,'this':1,'freezing-point.':1,'.':3,'their':1,'are':1,'freezing-point':1,'the':11},'graphite':{'similarly':1},'demonstrate':{'a':1},'percival':{'lowell':1,'lowell.':1},'arno':{'von':1},'stirring':{'times':1},'unfolding':{'of':1},'cynodonts':{'were':1},'roentgen.':{'discovery':1},'change-producing':{'factors':1},'--1':{'.':1},'pigment-cells':{'chromatophores':1,'change':1},'1781.9':{'84.02':1},'globules':{'of':1},'kind.':{'sec':1},'soft-shell':{'tortoise':1},'domesticated':{'sheep':1,'animals':7,'dog':2,'breeds':1,'type':1,'creature':1},'counteract':{'poisons':1},'limb':{';':1,'or':1},'mutual':{'benefit':1,'gravitation':1,'dependence':1,'assurance':1},'1898.':{'in':1},'incredible':{'refinement':1,'speed':1},'portion':{'consists':1,'of':5,'would':1},'other':{'all':1,'interpretation':1,'words':11,'four':1,'experiments':1,'facts':1,'birds':1,'causes':1,'chemical':1,'apes':2,'group':1,'shifts':1,'physiological':1,'interesting':1,'parts':1,'marsh':1,'main':1,'associations':1,'format':1,'inter-relations':1,'marked':1,'they':1,'new':2,'radio-active':1,'sensational':1,'worlds':1,'backboned':1,'sedimentary':1,'side':6,'investigators':2,'telescope.':1,'thinkers':1,'growths':1,'some':1,'mollusc':1,'sporadic':1,'bacteria':1,'creatures':3,'pigments':1,'organisms':1,'factors':1,'ways':3,'pictures':1,'heavenly':1,'got':1,';':3,'warranties':1,'body':1,'ends':1,'toes':1,'terms':1,'men':2,'atoms':3,'stellar':1,'objects':1,'by':1,'extreme':1,'digits':1,'great':1,'substance':1,'of':1,'haunts':1,'times':3,'thing':1,'s':1,'light--we':1,'host.':1,'useful':1,'features':1,'reasons':1,'intellectual':1,'highly':1,'fishes':1,'seashore':1,'protozoa':1,'sounds':1,'throughout':1,'persons.':1,'trifles':1,'sea-snail':2,'copies':1,'.':14,'way':4,'reptiles':1,'specimens':1,'direction':1,'senses':2,'spiral':1,'form':2,'substances':2,'mammals':7,'immediate':1,'known':1,'branches':1,'cases':9,'than':1,'circumstances':1,'animals':3,'liquid':1,'places':1,'work':2,'theories':1,'project':1,'wild':1,'stages':1,'colour':1,'and':1,'meant':1,'seven':1,'change-producing':1,'is':3,'experiments--indications':1,'it':1,'metals':2,'pieces':1,'medium':1,'universes.':1,'planets':3,'universes':1,'domesticated':1,'orders':1,'cotton':1,'end':2,'in':1,'things':1,'ideas':1,'species':1,'astronomers':2,'instance':1,'became':1,'animal':1,'party':1,'enemies':1,'intelligent':1,'creature':1,'kinds':2,'hand':9,'glimpses':1,'blood':1,'never':1,'authorities':1,'such':1,'acquisitions':1,'amoeboid':1,'modes':1,'consequences':1,'age':1,'obstacles':1,'lines':1,'shafts.':1,'fundamental':2,'mechanical':1,'the':1,'order':1,'bodies':2},'sunrise':{'the':1},'boon':{'to':1},'conclusion':{'we':1,'that':5,'is':2,'what':1,'to':1,'in':1},'supersaturated':{'vapour':1},'kinds':{'forms':1,'of':34,'neoceratodus':1,'with':1,'are':1},'june':{'1922':4},'inherently':{'liable':1},'4.29':{'vega':1},'--i':{'.':1},'supple':{'yet':1},'--a':{'sort':1,'quite':1},'opened':{'a':1,'cones':1,'up':1,'.':1,'with':1,'its':1},'association--why':{'is':1},'ranks':{'of':2},'half-second':{'that':1},'volumes':{'of':1,'g':1},'understand':{'them':1,'that':1,'very':1,'what':1,'why':2,'in':2,'not':1,'the':4,'now':1,'agree':1},'function.':{'interesting':1},'expands':{'as':1},'sun--the':{'surface':1,'planets':1},'sci.':{'volvox':1,'trypanosoma':1}} class Learner: def __init__(self): self.db={} def learn(self,text): replacements1={'[^a-zA-Z0-9\.;:\-]':' ', '\s+':' ',', ':' , ', '\. ':' . ', ': ':' : ','; ':' ; '} for key,value in replacements1.items(): text=re.sub(key,value,text) items=[item.lower() for item in text.split(' ')] for i in range(len(items)-1): item=items[i] nextitem=items[i+1] if not self.db.has_key(item): self.db[item]={} if not self.db[item].has_key(nextitem): self.db[item][nextitem]=1 else: self.db[item][nextitem]+=1 def save(self,filename): cPickle.dump(self.db,open(filename,'wb')) def load(self,filename): self.loadd(cPickle.load(open(filename,'rb'))) def loadd(self,db): self.db=db def generate(self,length=10000,prefix=False): replacements2={' ,':',', ' \.':'.\n', ' :':':', ' ;':';', '\n\s+':'\n' } keys=self.db.keys() key=keys[random.randint(0,len(keys)-1)] words=key words=words.capitalize() regex=re.compile('[a-z]+') for i in range(length): okey=key if not key in self.db: break # should not happen db=self.db[key] s=sum(db.values()) i=random.randint(0,s-1) for key,value in db.items(): if i<value: break else: i-=value if okey=='.': key1=key.capitalize() else: key1=key if prefix and regex.findall(key1) and \ random.random()<0.01: key1='<a href="%s%s">%s</a>' % (prefix,key1,key1) words+=' '+key1 text=words for key,value in replacements2.items(): text=re.sub(key,value,text) return text+'.\n' def da_du_ma(n=4): return ''.join([['da','du','ma','mo','ce','co', 'pa','po','sa','so','ta','to']\ [random.randint(0,11)] for i in range(n)]) def populate(table, n, default=True): ell=Learner() #ell.learn(open('20417.txt','r').read()) #ell.save('frequencies.pickle') #ell.load('frequencies.pickle') ell.loadd(IUP) ids={} for i in range(n): record={} for fieldname in table.fields: field = table[fieldname] if not isinstance(field.type,(str,unicode)): continue elif field.type == 'id': continue elif default and field.default: record[fieldname]=field.default elif field.type == 'text': record[fieldname]=ell.generate(random.randint(10,100),prefix=None) elif field.type == 'boolean': record[fieldname]=random.random()>0.5 elif field.type == 'date': record[fieldname] = \ datetime.date(2009,1,1) - \ datetime.timedelta(days=random.randint(0,365)) elif field.type == 'datetime': record[fieldname] = \ datetime.datetime(2009,1,1) - \ datetime.timedelta(days=random.randint(0,365)) elif field.type == 'time': h = random.randint(0,23) m = 15*random.randint(0,3) record[fieldname] = datetime.time(h,m,0) elif field.type == 'password': record[fieldname] = '' elif field.type == 'upload': record[fieldname] = None elif field.type=='integer' and hasattr(field.requires,'options'): options=field.requires.options(zero=False) record[fieldname] = options[random.randint(0,len(options)-1)][0] elif field.type=='list:integer' and hasattr(field.requires,'options'): options=field.requires.options(zero=False) if len(options) > 0: vals = [] for i in range(0, random.randint(0,len(options)-1)/2): vals.append(options[random.randint(0,len(options)-1)][0]) record[fieldname] = vals elif field.type in ['integer','double'] or str(field.type).startswith('decimal'): try: record[fieldname] = random.randint(field.requires.minimum,field.requires.maximum-1) except: record[fieldname] = random.randint(0,1000) elif field.type[:10] == 'reference ': tablename = field.type[10:] if not tablename in ids: if table._db._dbname=='gql': ids[tablename] = [x.id for x in table._db(table._db[field.type[10:]].id>0).select()] else: ids[tablename] = [x.id for x in table._db(table._db[field.type[10:]].id>0).select()] n = len(ids[tablename]) if n: record[fieldname] = ids[tablename][random.randint(0,n-1)] else: record[fieldname] = 0 elif field.type[:15] == 'list:reference ': tablename = field.type[15:] if not tablename in ids: if table._db._dbname=='gql': ids[tablename] = [x.id for x in table._db(table._db[field.type[15:]].id>0).select()] else: ids[tablename] = [x.id for x in table._db(table._db[field.type[15:]].id>0).select()] n = len(ids[tablename]) if n: vals = [] for i in range(0, random.randint(0,n-1)/2): vals.append(ids[tablename][random.randint(0,n-1)]) record[fieldname] = vals else: record[fieldname] = 0 elif field.type=='list:string' and hasattr(field.requires,'options'): options=field.requires.options(zero=False) if len(options) > 0: vals = [] for i in range(0, random.randint(0,len(options)-1)/2): vals.append(options[random.randint(0,len(options)-1)][0]) record[fieldname] = vals elif field.type=='string' and hasattr(field.requires,'options'): options=field.requires.options(zero=False) record[fieldname] = options[random.randint(0,len(options)-1)][0] elif field.type=='string' and fieldname.find('url')>=0: record[fieldname] = 'http://%s.example.com' % da_du_ma(4) elif field.type=='string' and fieldname.find('email')>=0: record[fieldname] = '%s@example.com' % da_du_ma(4) elif field.type=='string' and fieldname.find('name')>=0: record[fieldname] = da_du_ma(4).capitalize() elif field.type=='string': record[fieldname] = ell.generate(10, prefix=False)[:field.length].replace('\n',' ') table.insert(**record) table._db.commit() if __name__ == '__main__': ell=Learner() ell.loadd(eval(IUP)) print ell.generate(1000,prefix=None)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) """ import os import re import cgi import portalocker import logging import marshal import copy_reg from fileutils import listdir import settings from cfs import getcfs __all__ = ['translator', 'findT', 'update_all_languages'] is_gae = settings.global_settings.web2py_runtime_gae # pattern to find T(blah blah blah) expressions PY_STRING_LITERAL_RE = r'(?<=[^\w]T\()(?P<name>'\ + r"[uU]?[rR]?(?:'''(?:[^']|'{1,2}(?!'))*''')|"\ + r"(?:'(?:[^'\\]|\\.)*')|" + r'(?:"""(?:[^"]|"{1,2}(?!"))*""")|'\ + r'(?:"(?:[^"\\]|\\.)*"))' regex_translate = re.compile(PY_STRING_LITERAL_RE, re.DOTALL) # patter for a valid accept_language regex_language = \ re.compile('^[a-zA-Z]{2}(\-[a-zA-Z]{2})?(\-[a-zA-Z]+)?$') def read_dict_aux(filename): fp = open(filename, 'r') portalocker.lock(fp, portalocker.LOCK_SH) lang_text = fp.read().replace('\r\n', '\n') portalocker.unlock(fp) fp.close() if not lang_text.strip(): return {} try: return eval(lang_text) except: logging.error('Syntax error in %s' % filename) return {} def read_dict(filename): return getcfs('language:%s'%filename,filename, lambda filename=filename:read_dict_aux(filename)) def utf8_repr(s): r''' # note that we use raw strings to avoid having to use double back slashes below utf8_repr() works same as repr() when processing ascii string >>> utf8_repr('abc') == utf8_repr("abc") == repr('abc') == repr("abc") == "'abc'" True >>> utf8_repr('a"b"c') == repr('a"b"c') == '\'a"b"c\'' True >>> utf8_repr("a'b'c") == repr("a'b'c") == '"a\'b\'c"' True >>> utf8_repr('a\'b"c') == repr('a\'b"c') == utf8_repr("a'b\"c") == repr("a'b\"c") == '\'a\\\'b"c\'' True >>> utf8_repr('a\r\nb') == repr('a\r\nb') == "'a\\r\\nb'" # Test for \r, \n True Unlike repr(), utf8_repr() remains utf8 content when processing utf8 string >>> utf8_repr('中文字') == utf8_repr("中文字") == "'中文字'" != repr('中文字') True >>> utf8_repr('中"文"字') == "'中\"文\"字'" != repr('中"文"字') True >>> utf8_repr("中'文'字") == '"中\'文\'字"' != repr("中'文'字") True >>> utf8_repr('中\'文"字') == utf8_repr("中'文\"字") == '\'中\\\'文"字\'' != repr('中\'文"字') == repr("中'文\"字") True >>> utf8_repr('中\r\n文') == "'中\\r\\n文'" != repr('中\r\n文') # Test for \r, \n True ''' if (s.find("'") >= 0) and (s.find('"') < 0): # only single quote exists s = ''.join(['"', s, '"']) # s = ''.join(['"', s.replace('"','\\"'), '"']) else: s = ''.join(["'", s.replace("'","\\'"), "'"]) return s.replace("\n","\\n").replace("\r","\\r") def write_dict(filename, contents): try: fp = open(filename, 'w') except IOError: logging.error('Unable to write to file %s' % filename) return portalocker.lock(fp, portalocker.LOCK_EX) fp.write('# coding: utf8\n{\n') for key in sorted(contents): fp.write('%s: %s,\n' % (utf8_repr(key), utf8_repr(contents[key]))) fp.write('}\n') portalocker.unlock(fp) fp.close() class lazyT(object): """ never to be called explicitly, returned by translator.__call__ """ m = None s = None T = None def __init__( self, message, symbols = {}, T = None, ): self.m = message self.s = symbols self.T = T def __repr__(self): return "<lazyT %s>" % (repr(str(self.m)), ) def __str__(self): return self.T.translate(self.m, self.s) def __eq__(self, other): return self.T.translate(self.m, self.s) == other def __ne__(self, other): return self.T.translate(self.m, self.s) != other def __add__(self, other): return '%s%s' % (self, other) def __radd__(self, other): return '%s%s' % (other, self) def __cmp__(self,other): return cmp(str(self),str(other)) def __hash__(self): return hash(str(self)) def __getattr__(self, name): return getattr(str(self),name) def __getitem__(self, i): return str(self)[i] def __getslice__(self, i, j): return str(self)[i:j] def __iter__(self): for c in str(self): yield c def __len__(self): return len(str(self)) def xml(self): return cgi.escape(str(self)) def encode(self, *a, **b): return str(self).encode(*a, **b) def decode(self, *a, **b): return str(self).decode(*a, **b) def read(self): return str(self) def __mod__(self, symbols): return self.T.translate(self.m, symbols) class translator(object): """ this class is instantiated by gluon.compileapp.build_environment as the T object :: T.force(None) # turns off translation T.force('fr, it') # forces web2py to translate using fr.py or it.py T(\"Hello World\") # translates \"Hello World\" using the selected file notice 1: there is no need to force since, by default, T uses accept_language to determine a translation file. notice 2: en and en-en are considered different languages! """ def __init__(self, request): self.request = request self.folder = request.folder self.current_languages = ['en'] self.accepted_language = None self.language_file = None self.http_accept_language = request.env.http_accept_language self.requested_languages = self.force(self.http_accept_language) self.lazy = True self.otherTs = {} def get_possible_languages(self): possible_languages = self.current_languages file_ending = re.compile("\.py$") for langfile in os.listdir(os.path.join(self.folder,'languages')): if file_ending.search(langfile): possible_languages.append(file_ending.sub('',langfile)) return possible_languages def set_current_languages(self, *languages): if len(languages) == 1 and isinstance(languages[0], (tuple, list)): languages = languages[0] self.current_languages = languages self.force(self.http_accept_language) def force(self, *languages): if not languages or languages[0] == None: languages = [] if len(languages) == 1 and isinstance(languages[0], (str, unicode)): languages = languages[0] if languages: if isinstance(languages, (str, unicode)): accept_languages = languages.split(';') languages = [] [languages.extend(al.split(',')) for al in accept_languages] languages = [item.strip().lower() for item in languages \ if regex_language.match(item.strip())] for language in languages: if language in self.current_languages: self.accepted_language = language break filename = os.path.join(self.folder, 'languages/', language + '.py') if os.path.exists(filename): self.accepted_language = language self.language_file = filename self.t = read_dict(filename) return languages self.language_file = None self.t = {} # ## no language by default return languages def __call__(self, message, symbols={},language=None): if not language: if self.lazy: return lazyT(message, symbols, self) else: return self.translate(message, symbols) else: try: otherT = self.otherTs[language] except KeyError: otherT = self.otherTs[language] = translator(self.request) otherT.force(language) return otherT(message,symbols) def translate(self, message, symbols): """ user ## to add a comment into a translation string the comment can be useful do discriminate different possible translations for the same string (for example different locations) T(' hello world ') -> ' hello world ' T(' hello world ## token') -> 'hello world' T('hello ## world ## token') -> 'hello ## world' the ## notation is ignored in multiline strings and strings that start with ##. this is to allow markmin syntax to be translated """ if not message.startswith('#') and not '\n' in message: tokens = message.rsplit('##', 1) else: # this allows markmin syntax in translations tokens = [message] if len(tokens) == 2: tokens[0] = tokens[0].strip() message = tokens[0] + '##' + tokens[1].strip() mt = self.t.get(message, None) if mt == None: self.t[message] = mt = tokens[0] if self.language_file and not is_gae: write_dict(self.language_file, self.t) if symbols or symbols == 0: return mt % symbols return mt def findT(path, language='en-us'): """ must be run by the admin app """ filename = os.path.join(path, 'languages', '%s.py' % language) sentences = read_dict(filename) mp = os.path.join(path, 'models') cp = os.path.join(path, 'controllers') vp = os.path.join(path, 'views') for file in listdir(mp, '.+\.py', 0) + listdir(cp, '.+\.py', 0)\ + listdir(vp, '.+\.html', 0): fp = open(file, 'r') portalocker.lock(fp, portalocker.LOCK_SH) data = fp.read() portalocker.unlock(fp) fp.close() items = regex_translate.findall(data) for item in items: try: message = eval(item) if not message.startswith('#') and not '\n' in message: tokens = message.rsplit('##', 1) else: # this allows markmin syntax in translations tokens = [message] if len(tokens) == 2: message = tokens[0].strip() + '##' + tokens[1].strip() if message and not message in sentences: sentences[message] = message except: pass write_dict(filename, sentences) ### important to allow safe session.flash=T(....) def lazyT_unpickle(data): return marshal.loads(data) def lazyT_pickle(data): return lazyT_unpickle, (marshal.dumps(str(data)),) copy_reg.pickle(lazyT, lazyT_pickle, lazyT_unpickle) def update_all_languages(application_path): path = os.path.join(application_path, 'languages/') for language in listdir(path, '^\w+(\-\w+)?\.py$'): findT(application_path, language[:-3]) if __name__ == '__main__': import doctest doctest.testmod()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) """ import sys import cPickle import traceback import types import os import datetime import logging from utils import web2py_uuid from storage import Storage from http import HTTP from html import BEAUTIFY logger = logging.getLogger("web2py") __all__ = ['RestrictedError', 'restricted', 'TicketStorage', 'compile2'] class TicketStorage(Storage): """ defines the ticket object and the default values of its members (None) """ def __init__( self, db=None, tablename='web2py_ticket' ): self.db = db self.tablename = tablename def store(self, request, ticket_id, ticket_data): """ stores the ticket. It will figure out if this must be on disk or in db """ if self.db: self._store_in_db(request, ticket_id, ticket_data) else: self._store_on_disk(request, ticket_id, ticket_data) def _store_in_db(self, request, ticket_id, ticket_data): table = self._get_table(self.db, self.tablename, request.application) table.insert(ticket_id=ticket_id, ticket_data=cPickle.dumps(ticket_data), created_datetime=request.now) logger.error('In FILE: %(layer)s\n\n%(traceback)s\n' % ticket_data) def _store_on_disk(self, request, ticket_id, ticket_data): ef = self._error_file(request, ticket_id, 'wb') try: cPickle.dump(ticket_data, ef) finally: ef.close() def _error_file(self, request, ticket_id, mode, app=None): root = request.folder if app: root = os.path.join(os.path.join(root, '..'), app) errors_folder = os.path.abspath(os.path.join(root, 'errors'))#.replace('\\', '/') return open(os.path.join(errors_folder, ticket_id), mode) def _get_table(self, db, tablename, app): tablename = tablename + '_' + app table = db.get(tablename, None) if table is None: db.rollback() # not necessary but one day # any app may store tickets on DB table = db.define_table( tablename, db.Field('ticket_id', length=100), db.Field('ticket_data', 'text'), db.Field('created_datetime', 'datetime'), ) return table def load( self, request, app, ticket_id, ): if not self.db: ef = self._error_file(request, ticket_id, 'rb', app) try: return cPickle.load(ef) finally: ef.close() table = self._get_table(self.db, self.tablename, app) rows = self.db(table.ticket_id == ticket_id).select() if rows: return cPickle.loads(rows[0].ticket_data) return None class RestrictedError(Exception): """ class used to wrap an exception that occurs in the restricted environment below. the traceback is used to log the exception and generate a ticket. """ def __init__( self, layer='', code='', output='', environment={}, ): """ layer here is some description of where in the system the exception occurred. """ self.layer = layer self.code = code self.output = output if layer: try: self.traceback = traceback.format_exc() except: self.traceback = 'no traceback because template parting error' try: self.snapshot = snapshot(context=10,code=code,environment=environment) except: self.snapshot = {} else: self.traceback = '(no error)' self.snapshot = {} self.environment = environment def log(self, request): """ logs the exception. """ try: d = { 'layer': str(self.layer), 'code': str(self.code), 'output': str(self.output), 'traceback': str(self.traceback), 'snapshot': self.snapshot, } ticket_storage = TicketStorage(db=request.tickets_db) ticket_storage.store(request, request.uuid.split('/',1)[1], d) return request.uuid except: logger.error(self.traceback) return None def load(self, request, app, ticket_id): """ loads a logged exception. """ ticket_storage = TicketStorage(db=request.tickets_db) d = ticket_storage.load(request, app, ticket_id) self.layer = d['layer'] self.code = d['code'] self.output = d['output'] self.traceback = d['traceback'] self.snapshot = d.get('snapshot') def compile2(code,layer): """ The +'\n' is necessary else compile fails when code ends in a comment. """ return compile(code.rstrip().replace('\r\n','\n')+'\n', layer, 'exec') def restricted(code, environment={}, layer='Unknown'): """ runs code in environment and returns the output. if an exception occurs in code it raises a RestrictedError containing the traceback. layer is passed to RestrictedError to identify where the error occurred. """ environment['__file__'] = layer try: if type(code) == types.CodeType: ccode = code else: ccode = compile2(code,layer) exec ccode in environment except HTTP: raise except Exception, error: # XXX Show exception in Wing IDE if running in debugger if __debug__ and 'WINGDB_ACTIVE' in os.environ: etype, evalue, tb = sys.exc_info() sys.excepthook(etype, evalue, tb) raise RestrictedError(layer, code, '', environment) def snapshot(info=None, context=5, code=None, environment=None): """Return a dict describing a given traceback (based on cgitb.text).""" import os, types, time, traceback, linecache, inspect, pydoc, cgitb # if no exception info given, get current: etype, evalue, etb = info or sys.exc_info() if type(etype) is types.ClassType: etype = etype.__name__ # create a snapshot dict with some basic information s = {} s['pyver'] = 'Python ' + sys.version.split()[0] + ': ' + sys.executable s['date'] = time.ctime(time.time()) # start to process frames records = inspect.getinnerframes(etb, context) s['frames'] = [] for frame, file, lnum, func, lines, index in records: file = file and os.path.abspath(file) or '?' args, varargs, varkw, locals = inspect.getargvalues(frame) call = '' if func != '?': call = inspect.formatargvalues(args, varargs, varkw, locals, formatvalue=lambda value: '=' + pydoc.text.repr(value)) # basic frame information f = {'file': file, 'func': func, 'call': call, 'lines': {}, 'lnum': lnum} highlight = {} def reader(lnum=[lnum]): highlight[lnum[0]] = 1 try: return linecache.getline(file, lnum[0]) finally: lnum[0] += 1 vars = cgitb.scanvars(reader, frame, locals) # if it is a view, replace with generated code if file.endswith('html'): lmin = lnum>context and (lnum-context) or 0 lmax = lnum+context lines = code.split("\n")[lmin:lmax] index = min(context, lnum) - 1 if index is not None: i = lnum - index for line in lines: f['lines'][i] = line.rstrip() i += 1 # dump local variables (referenced in current line only) f['dump'] = {} for name, where, value in vars: if name in f['dump']: continue if value is not cgitb.__UNDEF__: if where == 'global': name = 'global ' + name elif where != 'local': name = where + name.split('.')[-1] f['dump'][name] = pydoc.text.repr(value) else: f['dump'][name] = 'undefined' s['frames'].append(f) # add exception type, value and attributes s['etype'] = str(etype) s['evalue'] = str(evalue) s['exception'] = {} if isinstance(evalue, BaseException): for name in dir(evalue): # prevent py26 DeprecatedWarning: if name!='message' or sys.version_info<(2.6): value = pydoc.text.repr(getattr(evalue, name)) s['exception'][name] = value # add all local values (of last frame) to the snapshot s['locals'] = {} for name, value in locals.items(): s['locals'][name] = pydoc.text.repr(value) # add web2py environment variables for k,v in environment.items(): if k in ('request', 'response', 'session'): s[k] = BEAUTIFY(v) return s
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) Web2Py framework modules ======================== """ __all__ = ['A', 'B', 'BEAUTIFY', 'BODY', 'BR', 'CAT', 'CENTER', 'CLEANUP', 'CODE', 'CRYPT', 'DAL', 'DIV', 'EM', 'EMBED', 'FIELDSET', 'FORM', 'Field', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'HEAD', 'HR', 'HTML', 'HTTP', 'I', 'IFRAME', 'IMG', 'INPUT', 'IS_ALPHANUMERIC', 'IS_DATE', 'IS_DATETIME', 'IS_DATETIME_IN_RANGE', 'IS_DATE_IN_RANGE', 'IS_DECIMAL_IN_RANGE', 'IS_EMAIL', 'IS_EMPTY_OR', 'IS_EQUAL_TO', 'IS_EXPR', 'IS_FLOAT_IN_RANGE', 'IS_IMAGE', 'IS_INT_IN_RANGE', 'IS_IN_DB', 'IS_IN_SET', 'IS_IPV4', 'IS_LENGTH', 'IS_LIST_OF', 'IS_LOWER', 'IS_MATCH', 'IS_NOT_EMPTY', 'IS_NOT_IN_DB', 'IS_NULL_OR', 'IS_SLUG', 'IS_STRONG', 'IS_TIME', 'IS_UPLOAD_FILENAME', 'IS_UPPER', 'IS_URL', 'LABEL', 'LEGEND', 'LI', 'LINK', 'MARKMIN', 'MENU', 'META', 'OBJECT', 'OL', 'ON', 'OPTGROUP', 'OPTION', 'P', 'PRE', 'SCRIPT', 'SELECT', 'SPAN', 'SQLFORM', 'SQLTABLE', 'STYLE', 'TABLE', 'TAG', 'TBODY', 'TD', 'TEXTAREA', 'TFOOT', 'TH', 'THEAD', 'TITLE', 'TR', 'TT', 'UL', 'URL', 'XHTML', 'XML','redirect','current','embed64'] from globals import current from html import * from validators import * from http import redirect, HTTP from dal import DAL, Field from sqlhtml import SQLFORM, SQLTABLE
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) """ import storage import os import re import tarfile import glob import time from http import HTTP from gzip import open as gzopen from settings import global_settings __all__ = [ 'read_file', 'write_file', 'readlines_file', 'up', 'abspath', 'mktree', 'listdir', 'recursive_unlink', 'cleanpath', 'tar', 'untar', 'tar_compiled', 'get_session', 'check_credentials', 'w2p_pack', 'w2p_unpack', 'w2p_pack_plugin', 'w2p_unpack_plugin', 'fix_newlines', 'make_fake_file_like_object', ] def read_file(filename, mode='r'): "returns content from filename, making sure to close the file explicitly on exit." f = open(filename, mode) try: return f.read() finally: f.close() def write_file(filename, value, mode='w'): "writes <value> to filename, making sure to close the file explicitly on exit." f = open(filename, mode) try: return f.write(value) finally: f.close() def readlines_file(filename, mode='r'): "applies .split('\n') to the output of read_file()" return read_file(filename, mode).split('\n') def abspath(*relpath, **base): "convert relative path to absolute path based (by default) on applications_parent" path = os.path.join(*relpath) gluon = base.get('gluon', False) if os.path.isabs(path): return path if gluon: return os.path.join(global_settings.gluon_parent, path) return os.path.join(global_settings.applications_parent, path) def mktree(path): head,tail =os.path.split(path) if head: if tail: mktree(head) if not os.path.exists(head): os.mkdir(head) def listdir( path, expression='^.+$', drop=True, add_dirs=False, sort=True, ): """ like os.listdir() but you can specify a regex pattern to filter files. if add_dirs is True, the returned items will have the full path. """ if path[-1:] != os.path.sep: path = path + os.path.sep if drop: n = len(path) else: n = 0 regex = re.compile(expression) items = [] for (root, dirs, files) in os.walk(path, topdown=True): for dir in dirs[:]: if dir.startswith('.'): dirs.remove(dir) if add_dirs: items.append(root[n:]) for file in sorted(files): if regex.match(file) and not file.startswith('.'): items.append(os.path.join(root, file)[n:]) if sort: return sorted(items) else: return items def recursive_unlink(f): if os.path.isdir(f): for s in os.listdir(f): recursive_unlink(os.path.join(f,s)) os.rmdir(f) elif os.path.isfile(f): os.unlink(f) def cleanpath(path): """ turns any expression/path into a valid filename. replaces / with _ and removes special characters. """ items = path.split('.') if len(items) > 1: path = re.sub('[^\w\.]+', '_', '_'.join(items[:-1]) + '.' + ''.join(items[-1:])) else: path = re.sub('[^\w\.]+', '_', ''.join(items[-1:])) return path def _extractall(filename, path='.', members=None): if not hasattr(tarfile.TarFile, 'extractall'): from tarfile import ExtractError class TarFile(tarfile.TarFile): def extractall(self, path='.', members=None): """Extract all members from the archive to the current working directory and set owner, modification time and permissions on directories afterwards. `path' specifies a different directory to extract to. `members' is optional and must be a subset of the list returned by getmembers(). """ directories = [] if members is None: members = self for tarinfo in members: if tarinfo.isdir(): # Extract directory with a safe mode, so that # all files below can be extracted as well. try: os.makedirs(os.path.join(path, tarinfo.name), 0777) except EnvironmentError: pass directories.append(tarinfo) else: self.extract(tarinfo, path) # Reverse sort directories. directories.sort(lambda a, b: cmp(a.name, b.name)) directories.reverse() # Set correct owner, mtime and filemode on directories. for tarinfo in directories: path = os.path.join(path, tarinfo.name) try: self.chown(tarinfo, path) self.utime(tarinfo, path) self.chmod(tarinfo, path) except ExtractError, e: if self.errorlevel > 1: raise else: self._dbg(1, 'tarfile: %s' % e) _cls = TarFile else: _cls = tarfile.TarFile tar = _cls(filename, 'r') ret = tar.extractall(path, members) tar.close() return ret def tar(file, dir, expression='^.+$'): """ tars dir into file, only tars file that match expression """ tar = tarfile.TarFile(file, 'w') try: for file in listdir(dir, expression, add_dirs=True): tar.add(os.path.join(dir, file), file, False) finally: tar.close() def untar(file, dir): """ untar file into dir """ _extractall(file, dir) def w2p_pack(filename, path, compiled=False): filename = abspath(filename) path = abspath(path) tarname = filename + '.tar' if compiled: tar_compiled(tarname, path, '^[\w\.\-]+$') else: tar(tarname, path, '^[\w\.\-]+$') w2pfp = gzopen(filename, 'wb') tarfp = open(tarname, 'rb') w2pfp.write(tarfp.read()) w2pfp.close() tarfp.close() os.unlink(tarname) def w2p_unpack(filename, path, delete_tar=True): filename = abspath(filename) path = abspath(path) if filename[-4:] == '.w2p' or filename[-3:] == '.gz': if filename[-4:] == '.w2p': tarname = filename[:-4] + '.tar' else: tarname = filename[:-3] + '.tar' fgzipped = gzopen(filename, 'rb') tarfile = open(tarname, 'wb') tarfile.write(fgzipped.read()) tarfile.close() fgzipped.close() else: tarname = filename untar(tarname, path) if delete_tar: os.unlink(tarname) def w2p_pack_plugin(filename, path, plugin_name): """Pack the given plugin into a w2p file. Will match files at: <path>/*/plugin_[name].* <path>/*/plugin_[name]/* """ filename = abspath(filename) path = abspath(path) if not filename.endswith('web2py.plugin.%s.w2p' % plugin_name): raise Exception, "Not a web2py plugin name" plugin_tarball = tarfile.open(filename, 'w:gz') try: app_dir = path while app_dir[-1]=='/': app_dir = app_dir[:-1] files1=glob.glob(os.path.join(app_dir,'*/plugin_%s.*' % plugin_name)) files2=glob.glob(os.path.join(app_dir,'*/plugin_%s/*' % plugin_name)) for file in files1+files2: plugin_tarball.add(file, arcname=file[len(app_dir)+1:]) finally: plugin_tarball.close() def w2p_unpack_plugin(filename, path, delete_tar=True): filename = abspath(filename) path = abspath(path) if not os.path.basename(filename).startswith('web2py.plugin.'): raise Exception, "Not a web2py plugin" w2p_unpack(filename,path,delete_tar) def tar_compiled(file, dir, expression='^.+$'): """ used to tar a compiled application. the content of models, views, controllers is not stored in the tar file. """ tar = tarfile.TarFile(file, 'w') for file in listdir(dir, expression, add_dirs=True): filename = os.path.join(dir, file) if os.path.islink(filename): continue if os.path.isfile(filename) and file[-4:] != '.pyc': if file[:6] == 'models': continue if file[:5] == 'views': continue if file[:11] == 'controllers': continue if file[:7] == 'modules': continue tar.add(filename, file, False) tar.close() def up(path): return os.path.dirname(os.path.normpath(path)) def get_session(request, other_application='admin'): """ checks that user is authorized to access other_application""" if request.application == other_application: raise KeyError try: session_id = request.cookies['session_id_' + other_application].value osession = storage.load_storage(os.path.join( up(request.folder), other_application, 'sessions', session_id)) except: osession = storage.Storage() return osession def check_credentials(request, other_application='admin', expiration = 60*60): """ checks that user is authorized to access other_application""" if request.env.web2py_runtime_gae: from google.appengine.api import users if users.is_current_user_admin(): return True else: login_html = '<a href="%s">Sign in with your google account</a>.' \ % users.create_login_url(request.env.path_info) raise HTTP(200, '<html><body>%s</body></html>' % login_html) else: dt = time.time() - expiration s = get_session(request, other_application) return (s.authorized and s.last_time and s.last_time > dt) def fix_newlines(path): regex = re.compile(r'''(\r |\r| )''') for filename in listdir(path, '.*\.(py|html)$', drop=False): rdata = read_file(filename, 'rb') wdata = regex.sub('\n', rdata) if wdata != rdata: write_file(filename, wdata, 'wb') def copystream( src, dest, size, chunk_size=10 ** 5, ): """ this is here because I think there is a bug in shutil.copyfileobj """ while size > 0: if size < chunk_size: data = src.read(size) else: data = src.read(chunk_size) length = len(data) if length > size: (data, length) = (data[:size], size) size -= length if length == 0: break dest.write(data) if length < chunk_size: break dest.seek(0) return def make_fake_file_like_object(): class LogFile(object): def write(self, value): pass def close(self): pass return LogFile()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) Contains the classes for the global used variables: - Request - Response - Session """ from storage import Storage, List from streamer import streamer, stream_file_or_304_or_206, DEFAULT_CHUNK_SIZE from xmlrpc import handler from contenttype import contenttype from html import xmlescape, TABLE, TR, PRE from http import HTTP from fileutils import up from serializers import json, custom_json import settings from utils import web2py_uuid from settings import global_settings import hashlib import portalocker import cPickle import cStringIO import datetime import re import Cookie import os import sys import traceback import threading regex_session_id = re.compile('^([\w\-]+/)?[\w\-\.]+$') __all__ = ['Request', 'Response', 'Session'] current = threading.local() # thread-local storage for request-scope globals class Request(Storage): """ defines the request object and the default values of its members - env: environment variables, by gluon.main.wsgibase() - cookies - get_vars - post_vars - vars - folder - application - function - args - extension - now: datetime.datetime.today() - restful() """ def __init__(self): self.wsgi = Storage() # hooks to environ and start_response self.env = Storage() self.cookies = Cookie.SimpleCookie() self.get_vars = Storage() self.post_vars = Storage() self.vars = Storage() self.folder = None self.application = None self.function = None self.args = List() self.extension = None self.now = datetime.datetime.now() self.is_restful = False self.is_https = False self.is_local = False def compute_uuid(self): self.uuid = '%s/%s.%s.%s' % ( self.application, self.client.replace(':', '_'), self.now.strftime('%Y-%m-%d.%H-%M-%S'), web2py_uuid()) return self.uuid def user_agent(self): from gluon.contrib import user_agent_parser session = current.session session._user_agent = session._user_agent or \ user_agent_parser.detect(self.env.http_user_agent) return session._user_agent def restful(self): def wrapper(action,self=self): def f(_action=action,_self=self,*a,**b): self.is_restful = True method = _self.env.request_method if len(_self.args) and '.' in _self.args[-1]: _self.args[-1],_self.extension = _self.args[-1].rsplit('.',1) if not method in ['GET','POST','DELETE','PUT']: raise HTTP(400,"invalid method") rest_action = _action().get(method,None) if not rest_action: raise HTTP(400,"method not supported") try: return rest_action(*_self.args,**_self.vars) except TypeError, e: exc_type, exc_value, exc_traceback = sys.exc_info() if len(traceback.extract_tb(exc_traceback))==1: raise HTTP(400,"invalid arguments") else: raise e f.__doc__ = action.__doc__ f.__name__ = action.__name__ return f return wrapper class Response(Storage): """ defines the response object and the default values of its members response.write( ) can be used to write in the output html """ def __init__(self): self.status = 200 self.headers = Storage() self.headers['X-Powered-By'] = 'web2py' self.body = cStringIO.StringIO() self.session_id = None self.cookies = Cookie.SimpleCookie() self.postprocessing = [] self.flash = '' # used by the default view layout self.meta = Storage() # used by web2py_ajax.html self.menu = [] # used by the default view layout self.files = [] # used by web2py_ajax.html self.generic_patterns = [] # patterns to allow generic views self._vars = None self._caller = lambda f: f() self._view_environment = None self._custom_commit = None self._custom_rollback = None def write(self, data, escape=True): if not escape: self.body.write(str(data)) else: self.body.write(xmlescape(data)) def render(self, *a, **b): from compileapp import run_view_in if len(a) > 2: raise SyntaxError, 'Response.render can be called with two arguments, at most' elif len(a) == 2: (view, self._vars) = (a[0], a[1]) elif len(a) == 1 and isinstance(a[0], str): (view, self._vars) = (a[0], {}) elif len(a) == 1 and hasattr(a[0], 'read') and callable(a[0].read): (view, self._vars) = (a[0], {}) elif len(a) == 1 and isinstance(a[0], dict): (view, self._vars) = (None, a[0]) else: (view, self._vars) = (None, {}) self._vars.update(b) self._view_environment.update(self._vars) if view: import cStringIO (obody, oview) = (self.body, self.view) (self.body, self.view) = (cStringIO.StringIO(), view) run_view_in(self._view_environment) page = self.body.getvalue() self.body.close() (self.body, self.view) = (obody, oview) else: run_view_in(self._view_environment) page = self.body.getvalue() return page def stream( self, stream, chunk_size = DEFAULT_CHUNK_SIZE, request=None, ): """ if a controller function:: return response.stream(file, 100) the file content will be streamed at 100 bytes at the time """ if isinstance(stream, (str, unicode)): stream_file_or_304_or_206(stream, chunk_size=chunk_size, request=request, headers=self.headers) # ## the following is for backward compatibility if hasattr(stream, 'name'): filename = stream.name else: filename = None keys = [item.lower() for item in self.headers] if filename and not 'content-type' in keys: self.headers['Content-Type'] = contenttype(filename) if filename and not 'content-length' in keys: try: self.headers['Content-Length'] = \ os.path.getsize(filename) except OSError: pass if request and request.env.web2py_use_wsgi_file_wrapper: wrapped = request.env.wsgi_file_wrapper(stream, chunk_size) else: wrapped = streamer(stream, chunk_size=chunk_size) return wrapped def download(self, request, db, chunk_size = DEFAULT_CHUNK_SIZE, attachment=True): """ example of usage in controller:: def download(): return response.download(request, db) downloads from http://..../download/filename """ import contenttype as c if not request.args: raise HTTP(404) name = request.args[-1] items = re.compile('(?P<table>.*?)\.(?P<field>.*?)\..*')\ .match(name) if not items: raise HTTP(404) (t, f) = (items.group('table'), items.group('field')) field = db[t][f] try: (filename, stream) = field.retrieve(name) except IOError: raise HTTP(404) self.headers['Content-Type'] = c.contenttype(name) if attachment: self.headers['Content-Disposition'] = \ "attachment; filename=%s" % filename return self.stream(stream, chunk_size = chunk_size, request=request) def json(self, data, default=None): return json(data, default = default or custom_json) def xmlrpc(self, request, methods): """ assuming:: def add(a, b): return a+b if a controller function \"func\":: return response.xmlrpc(request, [add]) the controller will be able to handle xmlrpc requests for the add function. Example:: import xmlrpclib connection = xmlrpclib.ServerProxy('http://hostname/app/contr/func') print connection.add(3, 4) """ return handler(request, self, methods) def toolbar(self): from html import DIV, SCRIPT, BEAUTIFY, TAG, URL BUTTON = TAG.button admin = URL("admin","default","design", args=current.request.application) from gluon.dal import thread dbstats = [TABLE(*[TR(PRE(row[0]),'%.2fms' % (row[1]*1000)) \ for row in i.db._timings]) \ for i in thread.instances] u = web2py_uuid() return DIV( BUTTON('design',_onclick="document.location='%s'" % admin), BUTTON('request',_onclick="jQuery('#request-%s').slideToggle()"%u), DIV(BEAUTIFY(current.request),_class="hidden",_id="request-%s"%u), BUTTON('session',_onclick="jQuery('#session-%s').slideToggle()"%u), DIV(BEAUTIFY(current.session),_class="hidden",_id="session-%s"%u), BUTTON('response',_onclick="jQuery('#response-%s').slideToggle()"%u), DIV(BEAUTIFY(current.response),_class="hidden",_id="response-%s"%u), BUTTON('db stats',_onclick="jQuery('#db-stats-%s').slideToggle()"%u), DIV(BEAUTIFY(dbstats),_class="hidden",_id="db-stats-%s"%u), SCRIPT("jQuery('.hidden').hide()") ) class Session(Storage): """ defines the session object and the default values of its members (None) """ def connect( self, request, response, db=None, tablename='web2py_session', masterapp=None, migrate=True, separate = None, check_client=False, ): """ separate can be separate=lambda(session_name): session_name[-2:] and it is used to determine a session prefix. separate can be True and it is set to session_name[-2:] """ if separate == True: separate = lambda session_name: session_name[-2:] self._unlock(response) if not masterapp: masterapp = request.application response.session_id_name = 'session_id_%s' % masterapp.lower() if not db: if global_settings.db_sessions is True or masterapp in global_settings.db_sessions: return response.session_new = False client = request.client.replace(':', '.') if response.session_id_name in request.cookies: response.session_id = \ request.cookies[response.session_id_name].value if regex_session_id.match(response.session_id): response.session_filename = \ os.path.join(up(request.folder), masterapp, 'sessions', response.session_id) else: response.session_id = None if response.session_id: try: response.session_file = \ open(response.session_filename, 'rb+') try: portalocker.lock(response.session_file, portalocker.LOCK_EX) response.session_locked = True self.update(cPickle.load(response.session_file)) response.session_file.seek(0) oc = response.session_filename.split('/')[-1].split('-')[0] if check_client and client!=oc: raise Exception, "cookie attack" finally: pass #This causes admin login to break. Must find out why. #self._close(response) except: response.session_id = None if not response.session_id: uuid = web2py_uuid() response.session_id = '%s-%s' % (client, uuid) if separate: prefix = separate(response.session_id) response.session_id = '%s/%s' % (prefix,response.session_id) response.session_filename = \ os.path.join(up(request.folder), masterapp, 'sessions', response.session_id) response.session_new = True else: if global_settings.db_sessions is not True: global_settings.db_sessions.add(masterapp) response.session_db = True if response.session_file: self._close(response) if settings.global_settings.web2py_runtime_gae: # in principle this could work without GAE request.tickets_db = db if masterapp == request.application: table_migrate = migrate else: table_migrate = False tname = tablename + '_' + masterapp table = db.get(tname, None) if table is None: table = db.define_table( tname, db.Field('locked', 'boolean', default=False), db.Field('client_ip', length=64), db.Field('created_datetime', 'datetime', default=request.now), db.Field('modified_datetime', 'datetime'), db.Field('unique_key', length=64), db.Field('session_data', 'blob'), migrate=table_migrate, ) try: key = request.cookies[response.session_id_name].value (record_id, unique_key) = key.split(':') if record_id == '0': raise Exception, 'record_id == 0' rows = db(table.id == record_id).select() if len(rows) == 0 or rows[0].unique_key != unique_key: raise Exception, 'No record' # rows[0].update_record(locked=True) session_data = cPickle.loads(rows[0].session_data) self.update(session_data) except Exception: record_id = None unique_key = web2py_uuid() session_data = {} response._dbtable_and_field = \ (response.session_id_name, table, record_id, unique_key) response.session_id = '%s:%s' % (record_id, unique_key) response.cookies[response.session_id_name] = response.session_id response.cookies[response.session_id_name]['path'] = '/' self.__hash = hashlib.md5(str(self)).digest() if self.flash: (response.flash, self.flash) = (self.flash, None) def is_new(self): if self._start_timestamp: return False else: self._start_timestamp = datetime.datetime.today() return True def is_expired(self, seconds = 3600): now = datetime.datetime.today() if not self._last_timestamp or \ self._last_timestamp + datetime.timedelta(seconds = seconds) > now: self._last_timestamp = now return False else: return True def secure(self): self._secure = True def forget(self, response=None): self._close(response) self._forget = True def _try_store_in_db(self, request, response): # don't save if file-based sessions, no session id, or session being forgotten if not response.session_db or not response.session_id or self._forget: return # don't save if no change to session __hash = self.__hash if __hash is not None: del self.__hash if __hash == hashlib.md5(str(self)).digest(): return (record_id_name, table, record_id, unique_key) = \ response._dbtable_and_field dd = dict(locked=False, client_ip=request.env.remote_addr, modified_datetime=request.now, session_data=cPickle.dumps(dict(self)), unique_key=unique_key) if record_id: table._db(table.id == record_id).update(**dd) else: record_id = table.insert(**dd) response.cookies[response.session_id_name] = '%s:%s'\ % (record_id, unique_key) response.cookies[response.session_id_name]['path'] = '/' def _try_store_on_disk(self, request, response): # don't save if sessions not not file-based if response.session_db: return # don't save if no change to session __hash = self.__hash if __hash is not None: del self.__hash if __hash == hashlib.md5(str(self)).digest(): self._close(response) return if not response.session_id or self._forget: self._close(response) return if response.session_new: # Tests if the session sub-folder exists, if not, create it session_folder = os.path.dirname(response.session_filename) if not os.path.exists(session_folder): os.mkdir(session_folder) response.session_file = open(response.session_filename, 'wb') portalocker.lock(response.session_file, portalocker.LOCK_EX) response.session_locked = True if response.session_file: cPickle.dump(dict(self), response.session_file) response.session_file.truncate() self._close(response) def _unlock(self, response): if response and response.session_file and response.session_locked: try: portalocker.unlock(response.session_file) response.session_locked = False except: ### this should never happen but happens in Windows pass def _close(self, response): if response and response.session_file: self._unlock(response) try: response.session_file.close() del response.session_file except: pass
Python
""" This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) """ import datetime from storage import Storage from html import TAG from html import xmlescape from languages import lazyT import contrib.simplejson as simplejson import contrib.rss2 as rss2 def custom_json(o): if hasattr(o,'custom_json') and callable(o.custom_json): return o.custom_json() if isinstance(o, (datetime.date, datetime.datetime, datetime.time)): return o.isoformat()[:19].replace('T',' ') elif isinstance(o, (int, long)): return int(o) elif isinstance(o, lazyT): return str(o) elif hasattr(o,'as_list') and callable(o.as_list): return o.as_list() elif hasattr(o,'as_dict') and callable(o.as_dict): return o.as_dict() else: raise TypeError(repr(o) + " is not JSON serializable") def xml_rec(value, key): if hasattr(value,'custom_xml') and callable(value.custom_xml): return value.custom_xml() elif isinstance(value, (dict, Storage)): return TAG[key](*[TAG[k](xml_rec(v, '')) for k, v in value.items()]) elif isinstance(value, list): return TAG[key](*[TAG.item(xml_rec(item, '')) for item in value]) elif hasattr(value,'as_list') and callable(value.as_list): return str(xml_rec(value.as_list(),'')) elif hasattr(value,'as_dict') and callable(value.as_dict): return str(xml_rec(value.as_dict(),'')) else: return xmlescape(value) def xml(value, encoding='UTF-8', key='document'): return ('<?xml version="1.0" encoding="%s"?>' % encoding) + str(xml_rec(value,key)) def json(value,default=custom_json): return simplejson.dumps(value,default=default) def csv(value): return '' def rss(feed): if not 'entries' in feed and 'items' in feed: feed['entries'] = feed['items'] now=datetime.datetime.now() rss = rss2.RSS2(title = feed['title'], link = str(feed['link']), description = feed['description'], lastBuildDate = feed.get('created_on', now), items = [rss2.RSSItem(\ title=entry['title'], link=str(entry['link']), description=entry['description'], pubDate=entry.get('created_on', now) )\ for entry in feed['entries'] ] ) return rss2.dumps(rss)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) """ import os import stat import time import re import errno import rewrite from http import HTTP from contenttype import contenttype regex_start_range = re.compile('\d+(?=\-)') regex_stop_range = re.compile('(?<=\-)\d+') DEFAULT_CHUNK_SIZE = 64*1024 def streamer(stream, chunk_size = DEFAULT_CHUNK_SIZE, bytes = None): offset = 0 while bytes == None or offset < bytes: if bytes != None and bytes - offset < chunk_size: chunk_size = bytes - offset data = stream.read(chunk_size) length = len(data) if not length: break else: yield data if length < chunk_size: break offset += length stream.close() def stream_file_or_304_or_206( static_file, chunk_size = DEFAULT_CHUNK_SIZE, request = None, headers = {}, error_message = None, ): if error_message is None: error_message = rewrite.thread.routes.error_message % 'invalid request' try: fp = open(static_file) except IOError, e: if e[0] == errno.EISDIR: raise HTTP(403, error_message, web2py_error='file is a directory') elif e[0] == errno.EACCES: raise HTTP(403, error_message, web2py_error='inaccessible file') else: raise HTTP(404, error_message, web2py_error='invalid file') else: fp.close() stat_file = os.stat(static_file) fsize = stat_file[stat.ST_SIZE] mtime = time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(stat_file[stat.ST_MTIME])) headers['Content-Type'] = contenttype(static_file) headers['Last-Modified'] = mtime headers['Pragma'] = 'cache' headers['Cache-Control'] = 'private' if request and request.env.http_if_modified_since == mtime: raise HTTP(304, **{'Content-Type': headers['Content-Type']}) elif request and request.env.http_range: start_items = regex_start_range.findall(request.env.http_range) if not start_items: start_items = [0] stop_items = regex_stop_range.findall(request.env.http_range) if not stop_items or int(stop_items[0]) > fsize - 1: stop_items = [fsize - 1] part = (int(start_items[0]), int(stop_items[0]), fsize) bytes = part[1] - part[0] + 1 try: stream = open(static_file, 'rb') except IOError, e: if e[0] in (errno.EISDIR, errno.EACCES): raise HTTP(403) else: raise HTTP(404) stream.seek(part[0]) headers['Content-Range'] = 'bytes %i-%i/%i' % part headers['Content-Length'] = '%i' % bytes status = 206 else: try: stream = open(static_file, 'rb') except IOError, e: if e[0] in (errno.EISDIR, errno.EACCES): raise HTTP(403) else: raise HTTP(404) headers['Content-Length'] = fsize bytes = None status = 200 if request and request.env.web2py_use_wsgi_file_wrapper: wrapped = request.env.wsgi_file_wrapper(stream, chunk_size) else: wrapped = streamer(stream, chunk_size=chunk_size, bytes=bytes) raise HTTP(status, wrapped, **headers)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) Functions required to execute app components ============================================ FOR INTERNAL USE ONLY """ import re import sys import fnmatch import os import copy import random import __builtin__ from storage import Storage, List from template import parse_template from restricted import restricted, compile2 from fileutils import mktree, listdir, read_file, write_file from myregex import regex_expose from languages import translator from dal import BaseAdapter, SQLDB, SQLField, DAL, Field from sqlhtml import SQLFORM, SQLTABLE from cache import Cache from globals import current import settings from cfs import getcfs import html import validators from http import HTTP, redirect import marshal import shutil import imp import logging logger = logging.getLogger("web2py") import rewrite try: import py_compile except: logger.warning('unable to import py_compile') is_gae = settings.global_settings.web2py_runtime_gae is_jython = settings.global_settings.is_jython = 'java' in sys.platform.lower() or hasattr(sys, 'JYTHON_JAR') or str(sys.copyright).find('Jython') > 0 TEST_CODE = \ r""" def _TEST(): import doctest, sys, cStringIO, types, cgi, gluon.fileutils if not gluon.fileutils.check_credentials(request): raise HTTP(401, web2py_error='invalid credentials') stdout = sys.stdout html = '<h2>Testing controller "%s.py" ... done.</h2><br/>\n' \ % request.controller for key in sorted([key for key in globals() if not key in __symbols__+['_TEST']]): eval_key = eval(key) if type(eval_key) == types.FunctionType: number_doctests = sum([len(ds.examples) for ds in doctest.DocTestFinder().find(eval_key)]) if number_doctests>0: sys.stdout = cStringIO.StringIO() name = '%s/controllers/%s.py in %s.__doc__' \ % (request.folder, request.controller, key) doctest.run_docstring_examples(eval_key, globals(), False, name=name) report = sys.stdout.getvalue().strip() if report: pf = 'failed' else: pf = 'passed' html += '<h3 class="%s">Function %s [%s]</h3>\n' \ % (pf, key, pf) if report: html += CODE(report, language='web2py', \ link='/examples/global/vars/').xml() html += '<br/>\n' else: html += \ '<h3 class="nodoctests">Function %s [no doctests]</h3><br/>\n' \ % (key) response._vars = html sys.stdout = stdout _TEST() """ class mybuiltin(object): """ NOTE could simple use a dict and populate it, NOTE not sure if this changes things though if monkey patching import..... """ #__builtins__ def __getitem__(self, key): try: return getattr(__builtin__, key) except AttributeError: raise KeyError, key def __setitem__(self, key, value): setattr(self, key, value) class LoadFactory(object): """ Attention: this helper is new and experimental """ def __init__(self,environment): self.environment = environment def __call__(self, c=None, f='index', args=[], vars={}, extension=None, target=None,ajax=False,ajax_trap=False, url=None,user_signature=False, content='loading...',**attr): import globals target = target or 'c'+str(random.random())[2:] attr['_id']=target request = self.environment['request'] if not isinstance(vars,Storage): vars = Storage(vars) if '.' in f: f, extension = f.split('.',1) if url or ajax: url = url or html.URL(request.application, c, f, r=request, args=args, vars=vars, extension=extension, user_signature=user_signature) script = html.SCRIPT('web2py_component("%s","%s")' % (url, target), _type="text/javascript") return html.TAG[''](script, html.DIV(content,**attr)) else: if not isinstance(args,(list,tuple)): args = [args] c = c or request.controller other_request = Storage() for key, value in request.items(): other_request[key] = value other_request['env'] = Storage() for key, value in request.env.items(): other_request.env['key'] = value other_request.controller = c other_request.function = f other_request.extension = extension or request.extension other_request.args = List(args) other_request.vars = vars other_request.get_vars = vars other_request.post_vars = Storage() other_response = globals.Response() other_request.env.path_info = '/' + \ '/'.join([request.application,c,f] + \ map(str, other_request.args)) other_request.env.query_string = \ vars and html.URL(vars=vars).split('?')[1] or '' other_request.env.http_web2py_component_location = \ request.env.path_info other_request.cid = target other_request.env.http_web2py_component_element = target other_response.view = '%s/%s.%s' % (c,f, other_request.extension) other_environment = copy.copy(self.environment) other_response._view_environment = other_environment other_response.generic_patterns = \ copy.copy(current.response.generic_patterns) other_environment['request'] = other_request other_environment['response'] = other_response ## some magic here because current are thread-locals original_request, current.request = current.request, other_request original_response, current.response = current.response, other_response page = run_controller_in(c, f, other_environment) if isinstance(page, dict): other_response._vars = page for key in page: other_response._view_environment[key] = page[key] run_view_in(other_response._view_environment) page = other_response.body.getvalue() current.request, current.response = original_request, original_response js = None if ajax_trap: link = html.URL(request.application, c, f, r=request, args=args, vars=vars, extension=extension, user_signature=user_signature) js = "web2py_trap_form('%s','%s');" % (link, target) script = js and html.SCRIPT(js,_type="text/javascript") or '' return html.TAG[''](html.DIV(html.XML(page),**attr),script) def local_import_aux(name, force=False, app='welcome'): """ In apps, instead of importing a local module (in applications/app/modules) with:: import a.b.c as d you should do:: d = local_import('a.b.c') or (to force a reload): d = local_import('a.b.c', reload=True) This prevents conflict between applications and un-necessary execs. It can be used to import any module, including regular Python modules. """ items = name.replace('/','.') name = "applications.%s.modules.%s" % (app, items) module = __import__(name) for item in name.split(".")[1:]: module = getattr(module, item) if force: reload(module) return module """ OLD IMPLEMENTATION: items = name.replace('/','.').split('.') filename, modulepath = items[-1], os.path.join(apath,'modules',*items[:-1]) imp.acquire_lock() try: file=None (file,path,desc) = imp.find_module(filename,[modulepath]+sys.path) if not path in sys.modules or reload: if is_gae: module={} execfile(path,{},module) module=Storage(module) else: module = imp.load_module(path,file,path,desc) sys.modules[path] = module else: module = sys.modules[path] except Exception, e: module = None if file: file.close() imp.release_lock() if not module: raise ImportError, "cannot find module %s in %s" % (filename, modulepath) return module """ def build_environment(request, response, session, store_current=True): """ Build the environment dictionary into which web2py files are executed. """ environment = {} for key in html.__all__: environment[key] = getattr(html, key) for key in validators.__all__: environment[key] = getattr(validators, key) if not request.env: request.env = Storage() t = environment['T'] = translator(request) c = environment['cache'] = Cache(request) if store_current: current.request = request current.response = response current.session = session current.T = t current.cache = c global __builtins__ if is_jython: # jython hack __builtins__ = mybuiltin() else: __builtins__['__import__'] = __builtin__.__import__ environment['__builtins__'] = __builtins__ environment['HTTP'] = HTTP environment['redirect'] = redirect environment['request'] = request environment['response'] = response environment['session'] = session environment['DAL'] = DAL environment['Field'] = Field environment['SQLDB'] = SQLDB # for backward compatibility environment['SQLField'] = SQLField # for backward compatibility environment['SQLFORM'] = SQLFORM environment['SQLTABLE'] = SQLTABLE environment['LOAD'] = LoadFactory(environment) environment['local_import'] = \ lambda name, reload=False, app=request.application:\ local_import_aux(name,reload,app) BaseAdapter.set_folder(os.path.join(request.folder, 'databases')) response._view_environment = copy.copy(environment) return environment def save_pyc(filename): """ Bytecode compiles the file `filename` """ py_compile.compile(filename) def read_pyc(filename): """ Read the code inside a bytecode compiled file if the MAGIC number is compatible :returns: a code object """ data = read_file(filename, 'rb') if not is_gae and data[:4] != imp.get_magic(): raise SystemError, 'compiled code is incompatible' return marshal.loads(data[8:]) def compile_views(folder): """ Compiles all the views in the application specified by `folder` """ path = os.path.join(folder, 'views') for file in listdir(path, '^[\w/]+\.\w+$'): data = parse_template(file, path) filename = ('views/%s.py' % file).replace('/', '_').replace('\\', '_') filename = os.path.join(folder, 'compiled', filename) write_file(filename, data) save_pyc(filename) os.unlink(filename) def compile_models(folder): """ Compiles all the models in the application specified by `folder` """ path = os.path.join(folder, 'models') for file in listdir(path, '.+\.py$'): data = read_file(os.path.join(path, file)) filename = os.path.join(folder, 'compiled','models',file) mktree(filename) write_file(filename, data) save_pyc(filename) os.unlink(filename) def compile_controllers(folder): """ Compiles all the controllers in the application specified by `folder` """ path = os.path.join(folder, 'controllers') for file in listdir(path, '.+\.py$'): ### why is this here? save_pyc(os.path.join(path, file)) data = read_file(os.path.join(path,file)) exposed = regex_expose.findall(data) for function in exposed: command = data + "\nresponse._vars=response._caller(%s)\n" % \ function filename = os.path.join(folder, 'compiled', ('controllers/' + file[:-3]).replace('/', '_') + '_' + function + '.py') write_file(filename, command) save_pyc(filename) os.unlink(filename) def run_models_in(environment): """ Runs all models (in the app specified by the current folder) It tries pre-compiled models first before compiling them. """ folder = environment['request'].folder c = environment['request'].controller f = environment['request'].function cpath = os.path.join(folder, 'compiled') if os.path.exists(cpath): for model in listdir(cpath, '^models_\w+\.pyc$', 0): restricted(read_pyc(model), environment, layer=model) path = os.path.join(cpath, 'models') models = listdir(path, '^\w+\.pyc$',0,sort=False) compiled=True else: path = os.path.join(folder, 'models') models = listdir(path, '^\w+\.py$',0,sort=False) compiled=False paths = (path, os.path.join(path,c), os.path.join(path,c,f)) for model in models: if not os.path.split(model)[0] in paths and c!='appadmin': continue elif compiled: code = read_pyc(model) elif is_gae: code = getcfs(model, model, lambda: compile2(read_file(model), model)) else: code = getcfs(model, model, None) restricted(code, environment, layer=model) def run_controller_in(controller, function, environment): """ Runs the controller.function() (for the app specified by the current folder). It tries pre-compiled controller_function.pyc first before compiling it. """ # if compiled should run compiled! folder = environment['request'].folder path = os.path.join(folder, 'compiled') badc = 'invalid controller (%s/%s)' % (controller, function) badf = 'invalid function (%s/%s)' % (controller, function) if os.path.exists(path): filename = os.path.join(path, 'controllers_%s_%s.pyc' % (controller, function)) if not os.path.exists(filename): raise HTTP(404, rewrite.thread.routes.error_message % badf, web2py_error=badf) restricted(read_pyc(filename), environment, layer=filename) elif function == '_TEST': # TESTING: adjust the path to include site packages from settings import global_settings from admin import abspath, add_path_first paths = (global_settings.gluon_parent, abspath('site-packages', gluon=True), abspath('gluon', gluon=True), '') [add_path_first(path) for path in paths] # TESTING END filename = os.path.join(folder, 'controllers/%s.py' % controller) if not os.path.exists(filename): raise HTTP(404, rewrite.thread.routes.error_message % badc, web2py_error=badc) environment['__symbols__'] = environment.keys() code = read_file(filename) code += TEST_CODE restricted(code, environment, layer=filename) else: filename = os.path.join(folder, 'controllers/%s.py' % controller) if not os.path.exists(filename): raise HTTP(404, rewrite.thread.routes.error_message % badc, web2py_error=badc) code = read_file(filename) exposed = regex_expose.findall(code) if not function in exposed: raise HTTP(404, rewrite.thread.routes.error_message % badf, web2py_error=badf) code = "%s\nresponse._vars=response._caller(%s)\n" % (code, function) if is_gae: layer = filename + ':' + function code = getcfs(layer, filename, lambda: compile2(code,layer)) restricted(code, environment, filename) response = environment['response'] vars=response._vars if response.postprocessing: for p in response.postprocessing: vars = p(vars) if isinstance(vars,unicode): vars = vars.encode('utf8') if hasattr(vars,'xml'): vars = vars.xml() return vars def run_view_in(environment): """ Executes the view for the requested action. The view is the one specified in `response.view` or determined by the url or `view/generic.extension` It tries the pre-compiled views_controller_function.pyc before compiling it. """ request = environment['request'] response = environment['response'] folder = request.folder path = os.path.join(folder, 'compiled') badv = 'invalid view (%s)' % response.view patterns = response.generic_patterns or [] regex = re.compile('|'.join(fnmatch.translate(r) for r in patterns)) short_action = '%(controller)s/%(function)s.%(extension)s' % request allow_generic = patterns and regex.search(short_action) if not isinstance(response.view, str): ccode = parse_template(response.view, os.path.join(folder, 'views'), context=environment) restricted(ccode, environment, 'file stream') elif os.path.exists(path): x = response.view.replace('/', '_') files = ['views_%s.pyc' % x] if allow_generic: files.append('views_generic.%s.pyc' % request.extension) # for backward compatibility if request.extension == 'html': files.append('views_%s.pyc' % x[:-5]) if allow_generic: files.append('views_generic.pyc') # end backward compatibility code for f in files: filename = os.path.join(path,f) if os.path.exists(filename): code = read_pyc(filename) restricted(code, environment, layer=filename) return raise HTTP(404, rewrite.thread.routes.error_message % badv, web2py_error=badv) else: filename = os.path.join(folder, 'views', response.view) if not os.path.exists(filename) and allow_generic: response.view = 'generic.' + request.extension filename = os.path.join(folder, 'views', response.view) if not os.path.exists(filename): raise HTTP(404, rewrite.thread.routes.error_message % badv, web2py_error=badv) layer = filename if is_gae: ccode = getcfs(layer, filename, lambda: compile2(parse_template(response.view, os.path.join(folder, 'views'), context=environment),layer)) else: ccode = parse_template(response.view, os.path.join(folder, 'views'), context=environment) restricted(ccode, environment, layer) def remove_compiled_application(folder): """ Deletes the folder `compiled` containing the compiled application. """ try: shutil.rmtree(os.path.join(folder, 'compiled')) path = os.path.join(folder, 'controllers') for file in listdir(path,'.*\.pyc$',drop=False): os.unlink(file) except OSError: pass def compile_application(folder): """ Compiles all models, views, controller for the application in `folder`. """ remove_compiled_application(folder) os.mkdir(os.path.join(folder, 'compiled')) compile_models(folder) compile_controllers(folder) compile_views(folder) def test(): """ Example:: >>> import traceback, types >>> environment={'x':1} >>> open('a.py', 'w').write('print 1/x') >>> save_pyc('a.py') >>> os.unlink('a.py') >>> if type(read_pyc('a.pyc'))==types.CodeType: print 'code' code >>> exec read_pyc('a.pyc') in environment 1 """ return if __name__ == '__main__': import doctest doctest.testmod()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) """ import re import cgi __all__ = ['highlight'] class Highlighter(object): """ Do syntax highlighting. """ def __init__( self, mode, link=None, styles={}, ): """ Initialise highlighter: mode = language (PYTHON, WEB2PY,C, CPP, HTML, HTML_PLAIN) """ mode = mode.upper() if link and link[-1] != '/': link = link + '/' self.link = link self.styles = styles self.output = [] self.span_style = None if mode == 'WEB2PY': (mode, self.suppress_tokens) = ('PYTHON', []) elif mode == 'PYTHON': self.suppress_tokens = ['GOTOHTML'] elif mode == 'CPP': (mode, self.suppress_tokens) = ('C', []) elif mode == 'C': self.suppress_tokens = ['CPPKEYWORD'] elif mode == 'HTML_PLAIN': (mode, self.suppress_tokens) = ('HTML', ['GOTOPYTHON']) elif mode == 'HTML': self.suppress_tokens = [] else: raise SyntaxError, 'Unknown mode: %s' % mode self.mode = mode def c_tokenizer( self, token, match, style, ): """ Callback for C specific highlighting. """ value = cgi.escape(match.group()) self.change_style(token, style) self.output.append(value) def python_tokenizer( self, token, match, style, ): """ Callback for python specific highlighting. """ value = cgi.escape(match.group()) if token == 'MULTILINESTRING': self.change_style(token, style) self.output.append(value) self.strMultilineString = match.group(1) return 'PYTHONMultilineString' elif token == 'ENDMULTILINESTRING': if match.group(1) == self.strMultilineString: self.output.append(value) self.strMultilineString = '' return 'PYTHON' if style and style[:5] == 'link:': self.change_style(None, None) (url, style) = style[5:].split(';', 1) if url == 'None' or url == '': self.output.append('<span style="%s">%s</span>' % (style, value)) else: self.output.append('<a href="%s%s" style="%s">%s</a>' % (url, value, style, value)) else: self.change_style(token, style) self.output.append(value) if token == 'GOTOHTML': return 'HTML' return None def html_tokenizer( self, token, match, style, ): """ Callback for HTML specific highlighting. """ value = cgi.escape(match.group()) self.change_style(token, style) self.output.append(value) if token == 'GOTOPYTHON': return 'PYTHON' return None all_styles = { 'C': (c_tokenizer, ( ('COMMENT', re.compile(r'//.*\r?\n'), 'color: green; font-style: italic'), ('MULTILINECOMMENT', re.compile(r'/\*.*?\*/', re.DOTALL), 'color: green; font-style: italic'), ('PREPROCESSOR', re.compile(r'\s*#.*?[^\\]\s*\n', re.DOTALL), 'color: magenta; font-style: italic'), ('PUNC', re.compile(r'[-+*!&|^~/%\=<>\[\]{}(),.:]'), 'font-weight: bold'), ('NUMBER', re.compile(r'0x[0-9a-fA-F]+|[+-]?\d+(\.\d+)?([eE][+-]\d+)?|\d+'), 'color: red'), ('KEYWORD', re.compile(r'(sizeof|int|long|short|char|void|' + r'signed|unsigned|float|double|' + r'goto|break|return|continue|asm|' + r'case|default|if|else|switch|while|for|do|' + r'struct|union|enum|typedef|' + r'static|register|auto|volatile|extern|const)(?![a-zA-Z0-9_])'), 'color:#185369; font-weight: bold'), ('CPPKEYWORD', re.compile(r'(class|private|protected|public|template|new|delete|' + r'this|friend|using|inline|export|bool|throw|try|catch|' + r'operator|typeid|virtual)(?![a-zA-Z0-9_])'), 'color: blue; font-weight: bold'), ('STRING', re.compile(r'r?u?\'(.*?)(?<!\\)\'|"(.*?)(?<!\\)"'), 'color: #FF9966'), ('IDENTIFIER', re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*'), None), ('WHITESPACE', re.compile(r'[ \r\n]+'), 'Keep'), )), 'PYTHON': (python_tokenizer, ( ('GOTOHTML', re.compile(r'\}\}'), 'color: red'), ('PUNC', re.compile(r'[-+*!|&^~/%\=<>\[\]{}(),.:]'), 'font-weight: bold'), ('NUMBER', re.compile(r'0x[0-9a-fA-F]+|[+-]?\d+(\.\d+)?([eE][+-]\d+)?|\d+' ), 'color: red'), ('KEYWORD', re.compile(r'(def|class|break|continue|del|exec|finally|pass|' + r'print|raise|return|try|except|global|assert|lambda|' + r'yield|for|while|if|elif|else|and|in|is|not|or|import|' + r'from|True|False)(?![a-zA-Z0-9_])'), 'color:#185369; font-weight: bold'), ('WEB2PY', re.compile(r'(request|response|session|cache|redirect|local_import|HTTP|TR|XML|URL|BEAUTIFY|A|BODY|BR|B|CAT|CENTER|CODE|DIV|EM|EMBED|FIELDSET|LEGEND|FORM|H1|H2|H3|H4|H5|H6|IFRAME|HEAD|HR|HTML|I|IMG|INPUT|LABEL|LI|LINK|MARKMIN|MENU|META|OBJECT|OL|ON|OPTION|P|PRE|SCRIPT|SELECT|SPAN|STYLE|TABLE|THEAD|TBODY|TFOOT|TAG|TD|TEXTAREA|TH|TITLE|TT|T|UL|XHTML|IS_SLUG|IS_STRONG|IS_LOWER|IS_UPPER|IS_ALPHANUMERIC|IS_DATETIME|IS_DATETIME_IN_RANGE|IS_DATE|IS_DATE_IN_RANGE|IS_DECIMAL_IN_RANGE|IS_EMAIL|IS_EXPR|IS_FLOAT_IN_RANGE|IS_IMAGE|IS_INT_IN_RANGE|IS_IN_SET|IS_IPV4|IS_LIST_OF|IS_LENGTH|IS_MATCH|IS_EQUAL_TO|IS_EMPTY_OR|IS_NULL_OR|IS_NOT_EMPTY|IS_TIME|IS_UPLOAD_FILENAME|IS_URL|CLEANUP|CRYPT|IS_IN_DB|IS_NOT_IN_DB|DAL|Field|SQLFORM|SQLTABLE|xmlescape|embed64)(?![a-zA-Z0-9_])' ), 'link:%(link)s;text-decoration:None;color:#FF5C1F;'), ('MAGIC', re.compile(r'self|None'), 'color:#185369; font-weight: bold'), ('MULTILINESTRING', re.compile(r'r?u?(\'\'\'|""")'), 'color: #FF9966'), ('STRING', re.compile(r'r?u?\'(.*?)(?<!\\)\'|"(.*?)(?<!\\)"' ), 'color: #FF9966'), ('IDENTIFIER', re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*'), None), ('COMMENT', re.compile(r'\#.*\r?\n'), 'color: green; font-style: italic'), ('WHITESPACE', re.compile(r'[ \r\n]+'), 'Keep'), )), 'PYTHONMultilineString': (python_tokenizer, (('ENDMULTILINESTRING', re.compile(r'.*?("""|\'\'\')', re.DOTALL), 'color: darkred'), )), 'HTML': (html_tokenizer, ( ('GOTOPYTHON', re.compile(r'\{\{'), 'color: red'), ('COMMENT', re.compile(r'<!--[^>]*-->|<!>'), 'color: green; font-style: italic'), ('XMLCRAP', re.compile(r'<![^>]*>'), 'color: blue; font-style: italic'), ('SCRIPT', re.compile(r'<script .*?</script>', re.IGNORECASE + re.DOTALL), 'color: black'), ('TAG', re.compile(r'</?\s*[a-zA-Z0-9]+'), 'color: darkred; font-weight: bold'), ('ENDTAG', re.compile(r'/?>'), 'color: darkred; font-weight: bold'), )), } def highlight(self, data): """ Syntax highlight some python code. Returns html version of code. """ i = 0 mode = self.mode while i < len(data): for (token, o_re, style) in Highlighter.all_styles[mode][1]: if not token in self.suppress_tokens: match = o_re.match(data, i) if match: if style: new_mode = \ Highlighter.all_styles[mode][0](self, token, match, style % dict(link=self.link)) else: new_mode = \ Highlighter.all_styles[mode][0](self, token, match, style) if new_mode != None: mode = new_mode i += max(1, len(match.group())) break else: self.change_style(None, None) self.output.append(data[i]) i += 1 self.change_style(None, None) return ''.join(self.output).expandtabs(4) def change_style(self, token, style): """ Generate output to change from existing style to another style only. """ if token in self.styles: style = self.styles[token] if self.span_style != style: if style != 'Keep': if self.span_style != None: self.output.append('</span>') if style != None: self.output.append('<span style="%s">' % style) self.span_style = style def highlight( code, language, link='/examples/globals/vars/', counter=1, styles={}, highlight_line=None, attributes={}, ): if not 'CODE' in styles: code_style = """ font-size: 11px; font-family: Bitstream Vera Sans Mono,monospace; background-color: transparent; margin: 0; padding: 5px; border: none; overflow: auto; white-space: pre !important;\n""" else: code_style = styles['CODE'] if not 'LINENUMBERS' in styles: linenumbers_style = """ font-size: 11px; font-family: Bitstream Vera Sans Mono,monospace; background-color: transparent; margin: 0; padding: 5px; border: none; color: #A0A0A0;\n""" else: linenumbers_style = styles['LINENUMBERS'] if not 'LINEHIGHLIGHT' in styles: linehighlight_style = "background-color: #EBDDE2;" else: linehighlight_style = styles['LINEHIGHLIGHT'] if language and language.upper() in ['PYTHON', 'C', 'CPP', 'HTML', 'WEB2PY']: code = Highlighter(language, link, styles).highlight(code) else: code = cgi.escape(code) lines = code.split('\n') if counter is None: linenumbers = [''] * len(lines) elif isinstance(counter, str): linenumbers = [cgi.escape(counter)] * len(lines) else: linenumbers = [str(i + counter) + '.' for i in xrange(len(lines))] if highlight_line: if counter and not isinstance(counter, str): lineno = highlight_line - counter else: lineno = highlight_line if lineno<len(lines): lines[lineno] = '<div style="%s">%s</div>' % (linehighlight_style, lines[lineno]) linenumbers[lineno] = '<div style="%s">%s</div>' % (linehighlight_style, linenumbers[lineno]) code = '<br/>'.join(lines) numbers = '<br/>'.join(linenumbers) items = attributes.items() fa = ' '.join([key[1:].lower() for (key, value) in items if key[:1] == '_' and value == None] + ['%s="%s"' % (key[1:].lower(), str(value).replace('"', "'")) for (key, value) in attributes.items() if key[:1] == '_' and value]) if fa: fa = ' ' + fa return '<table%s><tr valign="top"><td style="width:40px; text-align: right;"><pre style="%s">%s</pre></td><td><pre style="%s">%s</pre></td></tr></table>'\ % (fa, linenumbers_style, numbers, code_style, code) if __name__ == '__main__': import sys argfp = open(sys.argv[1]) data = argfp.read() argfp.close() print '<html><body>' + highlight(data, sys.argv[2])\ + '</body></html>'
Python
""" This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) Utility functions for the Admin application =========================================== """ import os import sys import traceback import zipfile import urllib from shutil import rmtree from utils import web2py_uuid from fileutils import w2p_pack, w2p_unpack, w2p_pack_plugin, w2p_unpack_plugin from fileutils import up, fix_newlines, abspath, recursive_unlink from fileutils import read_file, write_file from restricted import RestrictedError from settings import global_settings def apath(path='', r=None): """ Builds a path inside an application folder Parameters ---------- path: path within the application folder r: the global request object """ opath = up(r.folder) while path[:3] == '../': (opath, path) = (up(opath), path[3:]) return os.path.join(opath, path).replace('\\', '/') def app_pack(app, request): """ Builds a w2p package for the application Parameters ---------- app: application name request: the global request object Returns ------- filename: filename of the w2p file or None on error """ try: app_cleanup(app, request) filename = apath('../deposit/%s.w2p' % app, request) w2p_pack(filename, apath(app, request)) return filename except Exception: return False def app_pack_compiled(app, request): """ Builds a w2p bytecode-compiled package for the application Parameters ---------- app: application name request: the global request object Returns ------- filename: filename of the w2p file or None on error """ try: filename = apath('../deposit/%s.w2p' % app, request) w2p_pack(filename, apath(app, request), compiled=True) return filename except Exception: return None def app_cleanup(app, request): """ Removes session, cache and error files Parameters ---------- app: application name request: the global request object """ r = True # Remove error files path = apath('%s/errors/' % app, request) if os.path.exists(path): for f in os.listdir(path): try: if f[:1]!='.': os.unlink(os.path.join(path,f)) except IOError: r = False # Remove session files path = apath('%s/sessions/' % app, request) if os.path.exists(path): for f in os.listdir(path): try: if f[:1]!='.': recursive_unlink(os.path.join(path,f)) except IOError: r = False # Remove cache files path = apath('%s/sessions/' % app, request) if os.path.exists(path): for f in os.listdir(path): try: if f[:1]!='.': os.unlink(os.path.join(path,f)) except IOError: r = False return r def app_compile(app, request): """ Compiles the application Parameters ---------- app: application name request: the global request object """ from compileapp import compile_application, remove_compiled_application folder = apath(app, request) try: compile_application(folder) return None except (Exception, RestrictedError): tb = traceback.format_exc(sys.exc_info) remove_compiled_application(folder) return tb def app_create(app, request,force=False,key=None): """ Create a copy of welcome.w2p (scaffolding) app Parameters ---------- app: application name request: the global request object """ try: path = apath(app, request) os.mkdir(path) except: if not force: return False try: w2p_unpack('welcome.w2p', path) for subfolder in ['models','views','controllers', 'databases', 'modules','cron','errors','sessions', 'languages','static','private','uploads']: subpath = os.path.join(path,subfolder) if not os.path.exists(subpath): os.mkdir(subpath) db = os.path.join(path, 'models', 'db.py') if os.path.exists(db): data = read_file(db) data = data.replace('<your secret key>', 'sha512:'+(key or web2py_uuid())) write_file(db, data) return True except: rmtree(path) return False def app_install(app, fobj, request, filename, overwrite=None): """ Installs an application: - Identifies file type by filename - Writes `fobj` contents to the `../deposit/` folder - Calls `w2p_unpack()` to do the job. Parameters ---------- app: new application name fobj: file object containing the application to be installed request: the global request object filename: original filename of the `fobj`, required to determine extension Returns ------- upname: name of the file where app is temporarily stored or `None` on failure """ did_mkdir = False if filename[-4:] == '.w2p': extension = 'w2p' elif filename[-7:] == '.tar.gz': extension = 'tar.gz' else: extension = 'tar' upname = apath('../deposit/%s.%s' % (app, extension), request) try: write_file(upname, fobj.read(), 'wb') path = apath(app, request) if not overwrite: os.mkdir(path) did_mkdir = True w2p_unpack(upname, path) if extension != 'tar': os.unlink(upname) fix_newlines(path) return upname except Exception: if did_mkdir: rmtree(path) return False def app_uninstall(app, request): """ Uninstalls the application. Parameters ---------- app: application name request: the global request object Returns ------- `True` on success, `False` on failure """ try: # Hey App, this is your end... path = apath(app, request) rmtree(path) return True except Exception: return False def plugin_pack(app, plugin_name, request): """ Builds a w2p package for the application Parameters ---------- app: application name plugin_name: the name of the plugin without plugin_ prefix request: the current request app Returns ------- filename: filename of the w2p file or None on error """ try: filename = apath('../deposit/web2py.plugin.%s.w2p' % plugin_name, request) w2p_pack_plugin(filename, apath(app, request), plugin_name) return filename except Exception: return False def plugin_install(app, fobj, request, filename): """ Installs an application: - Identifies file type by filename - Writes `fobj` contents to the `../deposit/` folder - Calls `w2p_unpack()` to do the job. Parameters ---------- app: new application name fobj: file object containing the application to be installed request: the global request object filename: original filename of the `fobj`, required to determine extension Returns ------- upname: name of the file where app is temporarily stored or `None` on failure """ upname = apath('../deposit/%s' % filename, request) try: write_file(upname, fobj.read(), 'wb') path = apath(app, request) w2p_unpack_plugin(upname, path) fix_newlines(path) return upname except Exception: os.unlink(upname) return False def check_new_version(myversion, version_URL): """ Compares current web2py's version with the latest stable web2py version. Parameters ---------- myversion: the current version as stored in file `web2py/VERSION` version_URL: the URL that contains the version of the latest stable release Returns ------- state: `True` if upgrade available, `False` if current version if up-to-date, -1 on error version: the most up-to-version available """ try: from urllib import urlopen version = urlopen(version_URL).read() except Exception: return -1, myversion if version > myversion: return True, version else: return False, version def unzip(filename, dir, subfolder=''): """ Unzips filename into dir (.zip only, no .gz etc) if subfolder!='' it unzip only files in subfolder """ filename = abspath(filename) if not zipfile.is_zipfile(filename): raise RuntimeError, 'Not a valid zipfile' zf = zipfile.ZipFile(filename) if not subfolder.endswith('/'): subfolder = subfolder + '/' n = len(subfolder) for name in sorted(zf.namelist()): if not name.startswith(subfolder): continue #print name[n:] if name.endswith('/'): folder = os.path.join(dir,name[n:]) if not os.path.exists(folder): os.mkdir(folder) else: write_file(os.path.join(dir, name[n:]), zf.read(name), 'wb') def upgrade(request, url='http://web2py.com'): """ Upgrades web2py (src, osx, win) is a new version is posted. It detects whether src, osx or win is running and downloads the right one Parameters ---------- request: the current request object, required to determine version and path url: the incomplete url where to locate the latest web2py actual url is url+'/examples/static/web2py_(src|osx|win).zip' Returns ------- True on success, False on failure (network problem or old version) """ web2py_version = request.env.web2py_version gluon_parent = request.env.gluon_parent if not gluon_parent.endswith('/'): gluon_parent = gluon_parent + '/' (check, version) = check_new_version(web2py_version, url+'/examples/default/version') if not check: return (False, 'Already latest version') if os.path.exists(os.path.join(gluon_parent, 'web2py.exe')): version_type = 'win' destination = gluon_parent subfolder = 'web2py/' elif gluon_parent.endswith('/Contents/Resources/'): version_type = 'osx' destination = gluon_parent[:-len('/Contents/Resources/')] subfolder = 'web2py/web2py.app/' else: version_type = 'src' destination = gluon_parent subfolder = 'web2py/' full_url = url + '/examples/static/web2py_%s.zip' % version_type filename = abspath('web2py_%s_downloaded.zip' % version_type) file = None try: write_file(filename, urllib.urlopen(full_url).read(), 'wb') except Exception,e: return False, e try: unzip(filename, destination, subfolder) return True, None except Exception,e: return False, e def add_path_first(path): sys.path = [path]+[p for p in sys.path if (not p==path and not p==(path+'/'))] def create_missing_folders(): if not global_settings.web2py_runtime_gae: for path in ('applications', 'deposit', 'site-packages', 'logs'): path = abspath(path, gluon=True) if not os.path.exists(path): os.mkdir(path) paths = (global_settings.gluon_parent, abspath('site-packages', gluon=True), abspath('gluon', gluon=True), '') [add_path_first(path) for path in paths] def create_missing_app_folders(request): if not global_settings.web2py_runtime_gae: if request.folder not in global_settings.app_folders: for subfolder in ('models', 'views', 'controllers', 'databases', 'modules', 'cron', 'errors', 'sessions', 'languages', 'static', 'private', 'uploads'): path = os.path.join(request.folder, subfolder) if not os.path.exists(path): os.mkdir(path) global_settings.app_folders.add(request.folder)
Python
#!/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) Thanks to ga2arch for help with IS_IN_DB and IS_NOT_IN_DB on GAE """ import os import re import datetime import time import cgi import urllib import struct import decimal import unicodedata from cStringIO import StringIO from utils import simple_hash, hmac_hash __all__ = [ 'CLEANUP', 'CRYPT', 'IS_ALPHANUMERIC', 'IS_DATE_IN_RANGE', 'IS_DATE', 'IS_DATETIME_IN_RANGE', 'IS_DATETIME', 'IS_DECIMAL_IN_RANGE', 'IS_EMAIL', 'IS_EMPTY_OR', 'IS_EXPR', 'IS_FLOAT_IN_RANGE', 'IS_IMAGE', 'IS_IN_DB', 'IS_IN_SET', 'IS_INT_IN_RANGE', 'IS_IPV4', 'IS_LENGTH', 'IS_LIST_OF', 'IS_LOWER', 'IS_MATCH', 'IS_EQUAL_TO', 'IS_NOT_EMPTY', 'IS_NOT_IN_DB', 'IS_NULL_OR', 'IS_SLUG', 'IS_STRONG', 'IS_TIME', 'IS_UPLOAD_FILENAME', 'IS_UPPER', 'IS_URL', ] def translate(text): if isinstance(text,(str,unicode)): from globals import current if hasattr(current,'T'): return current.T(text) return text def options_sorter(x,y): return (str(x[1]).upper()>str(y[1]).upper() and 1) or -1 class Validator(object): """ Root for all validators, mainly for documentation purposes. Validators are classes used to validate input fields (including forms generated from database tables). Here is an example of using a validator with a FORM:: INPUT(_name='a', requires=IS_INT_IN_RANGE(0, 10)) Here is an example of how to require a validator for a table field:: db.define_table('person', SQLField('name')) db.person.name.requires=IS_NOT_EMPTY() Validators are always assigned using the requires attribute of a field. A field can have a single validator or multiple validators. Multiple validators are made part of a list:: db.person.name.requires=[IS_NOT_EMPTY(), IS_NOT_IN_DB(db, 'person.id')] Validators are called by the function accepts on a FORM or other HTML helper object that contains a form. They are always called in the order in which they are listed. Built-in validators have constructors that take the optional argument error message which allows you to change the default error message. Here is an example of a validator on a database table:: db.person.name.requires=IS_NOT_EMPTY(error_message=T('fill this')) where we have used the translation operator T to allow for internationalization. Notice that default error messages are not translated. """ def formatter(self, value): """ For some validators returns a formatted version (matching the validator) of value. Otherwise just returns the value. """ return value class IS_MATCH(Validator): """ example:: INPUT(_type='text', _name='name', requires=IS_MATCH('.+')) the argument of IS_MATCH is a regular expression:: >>> IS_MATCH('.+')('hello') ('hello', None) >>> IS_MATCH('.+')('') ('', 'invalid expression') """ def __init__(self, expression, error_message='invalid expression', strict=True): if strict: if not expression.endswith('$'): expression = '(%s)$' % expression self.regex = re.compile(expression) self.error_message = error_message def __call__(self, value): match = self.regex.match(value) if match: return (match.group(), None) return (value, translate(self.error_message)) class IS_EQUAL_TO(Validator): """ example:: INPUT(_type='text', _name='password') INPUT(_type='text', _name='password2', requires=IS_EQUAL_TO(request.vars.password)) the argument of IS_EQUAL_TO is a string >>> IS_EQUAL_TO('aaa')('aaa') ('aaa', None) >>> IS_EQUAL_TO('aaa')('aab') ('aab', 'no match') """ def __init__(self, expression, error_message='no match'): self.expression = expression self.error_message = error_message def __call__(self, value): if value == self.expression: return (value, None) return (value, translate(self.error_message)) class IS_EXPR(Validator): """ example:: INPUT(_type='text', _name='name', requires=IS_EXPR('5 < int(value) < 10')) the argument of IS_EXPR must be python condition:: >>> IS_EXPR('int(value) < 2')('1') ('1', None) >>> IS_EXPR('int(value) < 2')('2') ('2', 'invalid expression') """ def __init__(self, expression, error_message='invalid expression'): self.expression = expression self.error_message = error_message def __call__(self, value): environment = {'value': value} exec '__ret__=' + self.expression in environment if environment['__ret__']: return (value, None) return (value, translate(self.error_message)) class IS_LENGTH(Validator): """ Checks if length of field's value fits between given boundaries. Works for both text and file inputs. Arguments: maxsize: maximum allowed length / size minsize: minimum allowed length / size Examples:: #Check if text string is shorter than 33 characters: INPUT(_type='text', _name='name', requires=IS_LENGTH(32)) #Check if password string is longer than 5 characters: INPUT(_type='password', _name='name', requires=IS_LENGTH(minsize=6)) #Check if uploaded file has size between 1KB and 1MB: INPUT(_type='file', _name='name', requires=IS_LENGTH(1048576, 1024)) >>> IS_LENGTH()('') ('', None) >>> IS_LENGTH()('1234567890') ('1234567890', None) >>> IS_LENGTH(maxsize=5, minsize=0)('1234567890') # too long ('1234567890', 'enter from 0 to 5 characters') >>> IS_LENGTH(maxsize=50, minsize=20)('1234567890') # too short ('1234567890', 'enter from 20 to 50 characters') """ def __init__(self, maxsize=255, minsize=0, error_message='enter from %(min)g to %(max)g characters'): self.maxsize = maxsize self.minsize = minsize self.error_message = error_message def __call__(self, value): if isinstance(value, cgi.FieldStorage): if value.file: value.file.seek(0, os.SEEK_END) length = value.file.tell() value.file.seek(0, os.SEEK_SET) else: val = value.value if val: length = len(val) else: length = 0 if self.minsize <= length <= self.maxsize: return (value, None) elif isinstance(value, (str, unicode, list)): if self.minsize <= len(value) <= self.maxsize: return (value, None) elif self.minsize <= len(str(value)) <= self.maxsize: try: value.decode('utf8') return (value, None) except: pass return (value, translate(self.error_message) \ % dict(min=self.minsize, max=self.maxsize)) class IS_IN_SET(Validator): """ example:: INPUT(_type='text', _name='name', requires=IS_IN_SET(['max', 'john'],zero='')) the argument of IS_IN_SET must be a list or set >>> IS_IN_SET(['max', 'john'])('max') ('max', None) >>> IS_IN_SET(['max', 'john'])('massimo') ('massimo', 'value not allowed') >>> IS_IN_SET(['max', 'john'], multiple=True)(('max', 'john')) (('max', 'john'), None) >>> IS_IN_SET(['max', 'john'], multiple=True)(('bill', 'john')) (('bill', 'john'), 'value not allowed') >>> IS_IN_SET(('id1','id2'), ['first label','second label'])('id1') # Traditional way ('id1', None) >>> IS_IN_SET({'id1':'first label', 'id2':'second label'})('id1') ('id1', None) >>> import itertools >>> IS_IN_SET(itertools.chain(['1','3','5'],['2','4','6']))('1') ('1', None) >>> IS_IN_SET([('id1','first label'), ('id2','second label')])('id1') # Redundant way ('id1', None) """ def __init__( self, theset, labels=None, error_message='value not allowed', multiple=False, zero='', sort=False, ): self.multiple = multiple if isinstance(theset, dict): self.theset = [str(item) for item in theset] self.labels = theset.values() elif theset and isinstance(theset, (tuple,list)) \ and isinstance(theset[0], (tuple,list)) and len(theset[0])==2: self.theset = [str(item) for item,label in theset] self.labels = [str(label) for item,label in theset] else: self.theset = [str(item) for item in theset] self.labels = labels self.error_message = error_message self.zero = zero self.sort = sort def options(self,zero=True): if not self.labels: items = [(k, k) for (i, k) in enumerate(self.theset)] else: items = [(k, self.labels[i]) for (i, k) in enumerate(self.theset)] if self.sort: items.sort(options_sorter) if zero and self.zero != None and not self.multiple: items.insert(0,('',self.zero)) return items def __call__(self, value): if self.multiple: ### if below was values = re.compile("[\w\-:]+").findall(str(value)) if isinstance(value, (str,unicode)): values = [value] elif isinstance(value, (tuple, list)): values = value elif not value: values = [] else: values = [value] failures = [x for x in values if not x in self.theset] if failures and self.theset: if self.multiple and (value == None or value == ''): return ([], None) return (value, translate(self.error_message)) if self.multiple: if isinstance(self.multiple,(tuple,list)) and \ not self.multiple[0]<=len(values)<self.multiple[1]: return (values, translate(self.error_message)) return (values, None) return (value, None) regex1 = re.compile('[\w_]+\.[\w_]+') regex2 = re.compile('%\((?P<name>[^\)]+)\)s') class IS_IN_DB(Validator): """ example:: INPUT(_type='text', _name='name', requires=IS_IN_DB(db, db.mytable.myfield, zero='')) used for reference fields, rendered as a dropbox """ def __init__( self, dbset, field, label=None, error_message='value not in database', orderby=None, groupby=None, cache=None, multiple=False, zero='', sort=False, _and=None, ): from dal import Table if isinstance(field,Table): field = field._id if hasattr(dbset, 'define_table'): self.dbset = dbset() else: self.dbset = dbset self.field = field (ktable, kfield) = str(self.field).split('.') if not label: label = '%%(%s)s' % kfield if isinstance(label,str): if regex1.match(str(label)): label = '%%(%s)s' % str(label).split('.')[-1] ks = regex2.findall(label) if not kfield in ks: ks += [kfield] fields = ks else: ks = [kfield] fields = 'all' self.fields = fields self.label = label self.ktable = ktable self.kfield = kfield self.ks = ks self.error_message = error_message self.theset = None self.orderby = orderby self.groupby = groupby self.cache = cache self.multiple = multiple self.zero = zero self.sort = sort self._and = _and def set_self_id(self, id): if self._and: self._and.record_id = id def build_set(self): if self.fields == 'all': fields = [f for f in self.dbset.db[self.ktable]] else: fields = [self.dbset.db[self.ktable][k] for k in self.fields] if self.dbset.db._dbname != 'gae': orderby = self.orderby or reduce(lambda a,b:a|b,fields) groupby = self.groupby dd = dict(orderby=orderby, groupby=groupby, cache=self.cache) records = self.dbset.select(*fields, **dd) else: orderby = self.orderby or reduce(lambda a,b:a|b,(f for f in fields if not f.name=='id')) dd = dict(orderby=orderby, cache=self.cache) records = self.dbset.select(self.dbset.db[self.ktable].ALL, **dd) self.theset = [str(r[self.kfield]) for r in records] if isinstance(self.label,str): self.labels = [self.label % dict(r) for r in records] else: self.labels = [self.label(r) for r in records] def options(self, zero=True): self.build_set() items = [(k, self.labels[i]) for (i, k) in enumerate(self.theset)] if self.sort: items.sort(options_sorter) if zero and self.zero != None and not self.multiple: items.insert(0,('',self.zero)) return items def __call__(self, value): if self.multiple: if isinstance(value,list): values=value elif value: values = [value] else: values = [] if isinstance(self.multiple,(tuple,list)) and \ not self.multiple[0]<=len(values)<self.multiple[1]: return (values, translate(self.error_message)) if not [x for x in values if not x in self.theset]: return (values, None) elif self.theset: if value in self.theset: if self._and: return self._and(value) else: return (value, None) else: (ktable, kfield) = str(self.field).split('.') field = self.dbset.db[ktable][kfield] if self.dbset(field == value).count(): if self._and: return self._and(value) else: return (value, None) return (value, translate(self.error_message)) class IS_NOT_IN_DB(Validator): """ example:: INPUT(_type='text', _name='name', requires=IS_NOT_IN_DB(db, db.table)) makes the field unique """ def __init__( self, dbset, field, error_message='value already in database or empty', allowed_override=[], ): from dal import Table if isinstance(field,Table): field = field._id if hasattr(dbset, 'define_table'): self.dbset = dbset() else: self.dbset = dbset self.field = field self.error_message = error_message self.record_id = 0 self.allowed_override = allowed_override def set_self_id(self, id): self.record_id = id def __call__(self, value): value=str(value) if not value.strip(): return (value, translate(self.error_message)) if value in self.allowed_override: return (value, None) (tablename, fieldname) = str(self.field).split('.') field = self.dbset.db[tablename][fieldname] rows = self.dbset(field == value).select(limitby=(0, 1)) if len(rows) > 0: if isinstance(self.record_id, dict): for f in self.record_id: if str(getattr(rows[0], f)) != str(self.record_id[f]): return (value, translate(self.error_message)) elif str(rows[0].id) != str(self.record_id): return (value, translate(self.error_message)) return (value, None) class IS_INT_IN_RANGE(Validator): """ Determine that the argument is (or can be represented as) an int, and that it falls within the specified range. The range is interpreted in the Pythonic way, so the test is: min <= value < max. The minimum and maximum limits can be None, meaning no lower or upper limit, respectively. example:: INPUT(_type='text', _name='name', requires=IS_INT_IN_RANGE(0, 10)) >>> IS_INT_IN_RANGE(1,5)('4') (4, None) >>> IS_INT_IN_RANGE(1,5)(4) (4, None) >>> IS_INT_IN_RANGE(1,5)(1) (1, None) >>> IS_INT_IN_RANGE(1,5)(5) (5, 'enter an integer between 1 and 4') >>> IS_INT_IN_RANGE(1,5)(5) (5, 'enter an integer between 1 and 4') >>> IS_INT_IN_RANGE(1,5)(3.5) (3, 'enter an integer between 1 and 4') >>> IS_INT_IN_RANGE(None,5)('4') (4, None) >>> IS_INT_IN_RANGE(None,5)('6') (6, 'enter an integer less than or equal to 4') >>> IS_INT_IN_RANGE(1,None)('4') (4, None) >>> IS_INT_IN_RANGE(1,None)('0') (0, 'enter an integer greater than or equal to 1') >>> IS_INT_IN_RANGE()(6) (6, None) >>> IS_INT_IN_RANGE()('abc') ('abc', 'enter an integer') """ def __init__( self, minimum=None, maximum=None, error_message=None, ): self.minimum = self.maximum = None if minimum is None: if maximum is None: self.error_message = error_message or 'enter an integer' else: self.maximum = int(maximum) if error_message is None: error_message = 'enter an integer less than or equal to %(max)g' self.error_message = translate(error_message) % dict(max=self.maximum-1) elif maximum is None: self.minimum = int(minimum) if error_message is None: error_message = 'enter an integer greater than or equal to %(min)g' self.error_message = translate(error_message) % dict(min=self.minimum) else: self.minimum = int(minimum) self.maximum = int(maximum) if error_message is None: error_message = 'enter an integer between %(min)g and %(max)g' self.error_message = translate(error_message) \ % dict(min=self.minimum, max=self.maximum-1) def __call__(self, value): try: fvalue = float(value) value = int(value) if value != fvalue: return (value, self.error_message) if self.minimum is None: if self.maximum is None or value < self.maximum: return (value, None) elif self.maximum is None: if value >= self.minimum: return (value, None) elif self.minimum <= value < self.maximum: return (value, None) except ValueError: pass return (value, self.error_message) class IS_FLOAT_IN_RANGE(Validator): """ Determine that the argument is (or can be represented as) a float, and that it falls within the specified inclusive range. The comparison is made with native arithmetic. The minimum and maximum limits can be None, meaning no lower or upper limit, respectively. example:: INPUT(_type='text', _name='name', requires=IS_FLOAT_IN_RANGE(0, 10)) >>> IS_FLOAT_IN_RANGE(1,5)('4') (4.0, None) >>> IS_FLOAT_IN_RANGE(1,5)(4) (4.0, None) >>> IS_FLOAT_IN_RANGE(1,5)(1) (1.0, None) >>> IS_FLOAT_IN_RANGE(1,5)(5.25) (5.25, 'enter a number between 1 and 5') >>> IS_FLOAT_IN_RANGE(1,5)(6.0) (6.0, 'enter a number between 1 and 5') >>> IS_FLOAT_IN_RANGE(1,5)(3.5) (3.5, None) >>> IS_FLOAT_IN_RANGE(1,None)(3.5) (3.5, None) >>> IS_FLOAT_IN_RANGE(None,5)(3.5) (3.5, None) >>> IS_FLOAT_IN_RANGE(1,None)(0.5) (0.5, 'enter a number greater than or equal to 1') >>> IS_FLOAT_IN_RANGE(None,5)(6.5) (6.5, 'enter a number less than or equal to 5') >>> IS_FLOAT_IN_RANGE()(6.5) (6.5, None) >>> IS_FLOAT_IN_RANGE()('abc') ('abc', 'enter a number') """ def __init__( self, minimum=None, maximum=None, error_message=None, dot='.' ): self.minimum = self.maximum = None self.dot = dot if minimum is None: if maximum is None: if error_message is None: error_message = 'enter a number' else: self.maximum = float(maximum) if error_message is None: error_message = 'enter a number less than or equal to %(max)g' elif maximum is None: self.minimum = float(minimum) if error_message is None: error_message = 'enter a number greater than or equal to %(min)g' else: self.minimum = float(minimum) self.maximum = float(maximum) if error_message is None: error_message = 'enter a number between %(min)g and %(max)g' self.error_message = translate(error_message) \ % dict(min=self.minimum, max=self.maximum) def __call__(self, value): try: if self.dot=='.': fvalue = float(value) else: fvalue = float(str(value).replace(self.dot,'.')) if self.minimum is None: if self.maximum is None or fvalue <= self.maximum: return (fvalue, None) elif self.maximum is None: if fvalue >= self.minimum: return (fvalue, None) elif self.minimum <= fvalue <= self.maximum: return (fvalue, None) except (ValueError, TypeError): pass return (value, self.error_message) def formatter(self,value): if self.dot=='.': return str(value) else: return str(value).replace('.',self.dot) class IS_DECIMAL_IN_RANGE(Validator): """ Determine that the argument is (or can be represented as) a Python Decimal, and that it falls within the specified inclusive range. The comparison is made with Python Decimal arithmetic. The minimum and maximum limits can be None, meaning no lower or upper limit, respectively. example:: INPUT(_type='text', _name='name', requires=IS_DECIMAL_IN_RANGE(0, 10)) >>> IS_DECIMAL_IN_RANGE(1,5)('4') (Decimal('4'), None) >>> IS_DECIMAL_IN_RANGE(1,5)(4) (Decimal('4'), None) >>> IS_DECIMAL_IN_RANGE(1,5)(1) (Decimal('1'), None) >>> IS_DECIMAL_IN_RANGE(1,5)(5.25) (5.25, 'enter a number between 1 and 5') >>> IS_DECIMAL_IN_RANGE(5.25,6)(5.25) (Decimal('5.25'), None) >>> IS_DECIMAL_IN_RANGE(5.25,6)('5.25') (Decimal('5.25'), None) >>> IS_DECIMAL_IN_RANGE(1,5)(6.0) (6.0, 'enter a number between 1 and 5') >>> IS_DECIMAL_IN_RANGE(1,5)(3.5) (Decimal('3.5'), None) >>> IS_DECIMAL_IN_RANGE(1.5,5.5)(3.5) (Decimal('3.5'), None) >>> IS_DECIMAL_IN_RANGE(1.5,5.5)(6.5) (6.5, 'enter a number between 1.5 and 5.5') >>> IS_DECIMAL_IN_RANGE(1.5,None)(6.5) (Decimal('6.5'), None) >>> IS_DECIMAL_IN_RANGE(1.5,None)(0.5) (0.5, 'enter a number greater than or equal to 1.5') >>> IS_DECIMAL_IN_RANGE(None,5.5)(4.5) (Decimal('4.5'), None) >>> IS_DECIMAL_IN_RANGE(None,5.5)(6.5) (6.5, 'enter a number less than or equal to 5.5') >>> IS_DECIMAL_IN_RANGE()(6.5) (Decimal('6.5'), None) >>> IS_DECIMAL_IN_RANGE(0,99)(123.123) (123.123, 'enter a number between 0 and 99') >>> IS_DECIMAL_IN_RANGE(0,99)('123.123') ('123.123', 'enter a number between 0 and 99') >>> IS_DECIMAL_IN_RANGE(0,99)('12.34') (Decimal('12.34'), None) >>> IS_DECIMAL_IN_RANGE()('abc') ('abc', 'enter a decimal number') """ def __init__( self, minimum=None, maximum=None, error_message=None, dot='.' ): self.minimum = self.maximum = None self.dot = dot if minimum is None: if maximum is None: if error_message is None: error_message = 'enter a decimal number' else: self.maximum = decimal.Decimal(str(maximum)) if error_message is None: error_message = 'enter a number less than or equal to %(max)g' elif maximum is None: self.minimum = decimal.Decimal(str(minimum)) if error_message is None: error_message = 'enter a number greater than or equal to %(min)g' else: self.minimum = decimal.Decimal(str(minimum)) self.maximum = decimal.Decimal(str(maximum)) if error_message is None: error_message = 'enter a number between %(min)g and %(max)g' self.error_message = translate(error_message) \ % dict(min=self.minimum, max=self.maximum) def __call__(self, value): try: if isinstance(value,decimal.Decimal): v = value else: v = decimal.Decimal(str(value).replace(self.dot,'.')) if self.minimum is None: if self.maximum is None or v <= self.maximum: return (v, None) elif self.maximum is None: if v >= self.minimum: return (v, None) elif self.minimum <= v <= self.maximum: return (v, None) except (ValueError, TypeError, decimal.InvalidOperation): pass return (value, self.error_message) def formatter(self, value): return str(value).replace('.',self.dot) def is_empty(value, empty_regex=None): "test empty field" if isinstance(value, (str, unicode)): value = value.strip() if empty_regex is not None and empty_regex.match(value): value = '' if value == None or value == '' or value == []: return (value, True) return (value, False) class IS_NOT_EMPTY(Validator): """ example:: INPUT(_type='text', _name='name', requires=IS_NOT_EMPTY()) >>> IS_NOT_EMPTY()(1) (1, None) >>> IS_NOT_EMPTY()(0) (0, None) >>> IS_NOT_EMPTY()('x') ('x', None) >>> IS_NOT_EMPTY()(' x ') ('x', None) >>> IS_NOT_EMPTY()(None) (None, 'enter a value') >>> IS_NOT_EMPTY()('') ('', 'enter a value') >>> IS_NOT_EMPTY()(' ') ('', 'enter a value') >>> IS_NOT_EMPTY()(' \\n\\t') ('', 'enter a value') >>> IS_NOT_EMPTY()([]) ([], 'enter a value') >>> IS_NOT_EMPTY(empty_regex='def')('def') ('', 'enter a value') >>> IS_NOT_EMPTY(empty_regex='de[fg]')('deg') ('', 'enter a value') >>> IS_NOT_EMPTY(empty_regex='def')('abc') ('abc', None) """ def __init__(self, error_message='enter a value', empty_regex=None): self.error_message = error_message if empty_regex is not None: self.empty_regex = re.compile(empty_regex) else: self.empty_regex = None def __call__(self, value): value, empty = is_empty(value, empty_regex=self.empty_regex) if empty: return (value, translate(self.error_message)) return (value, None) class IS_ALPHANUMERIC(IS_MATCH): """ example:: INPUT(_type='text', _name='name', requires=IS_ALPHANUMERIC()) >>> IS_ALPHANUMERIC()('1') ('1', None) >>> IS_ALPHANUMERIC()('') ('', None) >>> IS_ALPHANUMERIC()('A_a') ('A_a', None) >>> IS_ALPHANUMERIC()('!') ('!', 'enter only letters, numbers, and underscore') """ def __init__(self, error_message='enter only letters, numbers, and underscore'): IS_MATCH.__init__(self, '^[\w]*$', error_message) class IS_EMAIL(Validator): """ Checks if field's value is a valid email address. Can be set to disallow or force addresses from certain domain(s). Email regex adapted from http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx, generally following the RFCs, except that we disallow quoted strings and permit underscores and leading numerics in subdomain labels Arguments: - banned: regex text for disallowed address domains - forced: regex text for required address domains Both arguments can also be custom objects with a match(value) method. Examples:: #Check for valid email address: INPUT(_type='text', _name='name', requires=IS_EMAIL()) #Check for valid email address that can't be from a .com domain: INPUT(_type='text', _name='name', requires=IS_EMAIL(banned='^.*\.com(|\..*)$')) #Check for valid email address that must be from a .edu domain: INPUT(_type='text', _name='name', requires=IS_EMAIL(forced='^.*\.edu(|\..*)$')) >>> IS_EMAIL()('a@b.com') ('a@b.com', None) >>> IS_EMAIL()('abc@def.com') ('abc@def.com', None) >>> IS_EMAIL()('abc@3def.com') ('abc@3def.com', None) >>> IS_EMAIL()('abc@def.us') ('abc@def.us', None) >>> IS_EMAIL()('abc@d_-f.us') ('abc@d_-f.us', None) >>> IS_EMAIL()('@def.com') # missing name ('@def.com', 'enter a valid email address') >>> IS_EMAIL()('"abc@def".com') # quoted name ('"abc@def".com', 'enter a valid email address') >>> IS_EMAIL()('abc+def.com') # no @ ('abc+def.com', 'enter a valid email address') >>> IS_EMAIL()('abc@def.x') # one-char TLD ('abc@def.x', 'enter a valid email address') >>> IS_EMAIL()('abc@def.12') # numeric TLD ('abc@def.12', 'enter a valid email address') >>> IS_EMAIL()('abc@def..com') # double-dot in domain ('abc@def..com', 'enter a valid email address') >>> IS_EMAIL()('abc@.def.com') # dot starts domain ('abc@.def.com', 'enter a valid email address') >>> IS_EMAIL()('abc@def.c_m') # underscore in TLD ('abc@def.c_m', 'enter a valid email address') >>> IS_EMAIL()('NotAnEmail') # missing @ ('NotAnEmail', 'enter a valid email address') >>> IS_EMAIL()('abc@NotAnEmail') # missing TLD ('abc@NotAnEmail', 'enter a valid email address') >>> IS_EMAIL()('customer/department@example.com') ('customer/department@example.com', None) >>> IS_EMAIL()('$A12345@example.com') ('$A12345@example.com', None) >>> IS_EMAIL()('!def!xyz%abc@example.com') ('!def!xyz%abc@example.com', None) >>> IS_EMAIL()('_Yosemite.Sam@example.com') ('_Yosemite.Sam@example.com', None) >>> IS_EMAIL()('~@example.com') ('~@example.com', None) >>> IS_EMAIL()('.wooly@example.com') # dot starts name ('.wooly@example.com', 'enter a valid email address') >>> IS_EMAIL()('wo..oly@example.com') # adjacent dots in name ('wo..oly@example.com', 'enter a valid email address') >>> IS_EMAIL()('pootietang.@example.com') # dot ends name ('pootietang.@example.com', 'enter a valid email address') >>> IS_EMAIL()('.@example.com') # name is bare dot ('.@example.com', 'enter a valid email address') >>> IS_EMAIL()('Ima.Fool@example.com') ('Ima.Fool@example.com', None) >>> IS_EMAIL()('Ima Fool@example.com') # space in name ('Ima Fool@example.com', 'enter a valid email address') >>> IS_EMAIL()('localguy@localhost') # localhost as domain ('localguy@localhost', None) """ regex = re.compile(''' ^(?!\.) # name may not begin with a dot ( [-a-z0-9!\#$%&'*+/=?^_`{|}~] # all legal characters except dot | (?<!\.)\. # single dots only )+ (?<!\.) # name may not end with a dot @ ( localhost | ( [a-z0-9] # [sub]domain begins with alphanumeric ( [-\w]* # alphanumeric, underscore, dot, hyphen [a-z0-9] # ending alphanumeric )? \. # ending dot )+ [a-z]{2,} # TLD alpha-only )$ ''', re.VERBOSE|re.IGNORECASE) regex_proposed_but_failed = re.compile('^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$',re.VERBOSE|re.IGNORECASE) def __init__(self, banned=None, forced=None, error_message='enter a valid email address'): if isinstance(banned, str): banned = re.compile(banned) if isinstance(forced, str): forced = re.compile(forced) self.banned = banned self.forced = forced self.error_message = error_message def __call__(self, value): match = self.regex.match(value) if match: domain = value.split('@')[1] if (not self.banned or not self.banned.match(domain)) \ and (not self.forced or self.forced.match(domain)): return (value, None) return (value, translate(self.error_message)) # URL scheme source: # <http://en.wikipedia.org/wiki/URI_scheme> obtained on 2008-Nov-10 official_url_schemes = [ 'aaa', 'aaas', 'acap', 'cap', 'cid', 'crid', 'data', 'dav', 'dict', 'dns', 'fax', 'file', 'ftp', 'go', 'gopher', 'h323', 'http', 'https', 'icap', 'im', 'imap', 'info', 'ipp', 'iris', 'iris.beep', 'iris.xpc', 'iris.xpcs', 'iris.lws', 'ldap', 'mailto', 'mid', 'modem', 'msrp', 'msrps', 'mtqp', 'mupdate', 'news', 'nfs', 'nntp', 'opaquelocktoken', 'pop', 'pres', 'prospero', 'rtsp', 'service', 'shttp', 'sip', 'sips', 'snmp', 'soap.beep', 'soap.beeps', 'tag', 'tel', 'telnet', 'tftp', 'thismessage', 'tip', 'tv', 'urn', 'vemmi', 'wais', 'xmlrpc.beep', 'xmlrpc.beep', 'xmpp', 'z39.50r', 'z39.50s', ] unofficial_url_schemes = [ 'about', 'adiumxtra', 'aim', 'afp', 'aw', 'callto', 'chrome', 'cvs', 'ed2k', 'feed', 'fish', 'gg', 'gizmoproject', 'iax2', 'irc', 'ircs', 'itms', 'jar', 'javascript', 'keyparc', 'lastfm', 'ldaps', 'magnet', 'mms', 'msnim', 'mvn', 'notes', 'nsfw', 'psyc', 'paparazzi:http', 'rmi', 'rsync', 'secondlife', 'sgn', 'skype', 'ssh', 'sftp', 'smb', 'sms', 'soldat', 'steam', 'svn', 'teamspeak', 'unreal', 'ut2004', 'ventrilo', 'view-source', 'webcal', 'wyciwyg', 'xfire', 'xri', 'ymsgr', ] all_url_schemes = [None] + official_url_schemes + unofficial_url_schemes http_schemes = [None, 'http', 'https'] # This regex comes from RFC 2396, Appendix B. It's used to split a URL into # its component parts # Here are the regex groups that it extracts: # scheme = group(2) # authority = group(4) # path = group(5) # query = group(7) # fragment = group(9) url_split_regex = \ re.compile('^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?') # Defined in RFC 3490, Section 3.1, Requirement #1 # Use this regex to split the authority component of a unicode URL into # its component labels label_split_regex = re.compile(u'[\u002e\u3002\uff0e\uff61]') def escape_unicode(string): ''' Converts a unicode string into US-ASCII, using a simple conversion scheme. Each unicode character that does not have a US-ASCII equivalent is converted into a URL escaped form based on its hexadecimal value. For example, the unicode character '\u4e86' will become the string '%4e%86' :param string: unicode string, the unicode string to convert into an escaped US-ASCII form :returns: the US-ASCII escaped form of the inputted string :rtype: string @author: Jonathan Benn ''' returnValue = StringIO() for character in string: code = ord(character) if code > 0x7F: hexCode = hex(code) returnValue.write('%' + hexCode[2:4] + '%' + hexCode[4:6]) else: returnValue.write(character) return returnValue.getvalue() def unicode_to_ascii_authority(authority): ''' Follows the steps in RFC 3490, Section 4 to convert a unicode authority string into its ASCII equivalent. For example, u'www.Alliancefran\xe7aise.nu' will be converted into 'www.xn--alliancefranaise-npb.nu' :param authority: unicode string, the URL authority component to convert, e.g. u'www.Alliancefran\xe7aise.nu' :returns: the US-ASCII character equivalent to the inputed authority, e.g. 'www.xn--alliancefranaise-npb.nu' :rtype: string :raises Exception: if the function is not able to convert the inputed authority @author: Jonathan Benn ''' #RFC 3490, Section 4, Step 1 #The encodings.idna Python module assumes that AllowUnassigned == True #RFC 3490, Section 4, Step 2 labels = label_split_regex.split(authority) #RFC 3490, Section 4, Step 3 #The encodings.idna Python module assumes that UseSTD3ASCIIRules == False #RFC 3490, Section 4, Step 4 #We use the ToASCII operation because we are about to put the authority #into an IDN-unaware slot asciiLabels = [] try: import encodings.idna for label in labels: if label: asciiLabels.append(encodings.idna.ToASCII(label)) else: #encodings.idna.ToASCII does not accept an empty string, but #it is necessary for us to allow for empty labels so that we #don't modify the URL asciiLabels.append('') except: asciiLabels=[str(label) for label in labels] #RFC 3490, Section 4, Step 5 return str(reduce(lambda x, y: x + unichr(0x002E) + y, asciiLabels)) def unicode_to_ascii_url(url, prepend_scheme): ''' Converts the inputed unicode url into a US-ASCII equivalent. This function goes a little beyond RFC 3490, which is limited in scope to the domain name (authority) only. Here, the functionality is expanded to what was observed on Wikipedia on 2009-Jan-22: Component Can Use Unicode? --------- ---------------- scheme No authority Yes path Yes query Yes fragment No The authority component gets converted to punycode, but occurrences of unicode in other components get converted into a pair of URI escapes (we assume 4-byte unicode). E.g. the unicode character U+4E2D will be converted into '%4E%2D'. Testing with Firefox v3.0.5 has shown that it can understand this kind of URI encoding. :param url: unicode string, the URL to convert from unicode into US-ASCII :param prepend_scheme: string, a protocol scheme to prepend to the URL if we're having trouble parsing it. e.g. "http". Input None to disable this functionality :returns: a US-ASCII equivalent of the inputed url :rtype: string @author: Jonathan Benn ''' #convert the authority component of the URL into an ASCII punycode string, #but encode the rest using the regular URI character encoding groups = url_split_regex.match(url).groups() #If no authority was found if not groups[3]: #Try appending a scheme to see if that fixes the problem scheme_to_prepend = prepend_scheme or 'http' groups = url_split_regex.match( unicode(scheme_to_prepend) + u'://' + url).groups() #if we still can't find the authority if not groups[3]: raise Exception('No authority component found, '+ \ 'could not decode unicode to US-ASCII') #We're here if we found an authority, let's rebuild the URL scheme = groups[1] authority = groups[3] path = groups[4] or '' query = groups[5] or '' fragment = groups[7] or '' if prepend_scheme: scheme = str(scheme) + '://' else: scheme = '' return scheme + unicode_to_ascii_authority(authority) +\ escape_unicode(path) + escape_unicode(query) + str(fragment) class IS_GENERIC_URL(Validator): """ Rejects a URL string if any of the following is true: * The string is empty or None * The string uses characters that are not allowed in a URL * The URL scheme specified (if one is specified) is not valid Based on RFC 2396: http://www.faqs.org/rfcs/rfc2396.html This function only checks the URL's syntax. It does not check that the URL points to a real document, for example, or that it otherwise makes sense semantically. This function does automatically prepend 'http://' in front of a URL if and only if that's necessary to successfully parse the URL. Please note that a scheme will be prepended only for rare cases (e.g. 'google.ca:80') The list of allowed schemes is customizable with the allowed_schemes parameter. If you exclude None from the list, then abbreviated URLs (lacking a scheme such as 'http') will be rejected. The default prepended scheme is customizable with the prepend_scheme parameter. If you set prepend_scheme to None then prepending will be disabled. URLs that require prepending to parse will still be accepted, but the return value will not be modified. @author: Jonathan Benn >>> IS_GENERIC_URL()('http://user@abc.com') ('http://user@abc.com', None) """ def __init__( self, error_message='enter a valid URL', allowed_schemes=None, prepend_scheme=None, ): """ :param error_message: a string, the error message to give the end user if the URL does not validate :param allowed_schemes: a list containing strings or None. Each element is a scheme the inputed URL is allowed to use :param prepend_scheme: a string, this scheme is prepended if it's necessary to make the URL valid """ self.error_message = error_message if allowed_schemes == None: self.allowed_schemes = all_url_schemes else: self.allowed_schemes = allowed_schemes self.prepend_scheme = prepend_scheme if self.prepend_scheme not in self.allowed_schemes: raise SyntaxError, \ "prepend_scheme='%s' is not in allowed_schemes=%s" \ % (self.prepend_scheme, self.allowed_schemes) def __call__(self, value): """ :param value: a string, the URL to validate :returns: a tuple, where tuple[0] is the inputed value (possible prepended with prepend_scheme), and tuple[1] is either None (success!) or the string error_message """ try: # if the URL does not misuse the '%' character if not re.compile( r"%[^0-9A-Fa-f]{2}|%[^0-9A-Fa-f][0-9A-Fa-f]|%[0-9A-Fa-f][^0-9A-Fa-f]|%$|%[0-9A-Fa-f]$|%[^0-9A-Fa-f]$" ).search(value): # if the URL is only composed of valid characters if re.compile( r"[A-Za-z0-9;/?:@&=+$,\-_\.!~*'\(\)%#]+$").match(value): # Then split up the URL into its components and check on # the scheme scheme = url_split_regex.match(value).group(2) # Clean up the scheme before we check it if scheme != None: scheme = urllib.unquote(scheme).lower() # If the scheme really exists if scheme in self.allowed_schemes: # Then the URL is valid return (value, None) else: # else, for the possible case of abbreviated URLs with # ports, check to see if adding a valid scheme fixes # the problem (but only do this if it doesn't have # one already!) if not re.compile('://').search(value) and None\ in self.allowed_schemes: schemeToUse = self.prepend_scheme or 'http' prependTest = self.__call__(schemeToUse + '://' + value) # if the prepend test succeeded if prependTest[1] == None: # if prepending in the output is enabled if self.prepend_scheme: return prependTest else: # else return the original, # non-prepended value return (value, None) except: pass # else the URL is not valid return (value, translate(self.error_message)) # Sources (obtained 2008-Nov-11): # http://en.wikipedia.org/wiki/Top-level_domain # http://www.iana.org/domains/root/db/ official_top_level_domains = [ 'ac', 'ad', 'ae', 'aero', 'af', 'ag', 'ai', 'al', 'am', 'an', 'ao', 'aq', 'ar', 'arpa', 'as', 'asia', 'at', 'au', 'aw', 'ax', 'az', 'ba', 'bb', 'bd', 'be', 'bf', 'bg', 'bh', 'bi', 'biz', 'bj', 'bl', 'bm', 'bn', 'bo', 'br', 'bs', 'bt', 'bv', 'bw', 'by', 'bz', 'ca', 'cat', 'cc', 'cd', 'cf', 'cg', 'ch', 'ci', 'ck', 'cl', 'cm', 'cn', 'co', 'com', 'coop', 'cr', 'cu', 'cv', 'cx', 'cy', 'cz', 'de', 'dj', 'dk', 'dm', 'do', 'dz', 'ec', 'edu', 'ee', 'eg', 'eh', 'er', 'es', 'et', 'eu', 'example', 'fi', 'fj', 'fk', 'fm', 'fo', 'fr', 'ga', 'gb', 'gd', 'ge', 'gf', 'gg', 'gh', 'gi', 'gl', 'gm', 'gn', 'gov', 'gp', 'gq', 'gr', 'gs', 'gt', 'gu', 'gw', 'gy', 'hk', 'hm', 'hn', 'hr', 'ht', 'hu', 'id', 'ie', 'il', 'im', 'in', 'info', 'int', 'invalid', 'io', 'iq', 'ir', 'is', 'it', 'je', 'jm', 'jo', 'jobs', 'jp', 'ke', 'kg', 'kh', 'ki', 'km', 'kn', 'kp', 'kr', 'kw', 'ky', 'kz', 'la', 'lb', 'lc', 'li', 'lk', 'localhost', 'lr', 'ls', 'lt', 'lu', 'lv', 'ly', 'ma', 'mc', 'md', 'me', 'mf', 'mg', 'mh', 'mil', 'mk', 'ml', 'mm', 'mn', 'mo', 'mobi', 'mp', 'mq', 'mr', 'ms', 'mt', 'mu', 'museum', 'mv', 'mw', 'mx', 'my', 'mz', 'na', 'name', 'nc', 'ne', 'net', 'nf', 'ng', 'ni', 'nl', 'no', 'np', 'nr', 'nu', 'nz', 'om', 'org', 'pa', 'pe', 'pf', 'pg', 'ph', 'pk', 'pl', 'pm', 'pn', 'pr', 'pro', 'ps', 'pt', 'pw', 'py', 'qa', 're', 'ro', 'rs', 'ru', 'rw', 'sa', 'sb', 'sc', 'sd', 'se', 'sg', 'sh', 'si', 'sj', 'sk', 'sl', 'sm', 'sn', 'so', 'sr', 'st', 'su', 'sv', 'sy', 'sz', 'tc', 'td', 'tel', 'test', 'tf', 'tg', 'th', 'tj', 'tk', 'tl', 'tm', 'tn', 'to', 'tp', 'tr', 'travel', 'tt', 'tv', 'tw', 'tz', 'ua', 'ug', 'uk', 'um', 'us', 'uy', 'uz', 'va', 'vc', 've', 'vg', 'vi', 'vn', 'vu', 'wf', 'ws', 'xn--0zwm56d', 'xn--11b5bs3a9aj6g', 'xn--80akhbyknj4f', 'xn--9t4b11yi5a', 'xn--deba0ad', 'xn--g6w251d', 'xn--hgbk6aj7f53bba', 'xn--hlcj6aya9esc7a', 'xn--jxalpdlp', 'xn--kgbechtv', 'xn--zckzah', 'ye', 'yt', 'yu', 'za', 'zm', 'zw', ] class IS_HTTP_URL(Validator): """ Rejects a URL string if any of the following is true: * The string is empty or None * The string uses characters that are not allowed in a URL * The string breaks any of the HTTP syntactic rules * The URL scheme specified (if one is specified) is not 'http' or 'https' * The top-level domain (if a host name is specified) does not exist Based on RFC 2616: http://www.faqs.org/rfcs/rfc2616.html This function only checks the URL's syntax. It does not check that the URL points to a real document, for example, or that it otherwise makes sense semantically. This function does automatically prepend 'http://' in front of a URL in the case of an abbreviated URL (e.g. 'google.ca'). The list of allowed schemes is customizable with the allowed_schemes parameter. If you exclude None from the list, then abbreviated URLs (lacking a scheme such as 'http') will be rejected. The default prepended scheme is customizable with the prepend_scheme parameter. If you set prepend_scheme to None then prepending will be disabled. URLs that require prepending to parse will still be accepted, but the return value will not be modified. @author: Jonathan Benn >>> IS_HTTP_URL()('http://1.2.3.4') ('http://1.2.3.4', None) >>> IS_HTTP_URL()('http://abc.com') ('http://abc.com', None) >>> IS_HTTP_URL()('https://abc.com') ('https://abc.com', None) >>> IS_HTTP_URL()('httpx://abc.com') ('httpx://abc.com', 'enter a valid URL') >>> IS_HTTP_URL()('http://abc.com:80') ('http://abc.com:80', None) >>> IS_HTTP_URL()('http://user@abc.com') ('http://user@abc.com', None) >>> IS_HTTP_URL()('http://user@1.2.3.4') ('http://user@1.2.3.4', None) """ def __init__( self, error_message='enter a valid URL', allowed_schemes=None, prepend_scheme='http', ): """ :param error_message: a string, the error message to give the end user if the URL does not validate :param allowed_schemes: a list containing strings or None. Each element is a scheme the inputed URL is allowed to use :param prepend_scheme: a string, this scheme is prepended if it's necessary to make the URL valid """ self.error_message = error_message if allowed_schemes == None: self.allowed_schemes = http_schemes else: self.allowed_schemes = allowed_schemes self.prepend_scheme = prepend_scheme for i in self.allowed_schemes: if i not in http_schemes: raise SyntaxError, \ "allowed_scheme value '%s' is not in %s" % \ (i, http_schemes) if self.prepend_scheme not in self.allowed_schemes: raise SyntaxError, \ "prepend_scheme='%s' is not in allowed_schemes=%s" % \ (self.prepend_scheme, self.allowed_schemes) def __call__(self, value): """ :param value: a string, the URL to validate :returns: a tuple, where tuple[0] is the inputed value (possible prepended with prepend_scheme), and tuple[1] is either None (success!) or the string error_message """ try: # if the URL passes generic validation x = IS_GENERIC_URL(error_message=self.error_message, allowed_schemes=self.allowed_schemes, prepend_scheme=self.prepend_scheme) if x(value)[1] == None: componentsMatch = url_split_regex.match(value) authority = componentsMatch.group(4) # if there is an authority component if authority: # if authority is a valid IP address if re.compile( "([\w.!~*'|;:&=+$,-]+@)?\d+\.\d+\.\d+\.\d+(:\d*)*$").match(authority): # Then this HTTP URL is valid return (value, None) else: # else if authority is a valid domain name domainMatch = \ re.compile( "([\w.!~*'|;:&=+$,-]+@)?(([A-Za-z0-9]+[A-Za-z0-9\-]*[A-Za-z0-9]+\.)*([A-Za-z0-9]+\.)*)*([A-Za-z]+[A-Za-z0-9\-]*[A-Za-z0-9]+)\.?(:\d*)*$" ).match(authority) if domainMatch: # if the top-level domain really exists if domainMatch.group(5).lower()\ in official_top_level_domains: # Then this HTTP URL is valid return (value, None) else: # else this is a relative/abbreviated URL, which will parse # into the URL's path component path = componentsMatch.group(5) # relative case: if this is a valid path (if it starts with # a slash) if re.compile('/').match(path): # Then this HTTP URL is valid return (value, None) else: # abbreviated case: if we haven't already, prepend a # scheme and see if it fixes the problem if not re.compile('://').search(value): schemeToUse = self.prepend_scheme or 'http' prependTest = self.__call__(schemeToUse + '://' + value) # if the prepend test succeeded if prependTest[1] == None: # if prepending in the output is enabled if self.prepend_scheme: return prependTest else: # else return the original, non-prepended # value return (value, None) except: pass # else the HTTP URL is not valid return (value, translate(self.error_message)) class IS_URL(Validator): """ Rejects a URL string if any of the following is true: * The string is empty or None * The string uses characters that are not allowed in a URL * The string breaks any of the HTTP syntactic rules * The URL scheme specified (if one is specified) is not 'http' or 'https' * The top-level domain (if a host name is specified) does not exist (These rules are based on RFC 2616: http://www.faqs.org/rfcs/rfc2616.html) This function only checks the URL's syntax. It does not check that the URL points to a real document, for example, or that it otherwise makes sense semantically. This function does automatically prepend 'http://' in front of a URL in the case of an abbreviated URL (e.g. 'google.ca'). If the parameter mode='generic' is used, then this function's behavior changes. It then rejects a URL string if any of the following is true: * The string is empty or None * The string uses characters that are not allowed in a URL * The URL scheme specified (if one is specified) is not valid (These rules are based on RFC 2396: http://www.faqs.org/rfcs/rfc2396.html) The list of allowed schemes is customizable with the allowed_schemes parameter. If you exclude None from the list, then abbreviated URLs (lacking a scheme such as 'http') will be rejected. The default prepended scheme is customizable with the prepend_scheme parameter. If you set prepend_scheme to None then prepending will be disabled. URLs that require prepending to parse will still be accepted, but the return value will not be modified. IS_URL is compatible with the Internationalized Domain Name (IDN) standard specified in RFC 3490 (http://tools.ietf.org/html/rfc3490). As a result, URLs can be regular strings or unicode strings. If the URL's domain component (e.g. google.ca) contains non-US-ASCII letters, then the domain will be converted into Punycode (defined in RFC 3492, http://tools.ietf.org/html/rfc3492). IS_URL goes a bit beyond the standards, and allows non-US-ASCII characters to be present in the path and query components of the URL as well. These non-US-ASCII characters will be escaped using the standard '%20' type syntax. e.g. the unicode character with hex code 0x4e86 will become '%4e%86' Code Examples:: INPUT(_type='text', _name='name', requires=IS_URL()) >>> IS_URL()('abc.com') ('http://abc.com', None) INPUT(_type='text', _name='name', requires=IS_URL(mode='generic')) >>> IS_URL(mode='generic')('abc.com') ('abc.com', None) INPUT(_type='text', _name='name', requires=IS_URL(allowed_schemes=['https'], prepend_scheme='https')) >>> IS_URL(allowed_schemes=['https'], prepend_scheme='https')('https://abc.com') ('https://abc.com', None) INPUT(_type='text', _name='name', requires=IS_URL(prepend_scheme='https')) >>> IS_URL(prepend_scheme='https')('abc.com') ('https://abc.com', None) INPUT(_type='text', _name='name', requires=IS_URL(mode='generic', allowed_schemes=['ftps', 'https'], prepend_scheme='https')) >>> IS_URL(mode='generic', allowed_schemes=['ftps', 'https'], prepend_scheme='https')('https://abc.com') ('https://abc.com', None) >>> IS_URL(mode='generic', allowed_schemes=['ftps', 'https', None], prepend_scheme='https')('abc.com') ('abc.com', None) @author: Jonathan Benn """ def __init__( self, error_message='enter a valid URL', mode='http', allowed_schemes=None, prepend_scheme='http', ): """ :param error_message: a string, the error message to give the end user if the URL does not validate :param allowed_schemes: a list containing strings or None. Each element is a scheme the inputed URL is allowed to use :param prepend_scheme: a string, this scheme is prepended if it's necessary to make the URL valid """ self.error_message = error_message self.mode = mode.lower() if not self.mode in ['generic', 'http']: raise SyntaxError, "invalid mode '%s' in IS_URL" % self.mode self.allowed_schemes = allowed_schemes if self.allowed_schemes: if prepend_scheme not in self.allowed_schemes: raise SyntaxError, \ "prepend_scheme='%s' is not in allowed_schemes=%s" \ % (prepend_scheme, self.allowed_schemes) # if allowed_schemes is None, then we will defer testing # prepend_scheme's validity to a sub-method self.prepend_scheme = prepend_scheme def __call__(self, value): """ :param value: a unicode or regular string, the URL to validate :returns: a (string, string) tuple, where tuple[0] is the modified input value and tuple[1] is either None (success!) or the string error_message. The input value will never be modified in the case of an error. However, if there is success then the input URL may be modified to (1) prepend a scheme, and/or (2) convert a non-compliant unicode URL into a compliant US-ASCII version. """ if self.mode == 'generic': subMethod = IS_GENERIC_URL(error_message=self.error_message, allowed_schemes=self.allowed_schemes, prepend_scheme=self.prepend_scheme) elif self.mode == 'http': subMethod = IS_HTTP_URL(error_message=self.error_message, allowed_schemes=self.allowed_schemes, prepend_scheme=self.prepend_scheme) else: raise SyntaxError, "invalid mode '%s' in IS_URL" % self.mode if type(value) != unicode: return subMethod(value) else: try: asciiValue = unicode_to_ascii_url(value, self.prepend_scheme) except Exception: #If we are not able to convert the unicode url into a # US-ASCII URL, then the URL is not valid return (value, translate(self.error_message)) methodResult = subMethod(asciiValue) #if the validation of the US-ASCII version of the value failed if methodResult[1] != None: # then return the original input value, not the US-ASCII version return (value, methodResult[1]) else: return methodResult regex_time = re.compile( '((?P<h>[0-9]+))([^0-9 ]+(?P<m>[0-9 ]+))?([^0-9ap ]+(?P<s>[0-9]*))?((?P<d>[ap]m))?') class IS_TIME(Validator): """ example:: INPUT(_type='text', _name='name', requires=IS_TIME()) understands the following formats hh:mm:ss [am/pm] hh:mm [am/pm] hh [am/pm] [am/pm] is optional, ':' can be replaced by any other non-space non-digit >>> IS_TIME()('21:30') (datetime.time(21, 30), None) >>> IS_TIME()('21-30') (datetime.time(21, 30), None) >>> IS_TIME()('21.30') (datetime.time(21, 30), None) >>> IS_TIME()('21:30:59') (datetime.time(21, 30, 59), None) >>> IS_TIME()('5:30') (datetime.time(5, 30), None) >>> IS_TIME()('5:30 am') (datetime.time(5, 30), None) >>> IS_TIME()('5:30 pm') (datetime.time(17, 30), None) >>> IS_TIME()('5:30 whatever') ('5:30 whatever', 'enter time as hh:mm:ss (seconds, am, pm optional)') >>> IS_TIME()('5:30 20') ('5:30 20', 'enter time as hh:mm:ss (seconds, am, pm optional)') >>> IS_TIME()('24:30') ('24:30', 'enter time as hh:mm:ss (seconds, am, pm optional)') >>> IS_TIME()('21:60') ('21:60', 'enter time as hh:mm:ss (seconds, am, pm optional)') >>> IS_TIME()('21:30::') ('21:30::', 'enter time as hh:mm:ss (seconds, am, pm optional)') >>> IS_TIME()('') ('', 'enter time as hh:mm:ss (seconds, am, pm optional)') """ def __init__(self, error_message='enter time as hh:mm:ss (seconds, am, pm optional)'): self.error_message = error_message def __call__(self, value): try: ivalue = value value = regex_time.match(value.lower()) (h, m, s) = (int(value.group('h')), 0, 0) if value.group('m') != None: m = int(value.group('m')) if value.group('s') != None: s = int(value.group('s')) if value.group('d') == 'pm' and 0 < h < 12: h = h + 12 if not (h in range(24) and m in range(60) and s in range(60)): raise ValueError\ ('Hours or minutes or seconds are outside of allowed range') value = datetime.time(h, m, s) return (value, None) except AttributeError: pass except ValueError: pass return (ivalue, translate(self.error_message)) class IS_DATE(Validator): """ example:: INPUT(_type='text', _name='name', requires=IS_DATE()) date has to be in the ISO8960 format YYYY-MM-DD """ def __init__(self, format='%Y-%m-%d', error_message='enter date as %(format)s'): self.format = str(format) self.error_message = str(error_message) def __call__(self, value): if isinstance(value,datetime.date): return (value,None) try: (y, m, d, hh, mm, ss, t0, t1, t2) = \ time.strptime(value, str(self.format)) value = datetime.date(y, m, d) return (value, None) except: return (value, translate(self.error_message) % IS_DATETIME.nice(self.format)) def formatter(self, value): format = self.format year = value.year y = '%.4i' % year format = format.replace('%y',y[-2:]) format = format.replace('%Y',y) if year<1900: year = 2000 d = datetime.date(year,value.month,value.day) return d.strftime(format) class IS_DATETIME(Validator): """ example:: INPUT(_type='text', _name='name', requires=IS_DATETIME()) datetime has to be in the ISO8960 format YYYY-MM-DD hh:mm:ss """ isodatetime = '%Y-%m-%d %H:%M:%S' @staticmethod def nice(format): code=(('%Y','1963'), ('%y','63'), ('%d','28'), ('%m','08'), ('%b','Aug'), ('%b','August'), ('%H','14'), ('%I','02'), ('%p','PM'), ('%M','30'), ('%S','59')) for (a,b) in code: format=format.replace(a,b) return dict(format=format) def __init__(self, format='%Y-%m-%d %H:%M:%S', error_message='enter date and time as %(format)s'): self.format = str(format) self.error_message = str(error_message) def __call__(self, value): if isinstance(value,datetime.datetime): return (value,None) try: (y, m, d, hh, mm, ss, t0, t1, t2) = \ time.strptime(value, str(self.format)) value = datetime.datetime(y, m, d, hh, mm, ss) return (value, None) except: return (value, translate(self.error_message) % IS_DATETIME.nice(self.format)) def formatter(self, value): format = self.format year = value.year y = '%.4i' % year format = format.replace('%y',y[-2:]) format = format.replace('%Y',y) if year<1900: year = 2000 d = datetime.datetime(year,value.month,value.day,value.hour,value.minute,value.second) return d.strftime(format) class IS_DATE_IN_RANGE(IS_DATE): """ example:: >>> v = IS_DATE_IN_RANGE(minimum=datetime.date(2008,1,1), \ maximum=datetime.date(2009,12,31), \ format="%m/%d/%Y",error_message="oops") >>> v('03/03/2008') (datetime.date(2008, 3, 3), None) >>> v('03/03/2010') (datetime.date(2010, 3, 3), 'oops') >>> v(datetime.date(2008,3,3)) (datetime.date(2008, 3, 3), None) >>> v(datetime.date(2010,3,3)) (datetime.date(2010, 3, 3), 'oops') """ def __init__(self, minimum = None, maximum = None, format='%Y-%m-%d', error_message = None): self.minimum = minimum self.maximum = maximum if error_message is None: if minimum is None: error_message = "enter date on or before %(max)s" elif maximum is None: error_message = "enter date on or after %(min)s" else: error_message = "enter date in range %(min)s %(max)s" d = dict(min=minimum, max=maximum) IS_DATE.__init__(self, format = format, error_message = error_message % d) def __call__(self, value): (value, msg) = IS_DATE.__call__(self,value) if msg is not None: return (value, msg) if self.minimum and self.minimum > value: return (value, translate(self.error_message)) if self.maximum and value > self.maximum: return (value, translate(self.error_message)) return (value, None) class IS_DATETIME_IN_RANGE(IS_DATETIME): """ example:: >>> v = IS_DATETIME_IN_RANGE(\ minimum=datetime.datetime(2008,1,1,12,20), \ maximum=datetime.datetime(2009,12,31,12,20), \ format="%m/%d/%Y %H:%M",error_message="oops") >>> v('03/03/2008 12:40') (datetime.datetime(2008, 3, 3, 12, 40), None) >>> v('03/03/2010 10:34') (datetime.datetime(2010, 3, 3, 10, 34), 'oops') >>> v(datetime.datetime(2008,3,3,0,0)) (datetime.datetime(2008, 3, 3, 0, 0), None) >>> v(datetime.datetime(2010,3,3,0,0)) (datetime.datetime(2010, 3, 3, 0, 0), 'oops') """ def __init__(self, minimum = None, maximum = None, format = '%Y-%m-%d %H:%M:%S', error_message = None): self.minimum = minimum self.maximum = maximum if error_message is None: if minimum is None: error_message = "enter date and time on or before %(max)s" elif maximum is None: error_message = "enter date and time on or after %(min)s" else: error_message = "enter date and time in range %(min)s %(max)s" d = dict(min = minimum, max = maximum) IS_DATETIME.__init__(self, format = format, error_message = error_message % d) def __call__(self, value): (value, msg) = IS_DATETIME.__call__(self, value) if msg is not None: return (value, msg) if self.minimum and self.minimum > value: return (value, translate(self.error_message)) if self.maximum and value > self.maximum: return (value, translate(self.error_message)) return (value, None) class IS_LIST_OF(Validator): def __init__(self, other): self.other = other def __call__(self, value): ivalue = value if not isinstance(value, list): ivalue = [ivalue] new_value = [] for item in ivalue: (v, e) = self.other(item) if e: return (value, e) else: new_value.append(v) return (new_value, None) class IS_LOWER(Validator): """ convert to lower case >>> IS_LOWER()('ABC') ('abc', None) >>> IS_LOWER()('Ñ') ('\\xc3\\xb1', None) """ def __call__(self, value): return (value.decode('utf8').lower().encode('utf8'), None) class IS_UPPER(Validator): """ convert to upper case >>> IS_UPPER()('abc') ('ABC', None) >>> IS_UPPER()('ñ') ('\\xc3\\x91', None) """ def __call__(self, value): return (value.decode('utf8').upper().encode('utf8'), None) def urlify(value, maxlen=80, keep_underscores=False): """ Convert incoming string to a simplified ASCII subset. if (keep_underscores): underscores are retained in the string else: underscores are translated to hyphens (default) """ s = value.lower() # to lowercase s = s.decode('utf-8') # to utf-8 s = unicodedata.normalize('NFKD', s) # normalize eg è => e, ñ => n s = s.encode('ASCII', 'ignore') # encode as ASCII s = re.sub('&\w+;', '', s) # strip html entities if keep_underscores: s = re.sub('\s+', '-', s) # whitespace to hyphens s = re.sub('[^\w\-]', '', s) # strip all but alphanumeric/underscore/hyphen else: s = re.sub('[\s_]+', '-', s) # whitespace & underscores to hyphens s = re.sub('[^a-z0-9\-]', '', s) # strip all but alphanumeric/hyphen s = re.sub('[-_][-_]+', '-', s) # collapse strings of hyphens s = s.strip('-') # remove leading and trailing hyphens return s[:maxlen] # enforce maximum length class IS_SLUG(Validator): """ convert arbitrary text string to a slug >>> IS_SLUG()('abc123') ('abc123', None) >>> IS_SLUG()('ABC123') ('abc123', None) >>> IS_SLUG()('abc-123') ('abc-123', None) >>> IS_SLUG()('abc--123') ('abc-123', None) >>> IS_SLUG()('abc 123') ('abc-123', None) >>> IS_SLUG()('abc\t_123') ('abc-123', None) >>> IS_SLUG()('-abc-') ('abc', None) >>> IS_SLUG()('--a--b--_ -c--') ('a-b-c', None) >>> IS_SLUG()('abc&amp;123') ('abc123', None) >>> IS_SLUG()('abc&amp;123&amp;def') ('abc123def', None) >>> IS_SLUG()('ñ') ('n', None) >>> IS_SLUG(maxlen=4)('abc123') ('abc1', None) >>> IS_SLUG()('abc_123') ('abc-123', None) >>> IS_SLUG(keep_underscores=False)('abc_123') ('abc-123', None) >>> IS_SLUG(keep_underscores=True)('abc_123') ('abc_123', None) >>> IS_SLUG(check=False)('abc') ('abc', None) >>> IS_SLUG(check=True)('abc') ('abc', None) >>> IS_SLUG(check=False)('a bc') ('a-bc', None) >>> IS_SLUG(check=True)('a bc') ('a bc', 'must be slug') """ @staticmethod def urlify(value, maxlen=80, keep_underscores=False): return urlify(value, maxlen, keep_underscores) def __init__(self, maxlen=80, check=False, error_message='must be slug', keep_underscores=False): self.maxlen = maxlen self.check = check self.error_message = error_message self.keep_underscores = keep_underscores def __call__(self, value): if self.check and value != urlify(value, self.maxlen, self.keep_underscores): return (value, translate(self.error_message)) return (urlify(value,self.maxlen, self.keep_underscores), None) class IS_EMPTY_OR(Validator): """ dummy class for testing IS_EMPTY_OR >>> IS_EMPTY_OR(IS_EMAIL())('abc@def.com') ('abc@def.com', None) >>> IS_EMPTY_OR(IS_EMAIL())(' ') (None, None) >>> IS_EMPTY_OR(IS_EMAIL(), null='abc')(' ') ('abc', None) >>> IS_EMPTY_OR(IS_EMAIL(), null='abc', empty_regex='def')('def') ('abc', None) >>> IS_EMPTY_OR(IS_EMAIL())('abc') ('abc', 'enter a valid email address') >>> IS_EMPTY_OR(IS_EMAIL())(' abc ') ('abc', 'enter a valid email address') """ def __init__(self, other, null=None, empty_regex=None): (self.other, self.null) = (other, null) if empty_regex is not None: self.empty_regex = re.compile(empty_regex) else: self.empty_regex = None if hasattr(other, 'multiple'): self.multiple = other.multiple if hasattr(other, 'options'): self.options=self._options def _options(self): options = self.other.options() if (not options or options[0][0]!='') and not self.multiple: options.insert(0,('','')) return options def set_self_id(self, id): if isinstance(self.other, (list, tuple)): for item in self.other: if hasattr(item, 'set_self_id'): item.set_self_id(id) else: if hasattr(self.other, 'set_self_id'): self.other.set_self_id(id) def __call__(self, value): value, empty = is_empty(value, empty_regex=self.empty_regex) if empty: return (self.null, None) if isinstance(self.other, (list, tuple)): for item in self.other: value, error = item(value) if error: break return value, error else: return self.other(value) def formatter(self, value): if hasattr(self.other, 'formatter'): return self.other.formatter(value) return value IS_NULL_OR = IS_EMPTY_OR # for backward compatibility class CLEANUP(Validator): """ example:: INPUT(_type='text', _name='name', requires=CLEANUP()) removes special characters on validation """ def __init__(self, regex='[^\x09\x0a\x0d\x20-\x7e]'): self.regex = re.compile(regex) def __call__(self, value): v = self.regex.sub('',str(value).strip()) return (v, None) class CRYPT(object): """ example:: INPUT(_type='text', _name='name', requires=CRYPT()) encodes the value on validation with a digest. If no arguments are provided CRYPT uses the MD5 algorithm. If the key argument is provided the HMAC+MD5 algorithm is used. If the digest_alg is specified this is used to replace the MD5 with, for example, SHA512. The digest_alg can be the name of a hashlib algorithm as a string or the algorithm itself. """ def __init__(self, key=None, digest_alg='md5'): self.key = key self.digest_alg = digest_alg def __call__(self, value): if self.key: return (hmac_hash(value, self.key, self.digest_alg), None) else: return (simple_hash(value, self.digest_alg), None) class IS_STRONG(object): """ example:: INPUT(_type='password', _name='passwd', requires=IS_STRONG(min=10, special=2, upper=2)) enforces complexity requirements on a field """ def __init__(self, min=8, max=20, upper=1, lower=1, number=1, special=1, specials=r'~!@#$%^&*()_+-=?<>,.:;{}[]|', invalid=' "', error_message=None): self.min = min self.max = max self.upper = upper self.lower = lower self.number = number self.special = special self.specials = specials self.invalid = invalid self.error_message = error_message def __call__(self, value): failures = [] if type(self.min) == int and self.min > 0: if not len(value) >= self.min: failures.append("Minimum length is %s" % self.min) if type(self.max) == int and self.max > 0: if not len(value) <= self.max: failures.append("Maximum length is %s" % self.max) if type(self.special) == int: all_special = [ch in value for ch in self.specials] if self.special > 0: if not all_special.count(True) >= self.special: failures.append("Must include at least %s of the following : %s" % (self.special, self.specials)) if self.invalid: all_invalid = [ch in value for ch in self.invalid] if all_invalid.count(True) > 0: failures.append("May not contain any of the following: %s" \ % self.invalid) if type(self.upper) == int: all_upper = re.findall("[A-Z]", value) if self.upper > 0: if not len(all_upper) >= self.upper: failures.append("Must include at least %s upper case" \ % str(self.upper)) else: if len(all_upper) > 0: failures.append("May not include any upper case letters") if type(self.lower) == int: all_lower = re.findall("[a-z]", value) if self.lower > 0: if not len(all_lower) >= self.lower: failures.append("Must include at least %s lower case" \ % str(self.lower)) else: if len(all_lower) > 0: failures.append("May not include any lower case letters") if type(self.number) == int: all_number = re.findall("[0-9]", value) if self.number > 0: numbers = "number" if self.number > 1: numbers = "numbers" if not len(all_number) >= self.number: failures.append("Must include at least %s %s" \ % (str(self.number), numbers)) else: if len(all_number) > 0: failures.append("May not include any numbers") if len(failures) == 0: return (value, None) if not translate(self.error_message): from html import XML return (value, XML('<br />'.join(failures))) else: return (value, translate(self.error_message)) class IS_IN_SUBSET(IS_IN_SET): def __init__(self, *a, **b): IS_IN_SET.__init__(self, *a, **b) def __call__(self, value): values = re.compile("\w+").findall(str(value)) failures = [x for x in values if IS_IN_SET.__call__(self, x)[1]] if failures: return (value, translate(self.error_message)) return (value, None) class IS_IMAGE(Validator): """ Checks if file uploaded through file input was saved in one of selected image formats and has dimensions (width and height) within given boundaries. Does *not* check for maximum file size (use IS_LENGTH for that). Returns validation failure if no data was uploaded. Supported file formats: BMP, GIF, JPEG, PNG. Code parts taken from http://mail.python.org/pipermail/python-list/2007-June/617126.html Arguments: extensions: iterable containing allowed *lowercase* image file extensions ('jpg' extension of uploaded file counts as 'jpeg') maxsize: iterable containing maximum width and height of the image minsize: iterable containing minimum width and height of the image Use (-1, -1) as minsize to pass image size check. Examples:: #Check if uploaded file is in any of supported image formats: INPUT(_type='file', _name='name', requires=IS_IMAGE()) #Check if uploaded file is either JPEG or PNG: INPUT(_type='file', _name='name', requires=IS_IMAGE(extensions=('jpeg', 'png'))) #Check if uploaded file is PNG with maximum size of 200x200 pixels: INPUT(_type='file', _name='name', requires=IS_IMAGE(extensions=('png'), maxsize=(200, 200))) """ def __init__(self, extensions=('bmp', 'gif', 'jpeg', 'png'), maxsize=(10000, 10000), minsize=(0, 0), error_message='invalid image'): self.extensions = extensions self.maxsize = maxsize self.minsize = minsize self.error_message = error_message def __call__(self, value): try: extension = value.filename.rfind('.') assert extension >= 0 extension = value.filename[extension + 1:].lower() if extension == 'jpg': extension = 'jpeg' assert extension in self.extensions if extension == 'bmp': width, height = self.__bmp(value.file) elif extension == 'gif': width, height = self.__gif(value.file) elif extension == 'jpeg': width, height = self.__jpeg(value.file) elif extension == 'png': width, height = self.__png(value.file) else: width = -1 height = -1 assert self.minsize[0] <= width <= self.maxsize[0] \ and self.minsize[1] <= height <= self.maxsize[1] value.file.seek(0) return (value, None) except: return (value, translate(self.error_message)) def __bmp(self, stream): if stream.read(2) == 'BM': stream.read(16) return struct.unpack("<LL", stream.read(8)) return (-1, -1) def __gif(self, stream): if stream.read(6) in ('GIF87a', 'GIF89a'): stream = stream.read(5) if len(stream) == 5: return tuple(struct.unpack("<HHB", stream)[:-1]) return (-1, -1) def __jpeg(self, stream): if stream.read(2) == '\xFF\xD8': while True: (marker, code, length) = struct.unpack("!BBH", stream.read(4)) if marker != 0xFF: break elif code >= 0xC0 and code <= 0xC3: return tuple(reversed( struct.unpack("!xHH", stream.read(5)))) else: stream.read(length - 2) return (-1, -1) def __png(self, stream): if stream.read(8) == '\211PNG\r\n\032\n': stream.read(4) if stream.read(4) == "IHDR": return struct.unpack("!LL", stream.read(8)) return (-1, -1) class IS_UPLOAD_FILENAME(Validator): """ Checks if name and extension of file uploaded through file input matches given criteria. Does *not* ensure the file type in any way. Returns validation failure if no data was uploaded. Arguments:: filename: filename (before dot) regex extension: extension (after dot) regex lastdot: which dot should be used as a filename / extension separator: True means last dot, eg. file.png -> file / png False means first dot, eg. file.tar.gz -> file / tar.gz case: 0 - keep the case, 1 - transform the string into lowercase (default), 2 - transform the string into uppercase If there is no dot present, extension checks will be done against empty string and filename checks against whole value. Examples:: #Check if file has a pdf extension (case insensitive): INPUT(_type='file', _name='name', requires=IS_UPLOAD_FILENAME(extension='pdf')) #Check if file has a tar.gz extension and name starting with backup: INPUT(_type='file', _name='name', requires=IS_UPLOAD_FILENAME(filename='backup.*', extension='tar.gz', lastdot=False)) #Check if file has no extension and name matching README #(case sensitive): INPUT(_type='file', _name='name', requires=IS_UPLOAD_FILENAME(filename='^README$', extension='^$', case=0)) """ def __init__(self, filename=None, extension=None, lastdot=True, case=1, error_message='enter valid filename'): if isinstance(filename, str): filename = re.compile(filename) if isinstance(extension, str): extension = re.compile(extension) self.filename = filename self.extension = extension self.lastdot = lastdot self.case = case self.error_message = error_message def __call__(self, value): try: string = value.filename except: return (value, translate(self.error_message)) if self.case == 1: string = string.lower() elif self.case == 2: string = string.upper() if self.lastdot: dot = string.rfind('.') else: dot = string.find('.') if dot == -1: dot = len(string) if self.filename and not self.filename.match(string[:dot]): return (value, translate(self.error_message)) elif self.extension and not self.extension.match(string[dot + 1:]): return (value, translate(self.error_message)) else: return (value, None) class IS_IPV4(Validator): """ Checks if field's value is an IP version 4 address in decimal form. Can be set to force addresses from certain range. IPv4 regex taken from: http://regexlib.com/REDetails.aspx?regexp_id=1411 Arguments: minip: lowest allowed address; accepts: str, eg. 192.168.0.1 list or tuple of octets, eg. [192, 168, 0, 1] maxip: highest allowed address; same as above invert: True to allow addresses only from outside of given range; note that range boundaries are not matched this way is_localhost: localhost address treatment: None (default): indifferent True (enforce): query address must match localhost address (127.0.0.1) False (forbid): query address must not match localhost address is_private: same as above, except that query address is checked against two address ranges: 172.16.0.0 - 172.31.255.255 and 192.168.0.0 - 192.168.255.255 is_automatic: same as above, except that query address is checked against one address range: 169.254.0.0 - 169.254.255.255 Minip and maxip may also be lists or tuples of addresses in all above forms (str, int, list / tuple), allowing setup of multiple address ranges: minip = (minip1, minip2, ... minipN) | | | | | | maxip = (maxip1, maxip2, ... maxipN) Longer iterable will be truncated to match length of shorter one. Examples:: #Check for valid IPv4 address: INPUT(_type='text', _name='name', requires=IS_IPV4()) #Check for valid IPv4 address belonging to specific range: INPUT(_type='text', _name='name', requires=IS_IPV4(minip='100.200.0.0', maxip='100.200.255.255')) #Check for valid IPv4 address belonging to either 100.110.0.0 - #100.110.255.255 or 200.50.0.0 - 200.50.0.255 address range: INPUT(_type='text', _name='name', requires=IS_IPV4(minip=('100.110.0.0', '200.50.0.0'), maxip=('100.110.255.255', '200.50.0.255'))) #Check for valid IPv4 address belonging to private address space: INPUT(_type='text', _name='name', requires=IS_IPV4(is_private=True)) #Check for valid IPv4 address that is not a localhost address: INPUT(_type='text', _name='name', requires=IS_IPV4(is_localhost=False)) >>> IS_IPV4()('1.2.3.4') ('1.2.3.4', None) >>> IS_IPV4()('255.255.255.255') ('255.255.255.255', None) >>> IS_IPV4()('1.2.3.4 ') ('1.2.3.4 ', 'enter valid IPv4 address') >>> IS_IPV4()('1.2.3.4.5') ('1.2.3.4.5', 'enter valid IPv4 address') >>> IS_IPV4()('123.123') ('123.123', 'enter valid IPv4 address') >>> IS_IPV4()('1111.2.3.4') ('1111.2.3.4', 'enter valid IPv4 address') >>> IS_IPV4()('0111.2.3.4') ('0111.2.3.4', 'enter valid IPv4 address') >>> IS_IPV4()('256.2.3.4') ('256.2.3.4', 'enter valid IPv4 address') >>> IS_IPV4()('300.2.3.4') ('300.2.3.4', 'enter valid IPv4 address') >>> IS_IPV4(minip='1.2.3.4', maxip='1.2.3.4')('1.2.3.4') ('1.2.3.4', None) >>> IS_IPV4(minip='1.2.3.5', maxip='1.2.3.9', error_message='bad ip')('1.2.3.4') ('1.2.3.4', 'bad ip') >>> IS_IPV4(maxip='1.2.3.4', invert=True)('127.0.0.1') ('127.0.0.1', None) >>> IS_IPV4(maxip='1.2.3.4', invert=True)('1.2.3.4') ('1.2.3.4', 'enter valid IPv4 address') >>> IS_IPV4(is_localhost=True)('127.0.0.1') ('127.0.0.1', None) >>> IS_IPV4(is_localhost=True)('1.2.3.4') ('1.2.3.4', 'enter valid IPv4 address') >>> IS_IPV4(is_localhost=False)('127.0.0.1') ('127.0.0.1', 'enter valid IPv4 address') >>> IS_IPV4(maxip='100.0.0.0', is_localhost=True)('127.0.0.1') ('127.0.0.1', 'enter valid IPv4 address') """ regex = re.compile( '^(([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])\.){3}([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])$') numbers = (16777216, 65536, 256, 1) localhost = 2130706433 private = ((2886729728L, 2886795263L), (3232235520L, 3232301055L)) automatic = (2851995648L, 2852061183L) def __init__( self, minip='0.0.0.0', maxip='255.255.255.255', invert=False, is_localhost=None, is_private=None, is_automatic=None, error_message='enter valid IPv4 address'): for n, value in enumerate((minip, maxip)): temp = [] if isinstance(value, str): temp.append(value.split('.')) elif isinstance(value, (list, tuple)): if len(value) == len(filter(lambda item: isinstance(item, int), value)) == 4: temp.append(value) else: for item in value: if isinstance(item, str): temp.append(item.split('.')) elif isinstance(item, (list, tuple)): temp.append(item) numbers = [] for item in temp: number = 0 for i, j in zip(self.numbers, item): number += i * int(j) numbers.append(number) if n == 0: self.minip = numbers else: self.maxip = numbers self.invert = invert self.is_localhost = is_localhost self.is_private = is_private self.is_automatic = is_automatic self.error_message = error_message def __call__(self, value): if self.regex.match(value): number = 0 for i, j in zip(self.numbers, value.split('.')): number += i * int(j) ok = False for bottom, top in zip(self.minip, self.maxip): if self.invert != (bottom <= number <= top): ok = True if not (self.is_localhost == None or self.is_localhost == \ (number == self.localhost)): ok = False if not (self.is_private == None or self.is_private == \ (sum([number[0] <= number <= number[1] for number in self.private]) > 0)): ok = False if not (self.is_automatic == None or self.is_automatic == \ (self.automatic[0] <= number <= self.automatic[1])): ok = False if ok: return (value, None) return (value, translate(self.error_message)) if __name__ == '__main__': import doctest doctest.testmod()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) Holds: - SQLFORM: provide a form for a table (with/without record) - SQLTABLE: provides a table for a set of records - form_factory: provides a SQLFORM for an non-db backed table """ from http import HTTP from html import XML, SPAN, TAG, A, DIV, UL, LI, TEXTAREA, BR, IMG, SCRIPT from html import FORM, INPUT, LABEL, OPTION, SELECT from html import TABLE, THEAD, TBODY, TR, TD, TH from html import URL as Url from dal import DAL, Table, Row, CALLABLETYPES from storage import Storage from utils import md5_hash from validators import IS_EMPTY_OR import urllib import re import cStringIO table_field = re.compile('[\w_]+\.[\w_]+') widget_class = re.compile('^\w*') def represent(field,value,record): f = field.represent if not callable(f): return str(value) n = f.func_code.co_argcount-len(f.func_defaults or []) if n==1: return f(value) elif n==2: return f(value,record) else: raise RuntimeError, "field representation must take 1 or 2 args" def safe_int(x): try: return int(x) except ValueError: return 0 def safe_float(x): try: return float(x) except ValueError: return 0 class FormWidget(object): """ helper for SQLFORM to generate form input fields (widget), related to the fieldtype """ @staticmethod def _attributes(field, widget_attributes, **attributes): """ helper to build a common set of attributes :param field: the field involved, some attributes are derived from this :param widget_attributes: widget related attributes :param attributes: any other supplied attributes """ attr = dict( _id = '%s_%s' % (field._tablename, field.name), _class = widget_class.match(str(field.type)).group(), _name = field.name, requires = field.requires, ) attr.update(widget_attributes) attr.update(attributes) return attr @staticmethod def widget(field, value, **attributes): """ generates the widget for the field. When serialized, will provide an INPUT tag: - id = tablename_fieldname - class = field.type - name = fieldname :param field: the field needing the widget :param value: value :param attributes: any other attributes to be applied """ raise NotImplementedError class StringWidget(FormWidget): @staticmethod def widget(field, value, **attributes): """ generates an INPUT text tag. see also: :meth:`FormWidget.widget` """ default = dict( _type = 'text', value = (value!=None and str(value)) or '', ) attr = StringWidget._attributes(field, default, **attributes) return INPUT(**attr) class IntegerWidget(StringWidget): pass class DoubleWidget(StringWidget): pass class DecimalWidget(StringWidget): pass class TimeWidget(StringWidget): pass class DateWidget(StringWidget): pass class DatetimeWidget(StringWidget): pass class TextWidget(FormWidget): @staticmethod def widget(field, value, **attributes): """ generates a TEXTAREA tag. see also: :meth:`FormWidget.widget` """ default = dict( value = value, ) attr = TextWidget._attributes(field, default, **attributes) return TEXTAREA(**attr) class BooleanWidget(FormWidget): @staticmethod def widget(field, value, **attributes): """ generates an INPUT checkbox tag. see also: :meth:`FormWidget.widget` """ default=dict( _type='checkbox', value=value, ) attr = BooleanWidget._attributes(field, default, **attributes) return INPUT(**attr) class OptionsWidget(FormWidget): @staticmethod def has_options(field): """ checks if the field has selectable options :param field: the field needing checking :returns: True if the field has options """ return hasattr(field.requires, 'options') @staticmethod def widget(field, value, **attributes): """ generates a SELECT tag, including OPTIONs (only 1 option allowed) see also: :meth:`FormWidget.widget` """ default = dict( value=value, ) attr = OptionsWidget._attributes(field, default, **attributes) requires = field.requires if not isinstance(requires, (list, tuple)): requires = [requires] if requires: if hasattr(requires[0], 'options'): options = requires[0].options() else: raise SyntaxError, 'widget cannot determine options of %s' \ % field opts = [OPTION(v, _value=k) for (k, v) in options] return SELECT(*opts, **attr) class ListWidget(StringWidget): @staticmethod def widget(field,value,**attributes): _id = '%s_%s' % (field._tablename, field.name) _name = field.name if field.type=='list:integer': _class = 'integer' else: _class = 'string' items=[LI(INPUT(_id=_id,_class=_class,_name=_name,value=v,hideerror=True)) \ for v in value or ['']] script=SCRIPT(""" // from http://refactormycode.com/codes/694-expanding-input-list-using-jquery (function(){ jQuery.fn.grow_input = function() { return this.each(function() { var ul = this; jQuery(ul).find(":text").after('<a href="javascript:void(0)>+</a>').keypress(function (e) { return (e.which == 13) ? pe(ul) : true; }).next().click(function(){ pe(ul) }); }); }; function pe(ul) { var new_line = ml(ul); rel(ul); new_line.appendTo(ul); new_line.find(":text").focus(); return false; } function ml(ul) { var line = jQuery(ul).find("li:first").clone(true); line.find(':text').val(''); return line; } function rel(ul) { jQuery(ul).find("li").each(function() { var trimmed = jQuery.trim(jQuery(this.firstChild).val()); if (trimmed=='') jQuery(this).remove(); else jQuery(this.firstChild).val(trimmed); }); } })(); jQuery(document).ready(function(){jQuery('#%s_grow_input').grow_input();}); """ % _id) attributes['_id']=_id+'_grow_input' return TAG[''](UL(*items,**attributes),script) class MultipleOptionsWidget(OptionsWidget): @staticmethod def widget(field, value, size=5, **attributes): """ generates a SELECT tag, including OPTIONs (multiple options allowed) see also: :meth:`FormWidget.widget` :param size: optional param (default=5) to indicate how many rows must be shown """ attributes.update(dict(_size=size, _multiple=True)) return OptionsWidget.widget(field, value, **attributes) class RadioWidget(OptionsWidget): @staticmethod def widget(field, value, **attributes): """ generates a TABLE tag, including INPUT radios (only 1 option allowed) see also: :meth:`FormWidget.widget` """ attr = OptionsWidget._attributes(field, {}, **attributes) requires = field.requires if not isinstance(requires, (list, tuple)): requires = [requires] if requires: if hasattr(requires[0], 'options'): options = requires[0].options() else: raise SyntaxError, 'widget cannot determine options of %s' \ % field options = [(k, v) for k, v in options if str(v)] opts = [] cols = attributes.get('cols',1) totals = len(options) mods = totals%cols rows = totals/cols if mods: rows += 1 for r_index in range(rows): tds = [] for k, v in options[r_index*cols:(r_index+1)*cols]: tds.append(TD(INPUT(_type='radio', _name=field.name, requires=attr.get('requires',None), hideerror=True, _value=k, value=value), v)) opts.append(TR(tds)) if opts: opts[-1][0][0]['hideerror'] = False return TABLE(*opts, **attr) class CheckboxesWidget(OptionsWidget): @staticmethod def widget(field, value, **attributes): """ generates a TABLE tag, including INPUT checkboxes (multiple allowed) see also: :meth:`FormWidget.widget` """ # was values = re.compile('[\w\-:]+').findall(str(value)) if isinstance(value, (list, tuple)): values = [str(v) for v in value] else: values = [str(value)] attr = OptionsWidget._attributes(field, {}, **attributes) requires = field.requires if not isinstance(requires, (list, tuple)): requires = [requires] if requires: if hasattr(requires[0], 'options'): options = requires[0].options() else: raise SyntaxError, 'widget cannot determine options of %s' \ % field options = [(k, v) for k, v in options if k != ''] opts = [] cols = attributes.get('cols', 1) totals = len(options) mods = totals % cols rows = totals / cols if mods: rows += 1 for r_index in range(rows): tds = [] for k, v in options[r_index*cols:(r_index+1)*cols]: if k in values: r_value = k else: r_value = [] tds.append(TD(INPUT(_type='checkbox', _name=field.name, requires=attr.get('requires', None), hideerror=True, _value=k, value=r_value), v)) opts.append(TR(tds)) if opts: opts[-1][0][0]['hideerror'] = False return TABLE(*opts, **attr) class PasswordWidget(FormWidget): DEFAULT_PASSWORD_DISPLAY = 8*('*') @staticmethod def widget(field, value, **attributes): """ generates a INPUT password tag. If a value is present it will be shown as a number of '*', not related to the length of the actual value. see also: :meth:`FormWidget.widget` """ default=dict( _type='password', _value=(value and PasswordWidget.DEFAULT_PASSWORD_DISPLAY) or '', ) attr = PasswordWidget._attributes(field, default, **attributes) return INPUT(**attr) class UploadWidget(FormWidget): DEFAULT_WIDTH = '150px' ID_DELETE_SUFFIX = '__delete' GENERIC_DESCRIPTION = 'file' DELETE_FILE = 'delete' @staticmethod def widget(field, value, download_url=None, **attributes): """ generates a INPUT file tag. Optionally provides an A link to the file, including a checkbox so the file can be deleted. All is wrapped in a DIV. see also: :meth:`FormWidget.widget` :param download_url: Optional URL to link to the file (default = None) """ default=dict( _type='file', ) attr = UploadWidget._attributes(field, default, **attributes) inp = INPUT(**attr) if download_url and value: url = download_url + '/' + value (br, image) = ('', '') if UploadWidget.is_image(value): br = BR() image = IMG(_src = url, _width = UploadWidget.DEFAULT_WIDTH) requires = attr["requires"] if requires == [] or isinstance(requires, IS_EMPTY_OR): inp = DIV(inp, '[', A(UploadWidget.GENERIC_DESCRIPTION, _href = url), '|', INPUT(_type='checkbox', _name=field.name + UploadWidget.ID_DELETE_SUFFIX), UploadWidget.DELETE_FILE, ']', br, image) else: inp = DIV(inp, '[', A(UploadWidget.GENERIC_DESCRIPTION, _href = url), ']', br, image) return inp @staticmethod def represent(field, value, download_url=None): """ how to represent the file: - with download url and if it is an image: <A href=...><IMG ...></A> - otherwise with download url: <A href=...>file</A> - otherwise: file :param field: the field :param value: the field value :param download_url: url for the file download (default = None) """ inp = UploadWidget.GENERIC_DESCRIPTION if download_url and value: url = download_url + '/' + value if UploadWidget.is_image(value): inp = IMG(_src = url, _width = UploadWidget.DEFAULT_WIDTH) inp = A(inp, _href = url) return inp @staticmethod def is_image(value): """ Tries to check if the filename provided references to an image Checking is based on filename extension. Currently recognized: gif, png, jp(e)g, bmp :param value: filename """ extension = value.split('.')[-1].lower() if extension in ['gif', 'png', 'jpg', 'jpeg', 'bmp']: return True return False class AutocompleteWidget(object): def __init__(self, request, field, id_field=None, db=None, orderby=None, limitby=(0,10), keyword='_autocomplete_%(fieldname)s', min_length=2): self.request = request self.keyword = keyword % dict(fieldname=field.name) self.db = db or field._db self.orderby = orderby self.limitby = limitby self.min_length = min_length self.fields=[field] if id_field: self.is_reference = True self.fields.append(id_field) else: self.is_reference = False if hasattr(request,'application'): self.url = Url(r=request, args=request.args) self.callback() else: self.url = request def callback(self): if self.keyword in self.request.vars: field = self.fields[0] rows = self.db(field.like(self.request.vars[self.keyword]+'%'))\ .select(orderby=self.orderby,limitby=self.limitby,*self.fields) if rows: if self.is_reference: id_field = self.fields[1] raise HTTP(200,SELECT(_id=self.keyword,_class='autocomplete', _size=len(rows),_multiple=(len(rows)==1), *[OPTION(s[field.name],_value=s[id_field.name], _selected=(k==0)) \ for k,s in enumerate(rows)]).xml()) else: raise HTTP(200,SELECT(_id=self.keyword,_class='autocomplete', _size=len(rows),_multiple=(len(rows)==1), *[OPTION(s[field.name], _selected=(k==0)) \ for k,s in enumerate(rows)]).xml()) else: raise HTTP(200,'') def __call__(self,field,value,**attributes): default = dict( _type = 'text', value = (value!=None and str(value)) or '', ) attr = StringWidget._attributes(field, default, **attributes) div_id = self.keyword+'_div' attr['_autocomplete']='off' if self.is_reference: key2 = self.keyword+'_aux' key3 = self.keyword+'_auto' attr['_class']='string' name = attr['_name'] if 'requires' in attr: del attr['requires'] attr['_name'] = key2 value = attr['value'] record = self.db(self.fields[1]==value).select(self.fields[0]).first() attr['value'] = record and record[self.fields[0].name] attr['_onblur']="jQuery('#%(div_id)s').delay(3000).fadeOut('slow');" % \ dict(div_id=div_id,u='F'+self.keyword) attr['_onkeyup'] = "jQuery('#%(key3)s').val('');var e=event.which?event.which:event.keyCode; function %(u)s(){jQuery('#%(id)s').val(jQuery('#%(key)s :selected').text());jQuery('#%(key3)s').val(jQuery('#%(key)s').val())}; if(e==39) %(u)s(); else if(e==40) {if(jQuery('#%(key)s option:selected').next().length)jQuery('#%(key)s option:selected').attr('selected',null).next().attr('selected','selected'); %(u)s();} else if(e==38) {if(jQuery('#%(key)s option:selected').prev().length)jQuery('#%(key)s option:selected').attr('selected',null).prev().attr('selected','selected'); %(u)s();} else if(jQuery('#%(id)s').val().length>=%(min_length)s) jQuery.get('%(url)s?%(key)s='+escape(jQuery('#%(id)s').val()),function(data){if(data=='')jQuery('#%(key3)s').val('');else{jQuery('#%(id)s').next('.error').hide();jQuery('#%(div_id)s').html(data).show().focus();jQuery('#%(div_id)s select').css('width',jQuery('#%(id)s').css('width'));jQuery('#%(key3)s').val(jQuery('#%(key)s').val());jQuery('#%(key)s').change(%(u)s);jQuery('#%(key)s').click(%(u)s);};}); else jQuery('#%(div_id)s').fadeOut('slow');" % \ dict(url=self.url,min_length=self.min_length, key=self.keyword,id=attr['_id'],key2=key2,key3=key3, name=name,div_id=div_id,u='F'+self.keyword) if self.min_length==0: attr['_onfocus'] = attr['_onkeyup'] return TAG[''](INPUT(**attr),INPUT(_type='hidden',_id=key3,_value=value, _name=name,requires=field.requires), DIV(_id=div_id,_style='position:absolute;')) else: attr['_name']=field.name attr['_onblur']="jQuery('#%(div_id)s').delay(3000).fadeOut('slow');" % \ dict(div_id=div_id,u='F'+self.keyword) attr['_onkeyup'] = "var e=event.which?event.which:event.keyCode; function %(u)s(){jQuery('#%(id)s').val(jQuery('#%(key)s').val())}; if(e==39) %(u)s(); else if(e==40) {if(jQuery('#%(key)s option:selected').next().length)jQuery('#%(key)s option:selected').attr('selected',null).next().attr('selected','selected'); %(u)s();} else if(e==38) {if(jQuery('#%(key)s option:selected').prev().length)jQuery('#%(key)s option:selected').attr('selected',null).prev().attr('selected','selected'); %(u)s();} else if(jQuery('#%(id)s').val().length>=%(min_length)s) jQuery.get('%(url)s?%(key)s='+escape(jQuery('#%(id)s').val()),function(data){jQuery('#%(id)s').next('.error').hide();jQuery('#%(div_id)s').html(data).show().focus();jQuery('#%(div_id)s select').css('width',jQuery('#%(id)s').css('width'));jQuery('#%(key)s').change(%(u)s);jQuery('#%(key)s').click(%(u)s);}); else jQuery('#%(div_id)s').fadeOut('slow');" % \ dict(url=self.url,min_length=self.min_length, key=self.keyword,id=attr['_id'],div_id=div_id,u='F'+self.keyword) if self.min_length==0: attr['_onfocus'] = attr['_onkeyup'] return TAG[''](INPUT(**attr),DIV(_id=div_id,_style='position:absolute;')) class SQLFORM(FORM): """ SQLFORM is used to map a table (and a current record) into an HTML form given a SQLTable stored in db.table generates an insert form:: SQLFORM(db.table) generates an update form:: record=db.table[some_id] SQLFORM(db.table, record) generates an update with a delete button:: SQLFORM(db.table, record, deletable=True) if record is an int:: record=db.table[record] optional arguments: :param fields: a list of fields that should be placed in the form, default is all. :param labels: a dictionary with labels for each field, keys are the field names. :param col3: a dictionary with content for an optional third column (right of each field). keys are field names. :param linkto: the URL of a controller/function to access referencedby records see controller appadmin.py for examples :param upload: the URL of a controller/function to download an uploaded file see controller appadmin.py for examples any named optional attribute is passed to the <form> tag for example _class, _id, _style, _action, _method, etc. """ # usability improvements proposal by fpp - 4 May 2008 : # - correct labels (for points to field id, not field name) # - add label for delete checkbox # - add translatable label for record ID # - add third column to right of fields, populated from the col3 dict widgets = Storage(dict( string = StringWidget, text = TextWidget, password = PasswordWidget, integer = IntegerWidget, double = DoubleWidget, decimal = DecimalWidget, time = TimeWidget, date = DateWidget, datetime = DatetimeWidget, upload = UploadWidget, boolean = BooleanWidget, blob = None, options = OptionsWidget, multiple = MultipleOptionsWidget, radio = RadioWidget, checkboxes = CheckboxesWidget, autocomplete = AutocompleteWidget, list = ListWidget, )) FIELDNAME_REQUEST_DELETE = 'delete_this_record' FIELDKEY_DELETE_RECORD = 'delete_record' ID_LABEL_SUFFIX = '__label' ID_ROW_SUFFIX = '__row' def __init__( self, table, record = None, deletable = False, linkto = None, upload = None, fields = None, labels = None, col3 = {}, submit_button = 'Submit', delete_label = 'Check to delete:', showid = True, readonly = False, comments = True, keepopts = [], ignore_rw = False, record_id = None, formstyle = 'table3cols', buttons = ['submit'], separator = ': ', **attributes ): """ SQLFORM(db.table, record=None, fields=['name'], labels={'name': 'Your name'}, linkto=URL(r=request, f='table/db/') """ self.ignore_rw = ignore_rw self.formstyle = formstyle nbsp = XML('&nbsp;') # Firefox2 does not display fields with blanks FORM.__init__(self, *[], **attributes) ofields = fields keyed = hasattr(table,'_primarykey') # if no fields are provided, build it from the provided table # will only use writable or readable fields, unless forced to ignore if fields == None: fields = [f.name for f in table if (ignore_rw or f.writable or f.readable) and not f.compute] self.fields = fields # make sure we have an id if self.fields[0] != table.fields[0] and \ isinstance(table,Table) and not keyed: self.fields.insert(0, table.fields[0]) self.table = table # try to retrieve the indicated record using its id # otherwise ignore it if record and isinstance(record, (int, long, str, unicode)): if not str(record).isdigit(): raise HTTP(404, "Object not found") record = table._db(table._id == record).select().first() if not record: raise HTTP(404, "Object not found") self.record = record self.record_id = record_id if keyed: if record: self.record_id = dict([(k,record[k]) for k in table._primarykey]) else: self.record_id = dict([(k,None) for k in table._primarykey]) self.field_parent = {} xfields = [] self.fields = fields self.custom = Storage() self.custom.dspval = Storage() self.custom.inpval = Storage() self.custom.label = Storage() self.custom.comment = Storage() self.custom.widget = Storage() self.custom.linkto = Storage() sep = separator or '' for fieldname in self.fields: if fieldname.find('.') >= 0: continue field = self.table[fieldname] comment = None if comments: comment = col3.get(fieldname, field.comment) if comment == None: comment = '' self.custom.comment[fieldname] = comment if labels != None and fieldname in labels: label = labels[fieldname] else: label = field.label self.custom.label[fieldname] = label field_id = '%s_%s' % (table._tablename, fieldname) label = LABEL(label, sep, _for=field_id, _id=field_id+SQLFORM.ID_LABEL_SUFFIX) row_id = field_id+SQLFORM.ID_ROW_SUFFIX if field.type == 'id': self.custom.dspval.id = nbsp self.custom.inpval.id = '' widget = '' if record: if showid and 'id' in fields and field.readable: v = record['id'] widget = SPAN(v, _id=field_id) self.custom.dspval.id = str(v) xfields.append((row_id,label, widget,comment)) self.record_id = str(record['id']) self.custom.widget.id = widget continue if readonly and not ignore_rw and not field.readable: continue if record: default = record[fieldname] else: default = field.default if isinstance(default,CALLABLETYPES): default=default() cond = readonly or \ (not ignore_rw and not field.writable and field.readable) if default and not cond: default = field.formatter(default) dspval = default inpval = default if cond: # ## if field.represent is available else # ## ignore blob and preview uploaded images # ## format everything else if field.represent: inp = represent(field,default,record) elif field.type in ['blob']: continue elif field.type == 'upload': inp = UploadWidget.represent(field, default, upload) elif field.type == 'boolean': inp = self.widgets.boolean.widget(field, default, _disabled=True) else: inp = field.formatter(default) elif field.type == 'upload': if hasattr(field, 'widget') and field.widget: inp = field.widget(field, default, upload) else: inp = self.widgets.upload.widget(field, default, upload) elif hasattr(field, 'widget') and field.widget: inp = field.widget(field, default) elif field.type == 'boolean': inp = self.widgets.boolean.widget(field, default) if default: inpval = 'checked' else: inpval = '' elif OptionsWidget.has_options(field): if not field.requires.multiple: inp = self.widgets.options.widget(field, default) else: inp = self.widgets.multiple.widget(field, default) if fieldname in keepopts: inpval = TAG[''](*inp.components) elif field.type.startswith('list:'): inp = self.widgets.list.widget(field,default) elif field.type == 'text': inp = self.widgets.text.widget(field, default) elif field.type == 'password': inp = self.widgets.password.widget(field, default) if self.record: dspval = PasswordWidget.DEFAULT_PASSWORD_DISPLAY else: dspval = '' elif field.type == 'blob': continue else: inp = self.widgets.string.widget(field, default) xfields.append((row_id,label,inp,comment)) self.custom.dspval[fieldname] = dspval or nbsp self.custom.inpval[fieldname] = inpval or '' self.custom.widget[fieldname] = inp # if a record is provided and found, as is linkto # build a link if record and linkto: db = linkto.split('/')[-1] for (rtable, rfield) in table._referenced_by: if keyed: rfld = table._db[rtable][rfield] query = urllib.quote('%s.%s==%s' % (db,rfld,record[rfld.type[10:].split('.')[1]])) else: query = urllib.quote('%s.%s==%s' % (db,table._db[rtable][rfield],record.id)) lname = olname = '%s.%s' % (rtable, rfield) if ofields and not olname in ofields: continue if labels and lname in labels: lname = labels[lname] widget = A(lname, _class='reference', _href='%s/%s?query=%s' % (linkto, rtable, query)) xfields.append((olname.replace('.', '__')+SQLFORM.ID_ROW_SUFFIX, '',widget,col3.get(olname,''))) self.custom.linkto[olname.replace('.', '__')] = widget # </block> # when deletable, add delete? checkbox self.custom.deletable = '' if record and deletable: widget = INPUT(_type='checkbox', _class='delete', _id=self.FIELDKEY_DELETE_RECORD, _name=self.FIELDNAME_REQUEST_DELETE, ) xfields.append((self.FIELDKEY_DELETE_RECORD+SQLFORM.ID_ROW_SUFFIX, LABEL( delete_label, _for=self.FIELDKEY_DELETE_RECORD, _id=self.FIELDKEY_DELETE_RECORD+SQLFORM.ID_LABEL_SUFFIX), widget, col3.get(self.FIELDKEY_DELETE_RECORD, ''))) self.custom.deletable = widget # when writable, add submit button self.custom.submit = '' if (not readonly) and ('submit' in buttons): widget = INPUT(_type='submit', _value=submit_button) xfields.append(('submit_record'+SQLFORM.ID_ROW_SUFFIX, '', widget,col3.get('submit_button', ''))) self.custom.submit = widget # if a record is provided and found # make sure it's id is stored in the form if record: if not self['hidden']: self['hidden'] = {} if not keyed: self['hidden']['id'] = record['id'] (begin, end) = self._xml() self.custom.begin = XML("<%s %s>" % (self.tag, begin)) self.custom.end = XML("%s</%s>" % (end, self.tag)) table = self.createform(xfields) self.components = [table] def createform(self, xfields): if self.formstyle == 'table3cols': table = TABLE() for id,a,b,c in xfields: td_b = self.field_parent[id] = TD(b,_class='w2p_fw') table.append(TR(TD(a,_class='w2p_fl'), td_b, TD(c,_class='w2p_fc'),_id=id)) elif self.formstyle == 'table2cols': table = TABLE() for id,a,b,c in xfields: td_b = self.field_parent[id] = TD(b,_class='w2p_fw',_colspan="2") table.append(TR(TD(a,_class='w2p_fl'), TD(c,_class='w2p_fc'),_id=id +'1',_class='even')) table.append(TR(td_b,_id=id+'2',_class='odd')) elif self.formstyle == 'divs': table = TAG['']() for id,a,b,c in xfields: div_b = self.field_parent[id] = DIV(b,_class='w2p_fw') table.append(DIV(DIV(a,_class='w2p_fl'), div_b, DIV(c,_class='w2p_fc'),_id=id)) elif self.formstyle == 'ul': table = UL() for id,a,b,c in xfields: div_b = self.field_parent[id] = DIV(b,_class='w2p_fw') table.append(LI(DIV(a,_class='w2p_fl'), div_b, DIV(c,_class='w2p_fc'),_id=id)) elif type(self.formstyle) == type(lambda:None): table = TABLE() for id,a,b,c in xfields: td_b = self.field_parent[id] = TD(b,_class='w2p_fw') newrows = self.formstyle(id,a,td_b,c) if type(newrows).__name__ != "tuple": newrows = [newrows] for newrow in newrows: table.append(newrow) else: raise RuntimeError, 'formstyle not supported' return table def accepts( self, request_vars, session=None, formname='%(tablename)s/%(record_id)s', keepvalues=False, onvalidation=None, dbio=True, hideerror=False, detect_record_change=False, ): """ similar FORM.accepts but also does insert, update or delete in DAL. but if detect_record_change == True than: form.record_changed = False (record is properly validated/submitted) form.record_changed = True (record cannot be submitted because changed) elseif detect_record_change == False than: form.record_changed = None """ if request_vars.__class__.__name__ == 'Request': request_vars = request_vars.post_vars keyed = hasattr(self.table, '_primarykey') # implement logic to detect whether record exist but has been modified # server side self.record_changed = None if detect_record_change: if self.record: self.record_changed = False serialized = '|'.join(str(self.record[k]) for k in self.table.fields()) self.record_hash = md5_hash(serialized) # logic to deal with record_id for keyed tables if self.record: if keyed: formname_id = '.'.join(str(self.record[k]) for k in self.table._primarykey if hasattr(self.record,k)) record_id = dict((k, request_vars[k]) for k in self.table._primarykey) else: (formname_id, record_id) = (self.record.id, request_vars.get('id', None)) keepvalues = True else: if keyed: formname_id = 'create' record_id = dict([(k, None) for k in self.table._primarykey]) else: (formname_id, record_id) = ('create', None) if not keyed and isinstance(record_id, (list, tuple)): record_id = record_id[0] if formname: formname = formname % dict(tablename = self.table._tablename, record_id = formname_id) # ## THIS IS FOR UNIQUE RECORDS, read IS_NOT_IN_DB for fieldname in self.fields: field = self.table[fieldname] requires = field.requires or [] if not isinstance(requires, (list, tuple)): requires = [requires] [item.set_self_id(self.record_id) for item in requires if hasattr(item, 'set_self_id') and self.record_id] # ## END fields = {} for key in self.vars: fields[key] = self.vars[key] ret = FORM.accepts( self, request_vars, session, formname, keepvalues, onvalidation, hideerror=hideerror, ) if not ret and self.record and self.errors: ### if there are errors in update mode # and some errors refers to an already uploaded file # delete error if # - user not trying to upload a new file # - there is existing file and user is not trying to delete it # this is because removing the file may not pass validation for key in self.errors.keys(): if key in self.table \ and self.table[key].type == 'upload' \ and request_vars.get(key, None) in (None, '') \ and self.record[key] \ and not key + UploadWidget.ID_DELETE_SUFFIX in request_vars: del self.errors[key] if not self.errors: ret = True requested_delete = \ request_vars.get(self.FIELDNAME_REQUEST_DELETE, False) self.custom.end = TAG[''](self.hidden_fields(), self.custom.end) auch = record_id and self.errors and requested_delete # auch is true when user tries to delete a record # that does not pass validation, yet it should be deleted if not ret and not auch: for fieldname in self.fields: field = self.table[fieldname] ### this is a workaround! widgets should always have default not None! if not field.widget and field.type.startswith('list:') and \ not OptionsWidget.has_options(field): field.widget = self.widgets.list.widget if hasattr(field, 'widget') and field.widget and fieldname in request_vars: if fieldname in self.vars: value = self.vars[fieldname] elif self.record: value = self.record[fieldname] else: value = self.table[fieldname].default row_id = '%s_%s%s' % (self.table, fieldname, SQLFORM.ID_ROW_SUFFIX) widget = field.widget(field, value) self.field_parent[row_id].components = [ widget ] if not field.type.startswith('list:'): self.field_parent[row_id]._traverse(False, hideerror) self.custom.widget[ fieldname ] = widget return ret if record_id and str(record_id) != str(self.record_id): raise SyntaxError, 'user is tampering with form\'s record_id: ' \ '%s != %s' % (record_id, self.record_id) if record_id and dbio: if keyed: self.vars.update(record_id) else: self.vars.id = self.record.id if requested_delete and self.custom.deletable: if dbio: if keyed: qry = reduce(lambda x, y: x & y, [self.table[k] == record_id[k] for k in self.table._primarykey]) else: qry = self.table._id == self.record.id self.table._db(qry).delete() self.errors.clear() for component in self.elements('input, select, textarea'): component['_disabled'] = True return True for fieldname in self.fields: if not fieldname in self.table.fields: continue if not self.ignore_rw and not self.table[fieldname].writable: ### this happens because FORM has no knowledge of writable ### and thinks that a missing boolean field is a None if self.table[fieldname].type == 'boolean' and \ self.vars.get(fieldname, True) == None: del self.vars[fieldname] continue field = self.table[fieldname] if field.type == 'id': continue if field.type == 'boolean': if self.vars.get(fieldname, False): self.vars[fieldname] = fields[fieldname] = True else: self.vars[fieldname] = fields[fieldname] = False elif field.type == 'password' and self.record\ and request_vars.get(fieldname, None) == \ PasswordWidget.DEFAULT_PASSWORD_DISPLAY: continue # do not update if password was not changed elif field.type == 'upload': f = self.vars[fieldname] fd = '%s__delete' % fieldname if f == '' or f == None: if self.vars.get(fd, False) or not self.record: fields[fieldname] = '' else: fields[fieldname] = self.record[fieldname] self.vars[fieldname] = fields[fieldname] continue elif hasattr(f, 'file'): (source_file, original_filename) = (f.file, f.filename) elif isinstance(f, (str, unicode)): ### do not know why this happens, it should not (source_file, original_filename) = \ (cStringIO.StringIO(f), 'file.txt') newfilename = field.store(source_file, original_filename) # this line is for backward compatibility only self.vars['%s_newfilename' % fieldname] = newfilename fields[fieldname] = newfilename if isinstance(field.uploadfield, str): fields[field.uploadfield] = source_file.read() # proposed by Hamdy (accept?) do we need fields at this point? self.vars[fieldname] = fields[fieldname] continue elif fieldname in self.vars: fields[fieldname] = self.vars[fieldname] elif field.default == None and field.type != 'blob': self.errors[fieldname] = 'no data' return False value = fields.get(fieldname,None) if field.type == 'list:string': if not isinstance(value, (tuple, list)): fields[fieldname] = value and [value] or [] elif isinstance(field.type,str) and field.type.startswith('list:'): if not isinstance(value, list): fields[fieldname] = [safe_int(x) for x in (value and [value] or [])] elif field.type == 'integer': if value != None: fields[fieldname] = safe_int(value) elif field.type.startswith('reference'): if value != None and isinstance(self.table, Table) and not keyed: fields[fieldname] = safe_int(value) elif field.type == 'double': if value != None: fields[fieldname] = safe_float(value) for fieldname in self.vars: if fieldname != 'id' and fieldname in self.table.fields\ and not fieldname in fields and not fieldname\ in request_vars: fields[fieldname] = self.vars[fieldname] if dbio: if 'delete_this_record' in fields: # this should never happen but seems to happen to some del fields['delete_this_record'] for field in self.table: if not field.name in fields and field.writable==False: if record_id: fields[field.name] = self.record[field.name] elif self.table[field.name].default!=None: fields[field.name] = self.table[field.name].default if keyed: if reduce(lambda x, y: x and y, record_id.values()): # if record_id if fields: qry = reduce(lambda x, y: x & y, [self.table[k] == self.record[k] for k in self.table._primarykey]) self.table._db(qry).update(**fields) else: pk = self.table.insert(**fields) if pk: self.vars.update(pk) else: ret = False else: if record_id: self.vars.id = self.record.id if fields: self.table._db(self.table._id == self.record.id).update(**fields) else: self.vars.id = self.table.insert(**fields) return ret @staticmethod def factory(*fields, **attributes): """ generates a SQLFORM for the given fields. Internally will build a non-database based data model to hold the fields. """ # Define a table name, this way it can be logical to our CSS. # And if you switch from using SQLFORM to SQLFORM.factory # your same css definitions will still apply. table_name = attributes.get('table_name', 'no_table') # So it won't interfear with SQLDB.define_table if 'table_name' in attributes: del attributes['table_name'] return SQLFORM(DAL(None).define_table(table_name, *fields), **attributes) class SQLTABLE(TABLE): """ given a Rows object, as returned by a db().select(), generates an html table with the rows. optional arguments: :param linkto: URL (or lambda to generate a URL) to edit individual records :param upload: URL to download uploaded files :param orderby: Add an orderby link to column headers. :param headers: dictionary of headers to headers redefinions headers can also be a string to gerenare the headers from data for now only headers="fieldname:capitalize", headers="labels" and headers=None are supported :param truncate: length at which to truncate text in table cells. Defaults to 16 characters. :param columns: a list or dict contaning the names of the columns to be shown Defaults to all Optional names attributes for passed to the <table> tag The keys of headers and columns must be of the form "tablename.fieldname" Simple linkto example:: rows = db.select(db.sometable.ALL) table = SQLTABLE(rows, linkto='someurl') This will link rows[id] to .../sometable/value_of_id More advanced linkto example:: def mylink(field, type, ref): return URL(r=request, args=[field]) rows = db.select(db.sometable.ALL) table = SQLTABLE(rows, linkto=mylink) This will link rows[id] to current_app/current_controlle/current_function/value_of_id New Implements: 24 June 2011: ----------------------------- :param selectid: The id you want to select :param renderstyle: Boolean render the style with the table :param extracolums = [{'label':A('Extra',_href='#'), 'class': '', #class name of the header 'width':'', #width in pixels or % 'content':lambda row, rc: A('Edit',_href='edit/%s'%row.id), 'selected': False #agregate class selected to this column }] :param headers = {'table.id':{'label':'Id', 'class':'', #class name of the header 'width':'', #width in pixels or % 'truncate': 16, #truncate the content to... 'selected': False #agregate class selected to this column }, 'table.myfield':{'label':'My field', 'class':'', #class name of the header 'width':'', #width in pixels or % 'truncate': 16, #truncate the content to... 'selected': False #agregate class selected to this column }, } table = SQLTABLE(rows, headers=headers, extracolums=extracolums) """ def __init__( self, sqlrows, linkto=None, upload=None, orderby=None, headers={}, truncate=16, columns=None, th_link='', extracolumns=None, selectid=None, renderstyle=False, **attributes ): TABLE.__init__(self, **attributes) self.components = [] self.attributes = attributes self.sqlrows = sqlrows (components, row) = (self.components, []) if not sqlrows: return if not columns: columns = sqlrows.colnames if headers=='fieldname:capitalize': headers = {} for c in columns: headers[c] = ' '.join([w.capitalize() for w in c.split('.')[-1].split('_')]) elif headers=='labels': headers = {} for c in columns: (t,f) = c.split('.') field = sqlrows.db[t][f] headers[c] = field.label if headers!=None: for c in columns:#new implement dict if isinstance(headers.get(c, c), dict): coldict = headers.get(c, c) attrcol = dict() if coldict['width']!="": attrcol.update(_width=coldict['width']) if coldict['class']!="": attrcol.update(_class=coldict['class']) row.append(TH(coldict['label'],**attrcol)) elif orderby: row.append(TH(A(headers.get(c, c), _href=th_link+'?orderby=' + c))) else: row.append(TH(headers.get(c, c))) if extracolumns:#new implement dict for c in extracolumns: attrcol = dict() if c['width']!="": attrcol.update(_width=c['width']) if c['class']!="": attrcol.update(_class=c['class']) row.append(TH(c['label'],**attrcol)) components.append(THEAD(TR(*row))) tbody = [] for (rc, record) in enumerate(sqlrows): row = [] if rc % 2 == 0: _class = 'even' else: _class = 'odd' if selectid!=None:#new implement if record.id==selectid: _class += ' rowselected' for colname in columns: if not table_field.match(colname): if "_extra" in record and colname in record._extra: r = record._extra[colname] row.append(TD(r)) continue else: raise KeyError("Column %s not found (SQLTABLE)" % colname) (tablename, fieldname) = colname.split('.') try: field = sqlrows.db[tablename][fieldname] except KeyError: field = None if tablename in record \ and isinstance(record,Row) \ and isinstance(record[tablename],Row): r = record[tablename][fieldname] elif fieldname in record: r = record[fieldname] else: raise SyntaxError, 'something wrong in Rows object' r_old = r if not field: pass elif linkto and field.type == 'id': try: href = linkto(r, 'table', tablename) except TypeError: href = '%s/%s/%s' % (linkto, tablename, r_old) r = A(r, _href=href) elif field.type.startswith('reference'): if linkto: ref = field.type[10:] try: href = linkto(r, 'reference', ref) except TypeError: href = '%s/%s/%s' % (linkto, ref, r_old) if ref.find('.') >= 0: tref,fref = ref.split('.') if hasattr(sqlrows.db[tref],'_primarykey'): href = '%s/%s?%s' % (linkto, tref, urllib.urlencode({fref:r})) r = A(represent(field,r,record), _href=str(href)) elif field.represent: r = represent(field,r,record) elif linkto and hasattr(field._table,'_primarykey') and fieldname in field._table._primarykey: # have to test this with multi-key tables key = urllib.urlencode(dict( [ \ ((tablename in record \ and isinstance(record, Row) \ and isinstance(record[tablename], Row)) and (k, record[tablename][k])) or (k, record[k]) \ for k in field._table._primarykey ] )) r = A(r, _href='%s/%s?%s' % (linkto, tablename, key)) elif field.type.startswith('list:'): r = represent(field,r or [],record) elif field.represent: r = represent(field,r,record) elif field.type == 'blob' and r: r = 'DATA' elif field.type == 'upload': if upload and r: r = A('file', _href='%s/%s' % (upload, r)) elif r: r = 'file' else: r = '' elif field.type in ['string','text']: r = str(field.formatter(r)) ur = unicode(r, 'utf8') if headers!={}: #new implement dict if isinstance(headers[colname],dict): if isinstance(headers[colname]['truncate'], int) \ and len(ur)>headers[colname]['truncate']: r = ur[:headers[colname]['truncate'] - 3] r = r.encode('utf8') + '...' elif truncate!=None and len(ur) > truncate: r = ur[:truncate - 3].encode('utf8') + '...' attrcol = dict()#new implement dict if headers!={}: if isinstance(headers[colname],dict): colclass=headers[colname]['class'] if headers[colname]['selected']: colclass= str(headers[colname]['class'] + " colselected").strip() if colclass!="": attrcol.update(_class=colclass) row.append(TD(r,**attrcol)) if extracolumns:#new implement dict for c in extracolumns: attrcol = dict() colclass=c['class'] if c['selected']: colclass= str(c['class'] + " colselected").strip() if colclass!="": attrcol.update(_class=colclass) contentfunc = c['content'] row.append(TD(contentfunc(record, rc),**attrcol)) tbody.append(TR(_class=_class, *row)) if renderstyle: components.append(STYLE(self.style())) components.append(TBODY(*tbody)) def style(self): css = ''' table tbody tr.odd { background-color: #DFD; } table tbody tr.even { background-color: #EFE; } table tbody tr.rowselected { background-color: #FDD; } table tbody tr td.colselected { background-color: #FDD; } table tbody tr:hover { background: #DDF; } ''' return css form_factory = SQLFORM.factory # for backward compatibility, deprecated
Python
#!/usr/bin/env python """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) This file is not strictly required by web2py. It is used for three purposes: 1) check that all required modules are installed properly 2) provide py2exe and py2app a list of modules to be packaged in the binary 3) (optional) preload modules in memory to speed up http responses """ import os import sys base_modules = ['aifc', 'anydbm', 'array', 'asynchat', 'asyncore', 'atexit', 'audioop', 'base64', 'BaseHTTPServer', 'Bastion', 'binascii', 'binhex', 'bisect', 'bz2', 'calendar', 'cgi', 'CGIHTTPServer', 'cgitb', 'chunk', 'cmath', 'cmd', 'code', 'codecs', 'codeop', 'collections', 'colorsys', 'compileall', 'compiler', 'compiler.ast', 'compiler.visitor', 'ConfigParser', 'contextlib', 'Cookie', 'cookielib', 'copy', 'copy_reg', 'cPickle', 'cProfile', 'cStringIO', 'csv', 'ctypes', 'datetime', 'decimal', 'difflib', 'dircache', 'dis', 'doctest', 'DocXMLRPCServer', 'dumbdbm', 'dummy_thread', 'dummy_threading', 'email', 'email.charset', 'email.encoders', 'email.errors', 'email.generator', 'email.header', 'email.iterators', 'email.message', 'email.mime', 'email.mime.audio', 'email.mime.base', 'email.mime.image', 'email.mime.message', 'email.mime.multipart', 'email.mime.nonmultipart', 'email.mime.text', 'email.parser', 'email.utils', 'encodings.idna', 'errno', 'exceptions', 'filecmp', 'fileinput', 'fnmatch', 'formatter', 'fpformat', 'ftplib', 'functools', 'gc', 'getopt', 'getpass', 'gettext', 'glob', 'gzip', 'hashlib', 'heapq', 'hmac', 'hotshot', 'hotshot.stats', 'htmlentitydefs', 'htmllib', 'HTMLParser', 'httplib', 'imaplib', 'imghdr', 'imp', 'inspect', 'itertools', 'keyword', 'linecache', 'locale', 'logging', 'macpath', 'mailbox', 'mailcap', 'marshal', 'math', 'mimetools', 'mimetypes', 'mmap', 'modulefinder', 'mutex', 'netrc', 'new', 'nntplib', 'operator', 'optparse', 'os', 'parser', 'pdb', 'pickle', 'pickletools', 'pkgutil', 'platform', 'poplib', 'pprint', 'py_compile', 'pyclbr', 'pydoc', 'Queue', 'quopri', 'random', 're', 'repr', 'rexec', 'rfc822', 'rlcompleter', 'robotparser', 'runpy', 'sched', 'select', 'sgmllib', 'shelve', 'shlex', 'shutil', 'signal', 'SimpleHTTPServer', 'SimpleXMLRPCServer', 'site', 'smtpd', 'smtplib', 'sndhdr', 'socket', 'SocketServer', 'sqlite3', 'stat', 'statvfs', 'string', 'StringIO', 'stringprep', 'struct', 'subprocess', 'sunau', 'symbol', 'tabnanny', 'tarfile', 'telnetlib', 'tempfile', 'textwrap', 'thread', 'threading', 'time', 'timeit', 'Tix', 'Tkinter', 'token', 'tokenize', 'trace', 'traceback', 'types', 'unicodedata', 'unittest', 'urllib', 'urllib2', 'urlparse', 'user', 'UserDict', 'UserList', 'UserString', 'uu', 'uuid', 'warnings', 'wave', 'weakref', 'webbrowser', 'whichdb', 'wsgiref', 'wsgiref.handlers', 'wsgiref.headers', 'wsgiref.simple_server', 'wsgiref.util', 'wsgiref.validate', 'xdrlib', 'xml.dom', 'xml.dom.minidom', 'xml.dom.pulldom', 'xml.etree.ElementTree', 'xml.parsers.expat', 'xml.sax', 'xml.sax.handler', 'xml.sax.saxutils', 'xml.sax.xmlreader', 'xmlrpclib', 'zipfile', 'zipimport', 'zlib', 'mhlib', 'MimeWriter', 'mimify', 'multifile', 'sets'] contributed_modules = [] for root, dirs, files in os.walk('gluon'): for candidate in ['.'.join( os.path.join(root, os.path.splitext(name)[0]).split(os.sep)) for name in files if name.endswith('.py') and root.split(os.sep) != ['gluon', 'tests'] ]: contributed_modules.append(candidate) # Python base version python_version = sys.version[:3] # Modules which we want to raise an Exception if they are missing alert_dependency = ['hashlib', 'uuid'] # Now we remove the blacklisted modules if we are using the stated # python version. # # List of modules deprecated in Python 2.6 or 2.7 that are in the above set py26_deprecated = ['mhlib', 'multifile', 'mimify', 'sets', 'MimeWriter'] py27_deprecated = [] # ['optparse'] but we need it for now if python_version >= '2.6': base_modules += ['json', 'multiprocessing'] base_modules = list(set(base_modules).difference(set(py26_deprecated))) if python_version >= '2.7': base_modules += ['argparse'] base_modules = list(set(base_modules).difference(set(py27_deprecated))) # Now iterate in the base_modules, trying to do the import for module in base_modules + contributed_modules: try: __import__(module, globals(), locals(), []) except: # Raise an exception if the current module is a dependency if module in alert_dependency: msg = "Missing dependency: %(module)s\n" % locals() msg += "Try the following command: " msg += "easy_install-%(python_version)s -U %(module)s" % locals() raise ImportError, msg
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) WSGI wrapper for mod_python. Requires Python 2.2 or greater. Part of CherryPy mut modified by Massimo Di Pierro (2008) for web2py <Location /myapp> SetHandler python-program PythonHandler modpythonhandler PythonPath \"['/path/to/web2py/'] + sys.path\" PythonOption SCRIPT_NAME /myapp </Location> Some WSGI implementations assume that the SCRIPT_NAME environ variable will always be equal to 'the root URL of the app'; Apache probably won't act as you expect in that case. You can add another PythonOption directive to tell modpython_gateway to force that behavior: PythonOption SCRIPT_NAME /mcontrol The module.function will be called with no arguments on server shutdown, once for each child process or thread. """ import traceback import sys import os from mod_python import apache path = os.path.dirname(os.path.abspath(__file__)) os.chdir(path) sys.path = [path]+[p for p in sys.path if not p==path] import gluon.main class InputWrapper(object): """ Input wrapper for the wsgi handler """ def __init__(self, req): """ InputWrapper constructor """ self.req = req def close(self): """ """ pass def read(self, size=-1): """ Wrapper for req.read """ return self.req.read(size) def readline(self, size=-1): """ Wrapper for req.readline """ return self.req.readline(size) def readlines(self, hint=-1): """ Wrapper for req.readlines """ return self.req.readlines(hint) def __iter__(self): """ Defines a generator with the req data """ line = self.readline() while line: yield line # Notice this won't prefetch the next line; it only # gets called if the generator is resumed. line = self.readline() class ErrorWrapper(object): """ Error wrapper for the wsgi handler """ def __init__(self, req): """ ErrorWrapper constructor """ self.req = req def flush(self): """ """ pass def write(self, msg): """ Logs the given msg in the log file """ self.req.log_error(msg) def writelines(self, seq): """ Writes various lines in the log file """ self.write(''.join(seq)) bad_value = "You must provide a PythonOption '%s', either 'on' or 'off', when running a version of mod_python < 3.1" class Handler: """ Defines the handler """ def __init__(self, req): """ Handler constructor """ self.started = False options = req.get_options() # Threading and forking try: q = apache.mpm_query threaded = q(apache.AP_MPMQ_IS_THREADED) forked = q(apache.AP_MPMQ_IS_FORKED) except AttributeError: threaded = options.get('multithread', '').lower() if threaded == 'on': threaded = True elif threaded == 'off': threaded = False else: raise ValueError(bad_value % 'multithread') forked = options.get('multiprocess', '').lower() if forked == 'on': forked = True elif forked == 'off': forked = False else: raise ValueError(bad_value % 'multiprocess') env = self.environ = dict(apache.build_cgi_env(req)) if 'SCRIPT_NAME' in options: # Override SCRIPT_NAME and PATH_INFO if requested. env['SCRIPT_NAME'] = options['SCRIPT_NAME'] env['PATH_INFO'] = req.uri[len(options['SCRIPT_NAME']):] env['wsgi.input'] = InputWrapper(req) env['wsgi.errors'] = ErrorWrapper(req) env['wsgi.version'] = (1, 0) env['wsgi.run_once'] = False if env.get('HTTPS') in ('yes', 'on', '1'): env['wsgi.url_scheme'] = 'https' else: env['wsgi.url_scheme'] = 'http' env['wsgi.multithread'] = threaded env['wsgi.multiprocess'] = forked self.request = req def run(self, application): """ Run the application """ try: result = application(self.environ, self.start_response) for data in result: self.write(data) if not self.started: self.request.set_content_length(0) if hasattr(result, 'close'): result.close() except: traceback.print_exc(None, self.environ['wsgi.errors']) if not self.started: self.request.status = 500 self.request.content_type = 'text/plain' data = 'A server error occurred. Please contact the ' + \ 'administrator.' self.request.set_content_length(len(data)) self.request.write(data) def start_response(self, status, headers, exc_info=None): """ Defines the request data """ if exc_info: try: if self.started: raise exc_info[0], exc_info[1], exc_info[2] finally: exc_info = None self.request.status = int(status[:3]) for (key, val) in headers: if key.lower() == 'content-length': self.request.set_content_length(int(val)) elif key.lower() == 'content-type': self.request.content_type = val else: self.request.headers_out.add(key, val) return self.write def write(self, data): """ Write the request data """ if not self.started: self.started = True self.request.write(data) def handler(req): """ Execute the gluon app """ Handler(req).run(gluon.main.wsgibase) return apache.OK
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- from datetime import datetime from time import mktime from time import sleep from time import time DB_URI = 'sqlite://sessions.sqlite' EXPIRATION_MINUTES = 60 SLEEP_MINUTES = 5 while 1: # Infinite loop now = time() # get current Unix timestamp for row in db().select(db.web2py_session_welcome.ALL): t = row.modified_datetime # Convert to a Unix timestamp t = mktime(t.timetuple())+1e-6*t.microsecond if now - t > EXPIRATION_MINUTES * 60: del db.web2py_session_welcome[row.id] db.commit() # Write changes to database sleep(SLEEP_MINUTES * 60)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import time import stat import datetime from gluon.utils import md5_hash from gluon.restricted import RestrictedError SLEEP_MINUTES = 5 DB_URI = 'sqlite://tickets.db' ALLOW_DUPLICATES = True path = os.path.join(request.folder, 'errors') db = SQLDB(DB_URI) db.define_table('ticket', SQLField('app'), SQLField('name'), SQLField('date_saved', 'datetime'), SQLField('layer'), SQLField('traceback', 'text'), SQLField('code', 'text')) hashes = {} while 1: for file in os.listdir(path): filename = os.path.join(path, file) if not ALLOW_DUPLICATES: fileobj = open(filename, 'r') try: file_data = fileobj.read() finally: fileobj.close() key = md5_hash(file_data) if key in hashes: continue hashes[key] = 1 error = RestrictedError() error.load(request, request.application, filename) modified_time = os.stat(filename)[stat.ST_MTIME] modified_time = datetime.datetime.fromtimestamp(modified_time) db.ticket.insert(app=request.application, date_saved=modified_time, name=file, layer=error.layer, traceback=error.traceback, code=error.code) os.unlink(filename) db.commit() time.sleep(SLEEP_MINUTES * 60)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' @author: Pierre Thibault (pierre.thibault1 -at- gmail.com) @license: MIT @since: 2011-06-17 Usage: dict_diff [OPTION]... dict1 dict2 Show the differences for two dictionaries. -h, --help Display this help message. dict1 and dict2 are two web2py dictionary files to compare. These are the files located in the "languages" directory of a web2py app. The tools show the differences between the two files. ''' __docformat__ = "epytext en" import getopt import os.path import sys def main(argv): """Parse the arguments and start the main process.""" try: opts, args = getopt.getopt(argv, "h", ["help"]) except getopt.GetoptError: exit_with_parsing_error() for opt, arg in opts: arg = arg # To avoid a warning from Pydev if opt in ("-h", "--help"): usage() sys.exit() if len(args) == 2: params = list(get_dicts(*args)) params.extend(get_dict_names(*args)) compare_dicts(*params) else: exit_with_parsing_error() def exit_with_parsing_error(): """Report invalid arguments and usage.""" print("Invalid argument(s).") usage() sys.exit(2) def usage(): """Display the documentation""" print(__doc__) def get_dicts(dict_path1, dict_path2): """ Parse the dictionaries. @param dict_path1: The path to the first dictionary. @param dict_path2: The path to the second dictionary. @return: The two dictionaries as a sequence. """ return eval(open(dict_path1).read()), eval(open(dict_path2).read()) def get_dict_names(dict1_path, dict2_path): """ Get the name of the dictionaries for the end user. Use the base name of the files. If the two base names are identical, returns "dict1" and "dict2." @param dict1_path: The path to the first dictionary. @param dict2_path: The path to the second dictionary. @return: The two dictionary names as a sequence. """ dict1_name = os.path.basename(dict1_path) dict2_name = os.path.basename(dict2_path) if dict1_name == dict2_name: dict1_name = "dict1" dict2_name = "dict2" return dict1_name, dict2_name def compare_dicts(dict1, dict2, dict1_name, dict2_name): """ Compare the two dictionaries. Print out the result. @param dict1: The first dictionary. @param dict1: The second dictionary. @param dict1_name: The name of the first dictionary. @param dict2_name: The name of the second dictionary. """ dict1_keyset = set(dict1.keys()) dict2_keyset = set(dict2.keys()) print_key_diff(dict1_keyset - dict2_keyset, dict1_name, dict2_name) print_key_diff(dict2_keyset - dict1_keyset, dict2_name, dict1_name) print "Value differences:" has_value_differences = False for key in dict1_keyset & dict2_keyset: if dict1[key] != dict2[key]: print " %s:" % (key,) print " %s: %s" % (dict1_name, dict1[key],) print " %s: %s" % (dict2_name, dict2[key],) print has_value_differences = True if not has_value_differences: print " None" def print_key_diff(key_diff, dict1_name, dict2_name): """ Prints the keys in the first dictionary and are in the second dictionary. @param key_diff: Keys in dictionary 1 not in dictionary 2. @param dict1_name: Name used for the first dictionary. @param dict2_name: Name used for the second dictionary. """ print "Keys in %s not in %s:" % (dict1_name, dict2_name) if len(key_diff): for key in key_diff: print " %s" % (key,) else: print " None" print if __name__ == "__main__": main(sys.argv[1:]) # Start the process (without the application name)
Python
import sys, glob, os, shutil name=sys.argv[1] app=sys.argv[2] dest=sys.argv[3] a=glob.glob('applications/%(app)s/*/plugin_%(name)s.*' % dict(app=app,name=name)) b=glob.glob('applications/%(app)s/*/plugin_%(name)s/*' % dict(app=app,name=name)) for f in a: print 'cp %s ...' % f, shutil.copyfile(f,os.path.join('applications',dest,*f.split('/')[2:])) print 'done' for f in b: print 'cp %s ...' % f, path = f.split('/') for i in range(3,len(path)): try: os.mkdir(os.path.join('applications',dest,*path[2:i])) except: pass path = os.path.join('applications',dest,*f.split('/')[2:]) if os.path.isdir(f): if not os.path.exists(path): shutil.copytree(f,path) else: shutil.copyfile(f,path) print 'done'
Python