code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
# coding: utf-8
import re
def minify(response):
def _replace(match):
match = match.group()
# save whole <pre>, <textarea> tags, and opening <!-- (so it doesn't break <script>)
# otherwise, replace all whitespace with a single space character
return match if match.startswith(('<pre', '<textarea', '<!--')) else ' '
cpat = re.compile(r'\s+|<pre(.*?)</pre>|<textarea(.*?)</textarea>|<!--\s', re.DOTALL)
return cpat.sub(_replace, response)
| Python |
#!/usr/bin/env python
# -*- coding: ascii -*-
#
# Copyright 2011
# Andr\xe9 Malo or his licensors, as applicable
#
# 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.
r"""
=====================
Javascript Minifier
=====================
Javascript Minifier based on `jsmin.c by Douglas Crockford`_\.
This module is a re-implementation based on the semantics of jsmin.c. Usually
it produces the same results. It differs in the following ways:
- there is no error detection: unterminated string, regex and comment
literals are treated as regular javascript code and minified as such.
- Control characters inside string and regex literals are left untouched; they
are not converted to spaces (nor to \n)
- Newline characters are not allowed inside string and regex literals, except
for line continuations in string literals (ECMA-5).
- "return /regex/" is recognized correctly.
- rjsmin does not handle streams, but only complete strings. (However, the
module provides a "streamy" interface).
Besides the list above it differs from direct python ports of jsmin.c in
speed. Since most parts of the logic are handled by the regex engine it's way
faster than the original python port by Baruch Even. The speed factor varies
between about 6 and 55 depending on input and python version (it gets faster
the more compressed the input already is). Compared to the speed-refactored
python port by Dave St.Germain the performance gain is less dramatic but still
between 1.2 and 7. See the docs/BENCHMARKS file for details.
rjsmin.c is a reimplementation of rjsmin.py in C and speeds it up even more.
Both python 2 and python 3 are supported.
.. _jsmin.c by Douglas Crockford:
http://www.crockford.com/javascript/jsmin.c
Original author of Python version: Andr\xe9 Malo
Home page: http://opensource.perlig.de/rjsmin/
Modified by Ross Peoples <ross.peoples@gmail.com> for inclusion into web2py.
"""
__author__ = "Andr\xe9 Malo"
__author__ = getattr(__author__, 'decode', lambda x: __author__)('latin-1')
__docformat__ = "restructuredtext en"
__license__ = "Apache License, Version 2.0"
__version__ = '1.0.2'
__all__ = ['jsmin', 'jsmin_for_posers']
import re as _re
def _make_jsmin(extended=True, python_only=True):
"""
Generate JS minifier based on `jsmin.c by Douglas Crockford`_
.. _jsmin.c by Douglas Crockford:
http://www.crockford.com/javascript/jsmin.c
:Parameters:
`extended` : ``bool``
Extended Regexps? (using lookahead and lookbehind). This is faster,
because it can be optimized way more. The regexps used with `extended`
being false are only left here to allow easier porting to platforms
without extended regex features (and for my own reference...)
`python_only` : ``bool``
Use only the python variant. If true, the c extension is not even
tried to be loaded.
:Return: Minifier
:Rtype: ``callable``
"""
# pylint: disable = R0912, R0914, W0612
if not python_only:
try:
import _rjsmin
except ImportError:
pass
else:
return _rjsmin.jsmin
try:
xrange
except NameError:
xrange = range # pylint: disable = W0622
space_chars = r'[\000-\011\013\014\016-\040]'
line_comment = r'(?://[^\r\n]*)'
space_comment = r'(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/)'
string1 = \
r'(?:\047[^\047\\\r\n]*(?:\\(?:[^\r\n]|\r?\n|\r)[^\047\\\r\n]*)*\047)'
string2 = r'(?:"[^"\\\r\n]*(?:\\(?:[^\r\n]|\r?\n|\r)[^"\\\r\n]*)*")'
strings = r'(?:%s|%s)' % (string1, string2)
charclass = r'(?:\[[^\\\]\r\n]*(?:\\[^\r\n][^\\\]\r\n]*)*\])'
nospecial = r'[^/\\\[\r\n]'
if extended:
regex = r'(?:/(?![\r\n/*])%s*(?:(?:\\[^\r\n]|%s)%s*)*/)' % (
nospecial, charclass, nospecial
)
else:
regex = (
r'(?:/(?:[^*/\\\r\n\[]|%s|\\[^\r\n])%s*(?:(?:\\[^\r\n]|%s)%s*)*/)'
)
regex = regex % (charclass, nospecial, charclass, nospecial)
space = r'(?:%s|%s)' % (space_chars, space_comment)
newline = r'(?:%s?[\r\n])' % line_comment
def fix_charclass(result):
""" Fixup string of chars to fit into a regex char class """
pos = result.find('-')
if pos >= 0:
result = r'%s%s-' % (result[:pos], result[pos + 1:])
def sequentize(string):
"""
Notate consecutive characters as sequence
(1-4 instead of 1234)
"""
first, last, result = None, None, []
for char in map(ord, string):
if last is None:
first = last = char
elif last + 1 == char:
last = char
else:
result.append((first, last))
first = last = char
if last is not None:
result.append((first, last))
return ''.join(['%s%s%s' % (
chr(first),
last > first + 1 and '-' or '',
last != first and chr(last) or ''
) for first, last in result])
return _re.sub(r'([\000-\040\047])', # for better portability
lambda m: '\\%03o' % ord(m.group(1)), (sequentize(result)
.replace('\\', '\\\\')
.replace('[', '\\[')
.replace(']', '\\]')
)
)
def id_literal_(what):
""" Make id_literal like char class """
match = _re.compile(what).match
result = ''.join([
chr(c) for c in xrange(127) if not match(chr(c))
])
return '[^%s]' % fix_charclass(result)
def not_id_literal_(keep):
""" Make negated id_literal like char class """
match = _re.compile(id_literal_(keep)).match
result = ''.join([
chr(c) for c in xrange(127) if not match(chr(c))
])
return r'[%s]' % fix_charclass(result)
not_id_literal = not_id_literal_(r'[a-zA-Z0-9_$]')
preregex1 = r'[(,=:\[!&|?{};\r\n]'
preregex2 = r'%(not_id_literal)sreturn' % locals()
if extended:
id_literal = id_literal_(r'[a-zA-Z0-9_$]')
id_literal_open = id_literal_(r'[a-zA-Z0-9_${\[(+-]')
id_literal_close = id_literal_(r'[a-zA-Z0-9_$}\])"\047+-]')
space_sub = _re.compile((
r'([^\047"/\000-\040]+)'
r'|(%(strings)s[^\047"/\000-\040]*)'
r'|(?:(?<=%(preregex1)s)%(space)s*(%(regex)s[^\047"/\000-\040]*))'
r'|(?:(?<=%(preregex2)s)%(space)s*(%(regex)s[^\047"/\000-\040]*))'
r'|(?<=%(id_literal_close)s)'
r'%(space)s*(?:(%(newline)s)%(space)s*)+'
r'(?=%(id_literal_open)s)'
r'|(?<=%(id_literal)s)(%(space)s)+(?=%(id_literal)s)'
r'|%(space)s+'
r'|(?:%(newline)s%(space)s*)+'
) % locals()).sub
def space_subber(match):
""" Substitution callback """
# pylint: disable = C0321, R0911
groups = match.groups()
if groups[0]: return groups[0]
elif groups[1]: return groups[1]
elif groups[2]: return groups[2]
elif groups[3]: return groups[3]
elif groups[4]: return '\n'
elif groups[5]: return ' '
else: return ''
def jsmin(script): # pylint: disable = W0621
r"""
Minify javascript based on `jsmin.c by Douglas Crockford`_\.
Instead of parsing the stream char by char, it uses a regular
expression approach which minifies the whole script with one big
substitution regex.
.. _jsmin.c by Douglas Crockford:
http://www.crockford.com/javascript/jsmin.c
:Parameters:
`script` : ``str``
Script to minify
:Return: Minified script
:Rtype: ``str``
"""
return space_sub(space_subber, '\n%s\n' % script).strip()
else:
pre_regex = r'(?:%(preregex1)s|%(preregex2)s)' % locals()
not_id_literal_open = not_id_literal_(r'[a-zA-Z0-9_${\[(+-]')
not_id_literal_close = not_id_literal_(r'[a-zA-Z0-9_$}\])"\047+-]')
space_norm_sub = _re.compile((
r'(%(strings)s)'
r'|(?:(%(pre_regex)s)%(space)s*(%(regex)s))'
r'|(%(space)s)+'
r'|(?:(%(newline)s)%(space)s*)+'
) % locals()).sub
def space_norm_subber(match):
""" Substitution callback """
# pylint: disable = C0321
groups = match.groups()
if groups[0]: return groups[0]
elif groups[1]: return groups[1].replace('\r', '\n') + groups[2]
elif groups[3]: return ' '
elif groups[4]: return '\n'
space_sub1 = _re.compile((
r'[\040\n]?(%(strings)s|%(pre_regex)s%(regex)s)'
r'|\040(%(not_id_literal)s)'
r'|\n(%(not_id_literal_open)s)'
) % locals()).sub
def space_subber1(match):
""" Substitution callback """
groups = match.groups()
return groups[0] or groups[1] or groups[2]
space_sub2 = _re.compile((
r'(%(strings)s)\040?'
r'|(%(pre_regex)s%(regex)s)[\040\n]?'
r'|(%(not_id_literal)s)\040'
r'|(%(not_id_literal_close)s)\n'
) % locals()).sub
def space_subber2(match):
""" Substitution callback """
groups = match.groups()
return groups[0] or groups[1] or groups[2] or groups[3]
def jsmin(script):
r"""
Minify javascript based on `jsmin.c by Douglas Crockford`_\.
Instead of parsing the stream char by char, it uses a regular
expression approach. The script is minified with three passes:
normalization
Control character are mapped to spaces, spaces and newlines
are squeezed and comments are stripped.
space removal 1
Spaces before certain tokens are removed
space removal 2
Spaces after certain tokens are remove
.. _jsmin.c by Douglas Crockford:
http://www.crockford.com/javascript/jsmin.c
:Parameters:
`script` : ``str``
Script to minify
:Return: Minified script
:Rtype: ``str``
"""
return space_sub2(space_subber2,
space_sub1(space_subber1,
space_norm_sub(space_norm_subber, '\n%s\n' % script)
)
).strip()
return jsmin
jsmin = _make_jsmin()
#####################
# EXAMPLE USAGE #
#####################
#
# import jsmin
# jsmin.jsmin(script)
#
def jsmin_for_posers(script):
r"""
Minify javascript based on `jsmin.c by Douglas Crockford`_\.
Instead of parsing the stream char by char, it uses a regular
expression approach which minifies the whole script with one big
substitution regex.
.. _jsmin.c by Douglas Crockford:
http://www.crockford.com/javascript/jsmin.c
:Warning: This function is the digest of a _make_jsmin() call. It just
utilizes the resulting regex. It's just for fun here and may
vanish any time. Use the `jsmin` function instead.
:Parameters:
`script` : ``str``
Script to minify
:Return: Minified script
:Rtype: ``str``
"""
def subber(match):
""" Substitution callback """
groups = match.groups()
return (
groups[0] or
groups[1] or
groups[2] or
groups[3] or
(groups[4] and '\n') or
(groups[5] and ' ') or
''
)
return _re.sub(
r'([^\047"/\000-\040]+)|((?:(?:\047[^\047\\\r\n]*(?:\\(?:[^\r\n]|\r?'
r'\n|\r)[^\047\\\r\n]*)*\047)|(?:"[^"\\\r\n]*(?:\\(?:[^\r\n]|\r?\n|'
r'\r)[^"\\\r\n]*)*"))[^\047"/\000-\040]*)|(?:(?<=[(,=:\[!&|?{};\r\n]'
r')(?:[\000-\011\013\014\016-\040]|(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/'
r'))*((?:/(?![\r\n/*])[^/\\\[\r\n]*(?:(?:\\[^\r\n]|(?:\[[^\\\]\r\n]*'
r'(?:\\[^\r\n][^\\\]\r\n]*)*\]))[^/\\\[\r\n]*)*/)[^\047"/\000-\040]*'
r'))|(?:(?<=[\000-#%-,./:-@\[-^`{-~-]return)(?:[\000-\011\013\014\01'
r'6-\040]|(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/))*((?:/(?![\r\n/*])[^/'
r'\\\[\r\n]*(?:(?:\\[^\r\n]|(?:\[[^\\\]\r\n]*(?:\\[^\r\n][^\\\]\r\n]'
r'*)*\]))[^/\\\[\r\n]*)*/)[^\047"/\000-\040]*))|(?<=[^\000-!#%&(*,./'
r':-@\[\\^`{|~])(?:[\000-\011\013\014\016-\040]|(?:/\*[^*]*\*+(?:[^/'
r'*][^*]*\*+)*/))*(?:((?:(?://[^\r\n]*)?[\r\n]))(?:[\000-\011\013\01'
r'4\016-\040]|(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/))*)+(?=[^\000-#%-\04'
r'7)*,./:-@\\-^`|-~])|(?<=[^\000-#%-,./:-@\[-^`{-~-])((?:[\000-\011'
r'\013\014\016-\040]|(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/)))+(?=[^\000-'
r'#%-,./:-@\[-^`{-~-])|(?:[\000-\011\013\014\016-\040]|(?:/\*[^*]*\*'
r'+(?:[^/*][^*]*\*+)*/))+|(?:(?:(?://[^\r\n]*)?[\r\n])(?:[\000-\011'
r'\013\014\016-\040]|(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/))*)+',
subber, '\n%s\n' % script
).strip()
if __name__ == '__main__':
import sys as _sys
_sys.stdout.write(jsmin(_sys.stdin.read()))
| 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 |
"""
Developed by 616d41631bff906704951934ffe4015e
Released under web2py license because includes gluon/cache.py source code
"""
import redis
from redis.exceptions import ConnectionError
from gluon import current
from gluon.cache import CacheAbstract
import cPickle as pickle
import time
import re
import logging
import thread
logger = logging.getLogger("web2py.cache.redis")
locker = thread.allocate_lock()
def RedisCache(*args, **vars):
"""
Usage example: put in models
from gluon.contrib.redis_cache import RedisCache
cache.redis = RedisCache('localhost:6379',db=None, debug=True)
cache.redis.stats()
return a dictionary with statistics of Redis server
with one additional key ('w2p_keys') showing all keys currently set
from web2py with their TTL
if debug=True additional tracking is activate and another key is added
('w2p_stats') showing total_hits and misses
"""
locker.acquire()
try:
if not hasattr(RedisCache, 'redis_instance'):
RedisCache.redis_instance = RedisClient(*args, **vars)
finally:
locker.release()
return RedisCache.redis_instance
class RedisClient(object):
meta_storage = {}
MAX_RETRIES = 5
RETRIES = 0
def __init__(self, server='localhost:6379', db=None, debug=False):
self.server = server
self.db = db or 0
host,port = (self.server.split(':')+['6379'])[:2]
port = int(port)
self.request = current.request
self.debug = debug
if self.request:
app = self.request.application
else:
app = ''
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]
self.r_server = redis.Redis(host=host, port=port, db=self.db)
def __call__(self, key, f, time_expire=300):
try:
if time_expire == None:
time_expire = 24*60*60
newKey = self.__keyFormat__(key)
value = None
obj = self.r_server.get(newKey)
ttl = self.r_server.ttl(newKey) or 0
if ttl > time_expire:
obj = None
if obj:
if self.debug:
self.r_server.incr('web2py_cache_statistics:hit_total')
value = pickle.loads(obj)
elif f is None:
self.r_server.delete(newKey)
else:
if self.debug:
self.r_server.incr('web2py_cache_statistics:misses')
value = f()
if time_expire == 0:
time_expire = 1
self.r_server.setex(newKey, pickle.dumps(value), time_expire)
return value
except ConnectionError:
return self.retry_call(key, f, time_expire)
def retry_call(self, key, f, time_expire):
self.RETRIES += 1
if self.RETRIES <= self.MAX_RETRIES:
logger.error("sleeping %s seconds before reconnecting" % (2 * self.RETRIES))
time.sleep(2 * self.RETRIES)
self.__init__(self.server, self.db, self.debug)
return self.__call__(key, f, time_expire)
else:
self.RETRIES = 0
raise ConnectionError , 'Redis instance is unavailable at %s' % (self.server)
def increment(self, key, value=1, time_expire=300):
try:
newKey = self.__keyFormat__(key)
obj = self.r_server.get(newKey)
if obj:
return self.r_server.incr(newKey, value)
else:
self.r_server.setex(newKey, value, time_expire)
return value
except ConnectionError:
return self.retry_increment(key, value, time_expire)
def retry_increment(self, key, value, time_expire):
self.RETRIES += 1
if self.RETRIES <= self.MAX_RETRIES:
logger.error("sleeping some seconds before reconnecting")
time.sleep(2 * self.RETRIES)
self.__init__(self.server, self.db, self.debug)
return self.increment(key, value, time_expire)
else:
self.RETRIES = 0
raise ConnectionError , 'Redis instance is unavailable at %s' % (self.server)
def clear(self, regex):
"""
Auxiliary function called by `clear` to search and
clear cache entries
"""
r = re.compile(regex)
prefix = "w2p:%s:" % (self.request.application)
pipe = self.r_server.pipeline()
for a in self.r_server.keys("%s*" % \
(prefix)):
if r.match(str(a).replace(prefix, '', 1)):
pipe.delete(a)
pipe.execute()
def stats(self):
statscollector = self.r_server.info()
if self.debug:
statscollector['w2p_stats'] = dict(
hit_total = self.r_server.get(
'web2py_cache_statistics:hit_total'),
misses=self.r_server.get('web2py_cache_statistics:misses')
)
statscollector['w2p_keys'] = dict()
for a in self.r_server.keys("w2p:%s:*" % (
self.request.application)):
statscollector['w2p_keys']["%s_expire_in_sec" % (a)] = \
self.r_server.ttl(a)
return statscollector
def __keyFormat__(self, key):
return 'w2p:%s:%s' % (self.request.application,
key.replace(' ', '_'))
| 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, **kwargs):
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.font_face="times" # initialize font
self.color=0 # initialize font color
self.set_font(kwargs.get("font","times"), kwargs.get("fontsize",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 = self.td.get('align', 'C')[0].upper()
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:
size = int(attrs.get('size'))
self.pdf.set_font(self.font_face, size=int(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_face:
self.set_font('Times',12)
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, **kwargs):
"Parse HTML and convert it to PDF"
h2p = HTML2FPDF(self,image_map=image_map,**kwargs)
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
"""
TODO: next version should use MathJax
<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js">
MathJax.Hub.Config({
extensions: ["tex2jax.js","TeX/AMSmath.js","TeX/AMSsymbols.js"],
jax: ["input/TeX", "output/HTML-CSS"],
tex2jax: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
},
"HTML-CSS": { availableFonts: ["TeX"] }
});
</script>
"""
__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" />'
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" />'
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\*]+)*)\*\*'),'<strong>\g<t></strong>'),
(re.compile("''(?P<t>[^\s']+( +[^\s']+)*)''"),'<em>\g<t></em>'),
(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_center_width = re.compile('\[\[(?P<t>[^\]]*?) +(?P<k>\S+) +center +(?P<w>\d+px)\]\]')
regex_image_width = re.compile('\[\[(?P<t>[^\]]*?) +(?P<k>\S+) +(?P<p>left|right) +(?P<w>\d+px)\]\]')
regex_image_center = re.compile('\[\[(?P<t>[^\]]*?) +(?P<k>\S+) +center\]\]')
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_qr = re.compile('(?<!["\w\>/=])qr:(?P<k>\w+://[\w\.\-\+\?&%\/\:]+)',re.M)
regex_embed = re.compile('(?<!["\w\>/=])embed:(?P<k>\w+://[\w\.\-\+\?&%\/\:]+)',re.M)
regex_auto_image = re.compile('(?<!["\w\>/=])(?P<k>\w+://\S+\.(jpeg|jpg|gif|png)(\?\S+)?)',re.M)
regex_auto_video = re.compile('(?<!["\w\>/=])(?P<k>\w+://\S+\.(mp4|mpeg|mov)(\?\S+)?)',re.M)
regex_auto_audio = re.compile('(?<!["\w\>/=])(?P<k>\w+://\S+\.(mp3|wav)(\?\S+)?)',re.M)
regex_auto = re.compile('(?<!["\w\>/=])(?P<k>\w+://\S+)',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><strong>hello world</strong></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><em>hello world</em></p>'
>>> render('** hello** **world**')
'<p>** hello** <strong>world</strong></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 <strong>link</strong></a></p>'
>>> render("``aaa``:custom",extra=dict(custom=lambda text: 'x'+text+'x'))
'xaaax'
>>> print render(r"$$\int_a^b sin(x)dx$$")
<img src="http://chart.apis.google.com/chart?cht=tx&chl=\\int_a^b sin(x)dx" />
"""
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>\n' + text[item.end():]
else:
text = text[:item.start()] + '<<blockquote class="%s">'%c + content + '</blockquote>\n' + text[item.end():]
#############################################################
# deal with images, videos, audios and links
#############################################################
text = regex_anchor.sub('<span id="\g<t>"><span>', text)
text = regex_image_center_width.sub('<p align="center"><img src="\g<k>" alt="\g<t>" width="\g<w>" /></p>', text)
text = regex_image_width.sub('<img src="\g<k>" alt="\g<t>" align="\g<p>" width="\g<w>" />', text)
text = regex_image_center.sub('<p align="center"><img src="\g<k>" alt="\g<t>" /></p>', 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_qr.sub('<img width="80px" src="http://qrcode.kaywa.com/img.php?s=8&d=\g<k>" alt="qr code" />',text)
text = regex_embed.sub('<iframe src="\g<k>" frameborder="0" allowfullscreen></iframe>',
text)
text = regex_auto_image.sub('<img src="\g<k>" controls />', text)
text = regex_auto_video.sub('<video src="\g<k>" controls></video>', text)
text = regex_auto_audio.sub('<audio src="\g<k>" controls></audio>', 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.strip())
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,
chapters=False):
#############################################################
# 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)
if chapters:
text=text.replace(r'\section*{',r'\chapter*{')
text=text.replace(r'\section{',r'\chapter{')
text=text.replace(r'subsection{',r'section{')
#############################################################
# 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("-c", "--chapters", dest="chapters",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,
chapters=options.chapters)
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 |
from gluon import XML
def button(merchant_id="123456789012345",
products=[dict(name="shoes",
quantity=1,
price=23.5,
currency='USD',
description="running shoes black")]):
t = '<input name="item_%(key)s_%(k)s" type="hidden" value="%(value)s"/>'
list_products = ''
for k,product in enumerate(products):
for key,value in product.items():
list_products += t % dict(k=k+1,key=key,value=value)
button = '<form action="https://checkout.google.com/api/checkout/v2/checkoutForm/Merchant/%s" id="BB_BuyButtonForm" method="post" name="BB_BuyButtonForm" target="_top">%s<input name="_charset_" type="hidden" value="utf-8"/><input alt="" src="https://checkout.google.com/buttons/buy.gif?merchant_id=%s&w=117&h=48&style=white&variant=text&loc=en_US" type="image"/></form>' % (merchant_id, list_products, merchant_id)
return XML(button)
| 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 = Client.get(self, newKey)
if obj:
return Client.incr(self, newKey, value)
else:
Client.set(self, 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 |
# vim: sw=4:expandtab:foldmethod=marker
#
# Copyright (c) 2007-2009, Mathieu Fenniak
# 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.
# * The name of the author may not be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# 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__ = "Mathieu Fenniak"
__version__ = "1.10"
import datetime
import time
import interface
import types
import threading
from errors import *
from warnings import warn
##
# The DBAPI level supported. Currently 2.0. This property is part of the
# DBAPI 2.0 specification.
apilevel = "2.0"
##
# Integer constant stating the level of thread safety the DBAPI interface
# supports. This DBAPI interface supports sharing of the module, connections,
# and cursors. This property is part of the DBAPI 2.0 specification.
threadsafety = 3
##
# String property stating the type of parameter marker formatting expected by
# the interface. This value defaults to "format". This property is part of
# the DBAPI 2.0 specification.
# <p>
# Unlike the DBAPI specification, this value is not constant. It can be
# changed to any standard paramstyle value (ie. qmark, numeric, named, format,
# and pyformat).
paramstyle = 'format' # paramstyle can be changed to any DB-API paramstyle
def convert_paramstyle(src_style, query, args):
# I don't see any way to avoid scanning the query string char by char,
# so we might as well take that careful approach and create a
# state-based scanner. We'll use int variables for the state.
# 0 -- outside quoted string
# 1 -- inside single-quote string '...'
# 2 -- inside quoted identifier "..."
# 3 -- inside escaped single-quote string, E'...'
state = 0
output_query = ""
output_args = []
if src_style == "numeric":
output_args = args
elif src_style in ("pyformat", "named"):
mapping_to_idx = {}
i = 0
while 1:
if i == len(query):
break
c = query[i]
# print "begin loop", repr(i), repr(c), repr(state)
if state == 0:
if c == "'":
i += 1
output_query += c
state = 1
elif c == '"':
i += 1
output_query += c
state = 2
elif c == 'E':
# check for escaped single-quote string
i += 1
if i < len(query) and i > 1 and query[i] == "'":
i += 1
output_query += "E'"
state = 3
else:
output_query += c
elif src_style == "qmark" and c == "?":
i += 1
param_idx = len(output_args)
if param_idx == len(args):
raise QueryParameterIndexError("too many parameter fields, not enough parameters")
output_args.append(args[param_idx])
output_query += "$" + str(param_idx + 1)
elif src_style == "numeric" and c == ":":
i += 1
if i < len(query) and i > 1 and query[i].isdigit():
output_query += "$" + query[i]
i += 1
else:
raise QueryParameterParseError("numeric parameter : does not have numeric arg")
elif src_style == "named" and c == ":":
name = ""
while 1:
i += 1
if i == len(query):
break
c = query[i]
if c.isalnum() or c == '_':
name += c
else:
break
if name == "":
raise QueryParameterParseError("empty name of named parameter")
idx = mapping_to_idx.get(name)
if idx == None:
idx = len(output_args)
output_args.append(args[name])
idx += 1
mapping_to_idx[name] = idx
output_query += "$" + str(idx)
elif src_style == "format" and c == "%":
i += 1
if i < len(query) and i > 1:
if query[i] == "s":
param_idx = len(output_args)
if param_idx == len(args):
raise QueryParameterIndexError("too many parameter fields, not enough parameters")
output_args.append(args[param_idx])
output_query += "$" + str(param_idx + 1)
elif query[i] == "%":
output_query += "%"
else:
raise QueryParameterParseError("Only %s and %% are supported")
i += 1
else:
raise QueryParameterParseError("format parameter % does not have format code")
elif src_style == "pyformat" and c == "%":
i += 1
if i < len(query) and i > 1:
if query[i] == "(":
i += 1
# begin mapping name
end_idx = query.find(')', i)
if end_idx == -1:
raise QueryParameterParseError("began pyformat dict read, but couldn't find end of name")
else:
name = query[i:end_idx]
i = end_idx + 1
if i < len(query) and query[i] == "s":
i += 1
idx = mapping_to_idx.get(name)
if idx == None:
idx = len(output_args)
output_args.append(args[name])
idx += 1
mapping_to_idx[name] = idx
output_query += "$" + str(idx)
else:
raise QueryParameterParseError("format not specified or not supported (only %(...)s supported)")
elif query[i] == "%":
output_query += "%"
elif query[i] == "s":
# we have a %s in a pyformat query string. Assume
# support for format instead.
i -= 1
src_style = "format"
else:
raise QueryParameterParseError("Only %(name)s, %s and %% are supported")
else:
i += 1
output_query += c
elif state == 1:
output_query += c
i += 1
if c == "'":
# Could be a double ''
if i < len(query) and query[i] == "'":
# is a double quote.
output_query += query[i]
i += 1
else:
state = 0
elif src_style in ("pyformat","format") and c == "%":
# hm... we're only going to support an escaped percent sign
if i < len(query):
if query[i] == "%":
# good. We already output the first percent sign.
i += 1
else:
raise QueryParameterParseError("'%" + query[i] + "' not supported in quoted string")
elif state == 2:
output_query += c
i += 1
if c == '"':
state = 0
elif src_style in ("pyformat","format") and c == "%":
# hm... we're only going to support an escaped percent sign
if i < len(query):
if query[i] == "%":
# good. We already output the first percent sign.
i += 1
else:
raise QueryParameterParseError("'%" + query[i] + "' not supported in quoted string")
elif state == 3:
output_query += c
i += 1
if c == "\\":
# check for escaped single-quote
if i < len(query) and query[i] == "'":
output_query += "'"
i += 1
elif c == "'":
state = 0
elif src_style in ("pyformat","format") and c == "%":
# hm... we're only going to support an escaped percent sign
if i < len(query):
if query[i] == "%":
# good. We already output the first percent sign.
i += 1
else:
raise QueryParameterParseError("'%" + query[i] + "' not supported in quoted string")
return output_query, tuple(output_args)
def require_open_cursor(fn):
def _fn(self, *args, **kwargs):
if self.cursor == None:
raise CursorClosedError()
return fn(self, *args, **kwargs)
return _fn
##
# The class of object returned by the {@link #ConnectionWrapper.cursor cursor method}.
class CursorWrapper(object):
def __init__(self, conn, connection):
self.cursor = interface.Cursor(conn)
self.arraysize = 1
self._connection = connection
self._override_rowcount = None
##
# This read-only attribute returns a reference to the connection object on
# which the cursor was created.
# <p>
# Stability: Part of a DBAPI 2.0 extension. A warning "DB-API extension
# cursor.connection used" will be fired.
connection = property(lambda self: self._getConnection())
def _getConnection(self):
warn("DB-API extension cursor.connection used", stacklevel=3)
return self._connection
##
# This read-only attribute specifies the number of rows that the last
# .execute*() produced (for DQL statements like 'select') or affected (for
# DML statements like 'update' or 'insert').
# <p>
# The attribute is -1 in case no .execute*() has been performed on the
# cursor or the rowcount of the last operation is cannot be determined by
# the interface.
# <p>
# Stability: Part of the DBAPI 2.0 specification.
rowcount = property(lambda self: self._getRowCount())
@require_open_cursor
def _getRowCount(self):
if self._override_rowcount != None:
return self._override_rowcount
return self.cursor.row_count
##
# This read-only attribute is a sequence of 7-item sequences. Each value
# contains information describing one result column. The 7 items returned
# for each column are (name, type_code, display_size, internal_size,
# precision, scale, null_ok). Only the first two values are provided by
# this interface implementation.
# <p>
# Stability: Part of the DBAPI 2.0 specification.
description = property(lambda self: self._getDescription())
@require_open_cursor
def _getDescription(self):
if self.cursor.row_description == None:
return None
columns = []
for col in self.cursor.row_description:
columns.append((col["name"], col["type_oid"], None, None, None, None, None))
return columns
##
# Executes a database operation. Parameters may be provided as a sequence
# or mapping and will be bound to variables in the operation.
# <p>
# Stability: Part of the DBAPI 2.0 specification.
@require_open_cursor
def execute(self, operation, args=()):
if not self._connection.in_transaction:
self._connection.begin()
self._override_rowcount = None
self._execute(operation, args)
def _execute(self, operation, args=()):
new_query, new_args = convert_paramstyle(paramstyle, operation, args)
try:
self.cursor.execute(new_query, *new_args)
except ConnectionClosedError:
# can't rollback in this case
raise
except:
# any error will rollback the transaction to-date
self._connection.rollback()
raise
def copy_from(self, fileobj, table=None, sep='\t', null=None, query=None):
if query == None:
if table == None:
raise CopyQueryOrTableRequiredError()
query = "COPY %s FROM stdout DELIMITER '%s'" % (table, sep)
if null is not None:
query += " NULL '%s'" % (null,)
self.copy_execute(fileobj, query)
def copy_to(self, fileobj, table=None, sep='\t', null=None, query=None):
if query == None:
if table == None:
raise CopyQueryOrTableRequiredError()
query = "COPY %s TO stdout DELIMITER '%s'" % (table, sep)
if null is not None:
query += " NULL '%s'" % (null,)
self.copy_execute(fileobj, query)
@require_open_cursor
def copy_execute(self, fileobj, query):
try:
self.cursor.execute(query, stream=fileobj)
except ConnectionClosedError:
# can't rollback in this case
raise
except:
# any error will rollback the transaction to-date
import traceback; traceback.print_exc()
self._connection.rollback()
raise
##
# Prepare a database operation and then execute it against all parameter
# sequences or mappings provided.
# <p>
# Stability: Part of the DBAPI 2.0 specification.
@require_open_cursor
def executemany(self, operation, parameter_sets):
if not self._connection.in_transaction:
self._connection.begin()
self._override_rowcount = 0
for parameters in parameter_sets:
self._execute(operation, parameters)
if self.cursor.row_count == -1 or self._override_rowcount == -1:
self._override_rowcount = -1
else:
self._override_rowcount += self.cursor.row_count
##
# Fetch the next row of a query result set, returning a single sequence, or
# None when no more data is available.
# <p>
# Stability: Part of the DBAPI 2.0 specification.
@require_open_cursor
def fetchone(self):
return self.cursor.read_tuple()
##
# Fetch the next set of rows of a query result, returning a sequence of
# sequences. An empty sequence is returned when no more rows are
# available.
# <p>
# Stability: Part of the DBAPI 2.0 specification.
# @param size The number of rows to fetch when called. If not provided,
# the arraysize property value is used instead.
def fetchmany(self, size=None):
if size == None:
size = self.arraysize
rows = []
for i in range(size):
value = self.fetchone()
if value == None:
break
rows.append(value)
return rows
##
# Fetch all remaining rows of a query result, returning them as a sequence
# of sequences.
# <p>
# Stability: Part of the DBAPI 2.0 specification.
@require_open_cursor
def fetchall(self):
return tuple(self.cursor.iterate_tuple())
##
# Close the cursor.
# <p>
# Stability: Part of the DBAPI 2.0 specification.
@require_open_cursor
def close(self):
self.cursor.close()
self.cursor = None
self._override_rowcount = None
def next(self):
warn("DB-API extension cursor.next() used", stacklevel=2)
retval = self.fetchone()
if retval == None:
raise StopIteration()
return retval
def __iter__(self):
warn("DB-API extension cursor.__iter__() used", stacklevel=2)
return self
def setinputsizes(self, sizes):
pass
def setoutputsize(self, size, column=None):
pass
@require_open_cursor
def fileno(self):
return self.cursor.fileno()
@require_open_cursor
def isready(self):
return self.cursor.isready()
def require_open_connection(fn):
def _fn(self, *args, **kwargs):
if self.conn == None:
raise ConnectionClosedError()
return fn(self, *args, **kwargs)
return _fn
##
# The class of object returned by the {@link #connect connect method}.
class ConnectionWrapper(object):
# DBAPI Extension: supply exceptions as attributes on the connection
Warning = property(lambda self: self._getError(Warning))
Error = property(lambda self: self._getError(Error))
InterfaceError = property(lambda self: self._getError(InterfaceError))
DatabaseError = property(lambda self: self._getError(DatabaseError))
OperationalError = property(lambda self: self._getError(OperationalError))
IntegrityError = property(lambda self: self._getError(IntegrityError))
InternalError = property(lambda self: self._getError(InternalError))
ProgrammingError = property(lambda self: self._getError(ProgrammingError))
NotSupportedError = property(lambda self: self._getError(NotSupportedError))
def _getError(self, error):
warn("DB-API extension connection.%s used" % error.__name__, stacklevel=3)
return error
@property
def in_transaction(self):
if self.conn:
return self.conn.in_transaction
return False
def __init__(self, **kwargs):
self.conn = interface.Connection(**kwargs)
self.notifies = []
self.notifies_lock = threading.Lock()
self.conn.NotificationReceived += self._notificationReceived
# Two Phase Commit internal attributes:
self.__tpc_xid = None
self.__tpc_prepared = None
def set_autocommit(self, state):
if self.conn.in_transaction and state and not self.conn.autocommit:
warn("enabling autocommit in an open transaction!")
self.conn.autocommit = state
def get_autocommit(self):
return self.conn.autocommit
autocommit = property(get_autocommit, set_autocommit)
@require_open_connection
def begin(self):
self.conn.begin()
def _notificationReceived(self, notice):
try:
# psycopg2 compatible notification interface
self.notifies_lock.acquire()
self.notifies.append((notice.backend_pid, notice.condition))
finally:
self.notifies_lock.release()
##
# Creates a {@link #CursorWrapper CursorWrapper} object bound to this
# connection.
# <p>
# Stability: Part of the DBAPI 2.0 specification.
@require_open_connection
def cursor(self):
return CursorWrapper(self.conn, self)
##
# Commits the current database transaction.
# <p>
# Stability: Part of the DBAPI 2.0 specification.
@require_open_connection
def commit(self):
# There's a threading bug here. If a query is sent after the
# commit, but before the begin, it will be executed immediately
# without a surrounding transaction. Like all threading bugs -- it
# sounds unlikely, until it happens every time in one
# application... however, to fix this, we need to lock the
# database connection entirely, so that no cursors can execute
# statements on other threads. Support for that type of lock will
# be done later.
if self.__tpc_xid:
raise ProgrammingError("Cannot do a normal commit() inside a "
"TPC transaction!")
self.conn.commit()
##
# Rolls back the current database transaction.
# <p>
# Stability: Part of the DBAPI 2.0 specification.
@require_open_connection
def rollback(self):
# see bug description in commit.
if self.__tpc_xid:
raise ProgrammingError("Cannot do a normal rollback() inside a "
"TPC transaction!")
self.conn.rollback()
##
# Closes the database connection.
# <p>
# Stability: Part of the DBAPI 2.0 specification.
@require_open_connection
def close(self):
self.conn.close()
self.conn = None
##
# Returns the "server_version" string provided by the connected server.
# <p>
# Stability: Extension of the DBAPI 2.0 specification.
@property
@require_open_connection
def server_version(self):
return self.conn.server_version()
# Stability: psycopg2 compatibility
@require_open_connection
def set_client_encoding(self, encoding=None):
"Set the client encoding for the current session"
if encoding:
self.conn.execute("SET client_encoding TO '%s';" % (encoding, ), simple_query=True)
return self.conn.encoding()
def xid(self,format_id, global_transaction_id, branch_qualifier):
"""Create a Transaction IDs (only global_transaction_id is used in pg)
format_id and branch_qualifier are not used in postgres
global_transaction_id may be any string identifier supported by postgres
returns a tuple (format_id, global_transaction_id, branch_qualifier)"""
return (format_id, global_transaction_id, branch_qualifier)
@require_open_connection
def tpc_begin(self,xid):
"Begin a two-phase transaction"
# set auto-commit mode to begin a TPC transaction
self.autocommit = False
# (actually in postgres at this point it is a normal one)
if self.conn.in_transaction:
warn("tpc_begin() should be called outside a transaction block",
stacklevel=3)
self.conn.begin()
# store actual TPC transaction id
self.__tpc_xid = xid
self.__tpc_prepared = False
@require_open_connection
def tpc_prepare(self):
"Prepare a two-phase transaction"
if not self.__tpc_xid:
raise ProgrammingError("tpc_prepare() outside a TPC transaction "
"is not allowed!")
# Prepare the TPC
self.conn.execute("PREPARE TRANSACTION '%s';" % (self.__tpc_xid[1],),
simple_query=True)
self.conn.in_transaction = False
self.__tpc_prepared = True
@require_open_connection
def tpc_commit(self, xid=None):
"Commit a prepared two-phase transaction"
try:
# save current autocommit status (to be recovered later)
previous_autocommit_mode = self.autocommit
if not xid:
# use current tpc transaction
tpc_xid = self.__tpc_xid
else:
# use a recovered tpc transaction
tpc_xid = xid
if not xid in self.tpc_recover():
raise ProgrammingError("Requested TPC transaction is not "
"prepared!")
if not tpc_xid:
raise ProgrammingError("Cannot tpc_commit() without a TPC "
"transaction!")
if self.__tpc_prepared or (xid != self.__tpc_xid and xid):
# a two-phase commit:
# set the auto-commit mode for TPC commit
self.autocommit = True
try:
self.conn.execute("COMMIT PREPARED '%s';" % (tpc_xid[1], ),
simple_query=True)
finally:
# return to previous auto-commit mode
self.autocommit = previous_autocommit_mode
else:
try:
# a single-phase commit
self.conn.commit()
finally:
# return to previous auto-commit mode
self.autocommit = previous_autocommit_mode
finally:
# transaction is done, clear xid
self.__tpc_xid = None
@require_open_connection
def tpc_rollback(self, xid=None):
"Commit a prepared two-phase transaction"
try:
# save current autocommit status (to be recovered later)
previous_autocommit_mode = self.autocommit
if not xid:
# use current tpc transaction
tpc_xid = self.__tpc_xid
else:
# use a recovered tpc transaction
tpc_xid = xid
if not xid in self.tpc_recover():
raise ProgrammingError("Requested TPC transaction is not prepared!")
if not tpc_xid:
raise ProgrammingError("Cannot tpc_rollback() without a TPC prepared transaction!")
if self.__tpc_prepared or (xid != self.__tpc_xid and xid):
# a two-phase rollback
# set auto-commit for the TPC rollback
self.autocommit = True
try:
self.conn.execute("ROLLBACK PREPARED '%s';" % (tpc_xid[1],),
simple_query=True)
finally:
# return to previous auto-commit mode
self.autocommit = previous_autocommit_mode
else:
# a single-phase rollback
try:
self.conn.rollback()
finally:
# return to previous auto-commit mode
self.autocommit = previous_autocommit_mode
finally:
# transaction is done, clear xid
self.__tpc_xid = None
@require_open_connection
def tpc_recover(self):
"Returns a list of pending transaction IDs"
previous_autocommit_mode = self.autocommit
if not self.conn.in_transaction and not self.autocommit:
self.autocommit = True
elif not self.autocommit:
warn("tpc_recover() will open a transaction block", stacklevel=3)
curs = self.cursor()
xids = []
try:
# query system view that stores open (prepared) TPC transactions
curs.execute("SELECT gid FROM pg_prepared_xacts;");
xids.extend([self.xid(0,row[0],'') for row in curs])
finally:
curs.close()
# return to previous auto-commit mode
self.autocommit = previous_autocommit_mode
# return a list of TPC transaction ids (xid)
return xids
##
# Creates a DBAPI 2.0 compatible interface to a PostgreSQL database.
# <p>
# Stability: Part of the DBAPI 2.0 specification.
#
# @param user The username to connect to the PostgreSQL server with. This
# parameter is required.
#
# @keyparam host The hostname of the PostgreSQL server to connect with.
# Providing this parameter is necessary for TCP/IP connections. One of either
# host, or unix_sock, must be provided.
#
# @keyparam unix_sock The path to the UNIX socket to access the database
# through, for example, '/tmp/.s.PGSQL.5432'. One of either unix_sock or host
# must be provided. The port parameter will have no affect if unix_sock is
# provided.
#
# @keyparam port The TCP/IP port of the PostgreSQL server instance. This
# parameter defaults to 5432, the registered and common port of PostgreSQL
# TCP/IP servers.
#
# @keyparam database The name of the database instance to connect with. This
# parameter is optional, if omitted the PostgreSQL server will assume the
# database name is the same as the username.
#
# @keyparam password The user password to connect to the server with. This
# parameter is optional. If omitted, and the database server requests password
# based authentication, the connection will fail. On the other hand, if this
# parameter is provided and the database does not request password
# authentication, then the password will not be used.
#
# @keyparam socket_timeout Socket connect timeout measured in seconds.
# Defaults to 60 seconds.
#
# @keyparam ssl Use SSL encryption for TCP/IP socket. Defaults to False.
#
# @return An instance of {@link #ConnectionWrapper ConnectionWrapper}.
def connect(dsn="", user=None, host=None, unix_sock=None, port=5432, database=None, password=None, socket_timeout=60, ssl=False):
return ConnectionWrapper(dsn=dsn, user=user, host=host,
unix_sock=unix_sock, port=port, database=database,
password=password, socket_timeout=socket_timeout, ssl=ssl)
def Date(year, month, day):
return datetime.date(year, month, day)
def Time(hour, minute, second):
return datetime.time(hour, minute, second)
def Timestamp(year, month, day, hour, minute, second):
return datetime.datetime(year, month, day, hour, minute, second)
def DateFromTicks(ticks):
return Date(*time.localtime(ticks)[:3])
def TimeFromTicks(ticks):
return Time(*time.localtime(ticks)[3:6])
def TimestampFromTicks(ticks):
return Timestamp(*time.localtime(ticks)[:6])
##
# Construct an object holding binary data.
def Binary(value):
return types.Bytea(value)
# I have no idea what this would be used for by a client app. Should it be
# TEXT, VARCHAR, CHAR? It will only compare against row_description's
# type_code if it is this one type. It is the varchar type oid for now, this
# appears to match expectations in the DB API 2.0 compliance test suite.
STRING = 1043
# bytea type_oid
BINARY = 17
# numeric type_oid
NUMBER = 1700
# timestamp type_oid
DATETIME = 1114
# oid type_oid
ROWID = 26
| Python |
# vim: sw=4:expandtab:foldmethod=marker
#
# Copyright (c) 2007-2009, Mathieu Fenniak
# 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.
# * The name of the author may not be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# 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__ = "Mathieu Fenniak"
import socket
try:
import ssl as sslmodule
except ImportError:
sslmodule = None
import select
import threading
import struct
import hashlib
from cStringIO import StringIO
from errors import *
from util import MulticastDelegate
import types
##
# An SSLRequest message. To initiate an SSL-encrypted connection, an
# SSLRequest message is used rather than a {@link StartupMessage
# StartupMessage}. A StartupMessage is still sent, but only after SSL
# negotiation (if accepted).
# <p>
# Stability: This is an internal class. No stability guarantee is made.
class SSLRequest(object):
def __init__(self):
pass
# Int32(8) - Message length, including self.<br>
# Int32(80877103) - The SSL request code.<br>
def serialize(self):
return struct.pack("!ii", 8, 80877103)
##
# A StartupMessage message. Begins a DB session, identifying the user to be
# authenticated as and the database to connect to.
# <p>
# Stability: This is an internal class. No stability guarantee is made.
class StartupMessage(object):
def __init__(self, user, database=None):
self.user = user
self.database = database
# Int32 - Message length, including self.
# Int32(196608) - Protocol version number. Version 3.0.
# Any number of key/value pairs, terminated by a zero byte:
# String - A parameter name (user, database, or options)
# String - Parameter value
def serialize(self):
protocol = 196608
val = struct.pack("!i", protocol)
val += "user\x00" + self.user + "\x00"
if self.database:
val += "database\x00" + self.database + "\x00"
val += "\x00"
val = struct.pack("!i", len(val) + 4) + val
return val
##
# Parse message. Creates a prepared statement in the DB session.
# <p>
# Stability: This is an internal class. No stability guarantee is made.
#
# @param ps Name of the prepared statement to create.
# @param qs Query string.
# @param type_oids An iterable that contains the PostgreSQL type OIDs for
# parameters in the query string.
class Parse(object):
def __init__(self, ps, qs, type_oids):
if isinstance(qs, unicode):
raise TypeError("qs must be encoded byte data")
self.ps = ps
self.qs = qs
self.type_oids = type_oids
def __repr__(self):
return "<Parse ps=%r qs=%r>" % (self.ps, self.qs)
# Byte1('P') - Identifies the message as a Parse command.
# Int32 - Message length, including self.
# String - Prepared statement name. An empty string selects the unnamed
# prepared statement.
# String - The query string.
# Int16 - Number of parameter data types specified (can be zero).
# For each parameter:
# Int32 - The OID of the parameter data type.
def serialize(self):
val = self.ps + "\x00" + self.qs + "\x00"
val = val + struct.pack("!h", len(self.type_oids))
for oid in self.type_oids:
# Parse message doesn't seem to handle the -1 type_oid for NULL
# values that other messages handle. So we'll provide type_oid 705,
# the PG "unknown" type.
if oid == -1: oid = 705
val = val + struct.pack("!i", oid)
val = struct.pack("!i", len(val) + 4) + val
val = "P" + val
return val
##
# Bind message. Readies a prepared statement for execution.
# <p>
# Stability: This is an internal class. No stability guarantee is made.
#
# @param portal Name of the destination portal.
# @param ps Name of the source prepared statement.
# @param in_fc An iterable containing the format codes for input
# parameters. 0 = Text, 1 = Binary.
# @param params The parameters.
# @param out_fc An iterable containing the format codes for output
# parameters. 0 = Text, 1 = Binary.
# @param kwargs Additional arguments to pass to the type conversion
# methods.
class Bind(object):
def __init__(self, portal, ps, in_fc, params, out_fc, **kwargs):
self.portal = portal
self.ps = ps
self.in_fc = in_fc
self.params = []
for i in range(len(params)):
if len(self.in_fc) == 0:
fc = 0
elif len(self.in_fc) == 1:
fc = self.in_fc[0]
else:
fc = self.in_fc[i]
self.params.append(types.pg_value(params[i], fc, **kwargs))
self.out_fc = out_fc
def __repr__(self):
return "<Bind p=%r s=%r>" % (self.portal, self.ps)
# Byte1('B') - Identifies the Bind command.
# Int32 - Message length, including self.
# String - Name of the destination portal.
# String - Name of the source prepared statement.
# Int16 - Number of parameter format codes.
# For each parameter format code:
# Int16 - The parameter format code.
# Int16 - Number of parameter values.
# For each parameter value:
# Int32 - The length of the parameter value, in bytes, not including this
# this length. -1 indicates a NULL parameter value, in which no
# value bytes follow.
# Byte[n] - Value of the parameter.
# Int16 - The number of result-column format codes.
# For each result-column format code:
# Int16 - The format code.
def serialize(self):
retval = StringIO()
retval.write(self.portal + "\x00")
retval.write(self.ps + "\x00")
retval.write(struct.pack("!h", len(self.in_fc)))
for fc in self.in_fc:
retval.write(struct.pack("!h", fc))
retval.write(struct.pack("!h", len(self.params)))
for param in self.params:
if param == None:
# special case, NULL value
retval.write(struct.pack("!i", -1))
else:
retval.write(struct.pack("!i", len(param)))
retval.write(param)
retval.write(struct.pack("!h", len(self.out_fc)))
for fc in self.out_fc:
retval.write(struct.pack("!h", fc))
val = retval.getvalue()
val = struct.pack("!i", len(val) + 4) + val
val = "B" + val
return val
##
# A Close message, used for closing prepared statements and portals.
# <p>
# Stability: This is an internal class. No stability guarantee is made.
#
# @param typ 'S' for prepared statement, 'P' for portal.
# @param name The name of the item to close.
class Close(object):
def __init__(self, typ, name):
if len(typ) != 1:
raise InternalError("Close typ must be 1 char")
self.typ = typ
self.name = name
# Byte1('C') - Identifies the message as a close command.
# Int32 - Message length, including self.
# Byte1 - 'S' for prepared statement, 'P' for portal.
# String - The name of the item to close.
def serialize(self):
val = self.typ + self.name + "\x00"
val = struct.pack("!i", len(val) + 4) + val
val = "C" + val
return val
##
# A specialized Close message for a portal.
# <p>
# Stability: This is an internal class. No stability guarantee is made.
class ClosePortal(Close):
def __init__(self, name):
Close.__init__(self, "P", name)
##
# A specialized Close message for a prepared statement.
# <p>
# Stability: This is an internal class. No stability guarantee is made.
class ClosePreparedStatement(Close):
def __init__(self, name):
Close.__init__(self, "S", name)
##
# A Describe message, used for obtaining information on prepared statements
# and portals.
# <p>
# Stability: This is an internal class. No stability guarantee is made.
#
# @param typ 'S' for prepared statement, 'P' for portal.
# @param name The name of the item to close.
class Describe(object):
def __init__(self, typ, name):
if len(typ) != 1:
raise InternalError("Describe typ must be 1 char")
self.typ = typ
self.name = name
# Byte1('D') - Identifies the message as a describe command.
# Int32 - Message length, including self.
# Byte1 - 'S' for prepared statement, 'P' for portal.
# String - The name of the item to close.
def serialize(self):
val = self.typ + self.name + "\x00"
val = struct.pack("!i", len(val) + 4) + val
val = "D" + val
return val
##
# A specialized Describe message for a portal.
# <p>
# Stability: This is an internal class. No stability guarantee is made.
class DescribePortal(Describe):
def __init__(self, name):
Describe.__init__(self, "P", name)
def __repr__(self):
return "<DescribePortal %r>" % (self.name)
##
# A specialized Describe message for a prepared statement.
# <p>
# Stability: This is an internal class. No stability guarantee is made.
class DescribePreparedStatement(Describe):
def __init__(self, name):
Describe.__init__(self, "S", name)
def __repr__(self):
return "<DescribePreparedStatement %r>" % (self.name)
##
# A Flush message forces the backend to deliver any data pending in its
# output buffers.
# <p>
# Stability: This is an internal class. No stability guarantee is made.
class Flush(object):
# Byte1('H') - Identifies the message as a flush command.
# Int32(4) - Length of message, including self.
def serialize(self):
return 'H\x00\x00\x00\x04'
def __repr__(self):
return "<Flush>"
##
# Causes the backend to close the current transaction (if not in a BEGIN/COMMIT
# block), and issue ReadyForQuery.
# <p>
# Stability: This is an internal class. No stability guarantee is made.
class Sync(object):
# Byte1('S') - Identifies the message as a sync command.
# Int32(4) - Length of message, including self.
def serialize(self):
return 'S\x00\x00\x00\x04'
def __repr__(self):
return "<Sync>"
##
# Transmits a password.
# <p>
# Stability: This is an internal class. No stability guarantee is made.
class PasswordMessage(object):
def __init__(self, pwd):
self.pwd = pwd
# Byte1('p') - Identifies the message as a password message.
# Int32 - Message length including self.
# String - The password. Password may be encrypted.
def serialize(self):
val = self.pwd + "\x00"
val = struct.pack("!i", len(val) + 4) + val
val = "p" + val
return val
##
# Requests that the backend execute a portal and retrieve any number of rows.
# <p>
# Stability: This is an internal class. No stability guarantee is made.
# @param row_count The number of rows to return. Can be zero to indicate the
# backend should return all rows. If the portal represents a
# query that does not return rows, no rows will be returned
# no matter what the row_count.
class Execute(object):
def __init__(self, portal, row_count):
self.portal = portal
self.row_count = row_count
# Byte1('E') - Identifies the message as an execute message.
# Int32 - Message length, including self.
# String - The name of the portal to execute.
# Int32 - Maximum number of rows to return, if portal contains a query that
# returns rows. 0 = no limit.
def serialize(self):
val = self.portal + "\x00" + struct.pack("!i", self.row_count)
val = struct.pack("!i", len(val) + 4) + val
val = "E" + val
return val
class SimpleQuery(object):
"Requests that the backend execute a Simple Query (SQL string)"
def __init__(self, query_string):
self.query_string = query_string
# Byte1('Q') - Identifies the message as an query message.
# Int32 - Message length, including self.
# String - The query string itself.
def serialize(self):
val = self.query_string + "\x00"
val = struct.pack("!i", len(val) + 4) + val
val = "Q" + val
return val
def __repr__(self):
return "<SimpleQuery qs=%r>" % (self.query_string)
##
# Informs the backend that the connection is being closed.
# <p>
# Stability: This is an internal class. No stability guarantee is made.
class Terminate(object):
def __init__(self):
pass
# Byte1('X') - Identifies the message as a terminate message.
# Int32(4) - Message length, including self.
def serialize(self):
return 'X\x00\x00\x00\x04'
##
# Base class of all Authentication[*] messages.
# <p>
# Stability: This is an internal class. No stability guarantee is made.
class AuthenticationRequest(object):
def __init__(self, data):
pass
# Byte1('R') - Identifies the message as an authentication request.
# Int32(8) - Message length, including self.
# Int32 - An authentication code that represents different
# authentication messages:
# 0 = AuthenticationOk
# 5 = MD5 pwd
# 2 = Kerberos v5 (not supported by pg8000)
# 3 = Cleartext pwd (not supported by pg8000)
# 4 = crypt() pwd (not supported by pg8000)
# 6 = SCM credential (not supported by pg8000)
# 7 = GSSAPI (not supported by pg8000)
# 8 = GSSAPI data (not supported by pg8000)
# 9 = SSPI (not supported by pg8000)
# Some authentication messages have additional data following the
# authentication code. That data is documented in the appropriate class.
def createFromData(data):
ident = struct.unpack("!i", data[:4])[0]
klass = authentication_codes.get(ident, None)
if klass != None:
return klass(data[4:])
else:
raise NotSupportedError("authentication method %r not supported" % (ident,))
createFromData = staticmethod(createFromData)
def ok(self, conn, user, **kwargs):
raise InternalError("ok method should be overridden on AuthenticationRequest instance")
##
# A message representing that the backend accepting the provided username
# without any challenge.
# <p>
# Stability: This is an internal class. No stability guarantee is made.
class AuthenticationOk(AuthenticationRequest):
def ok(self, conn, user, **kwargs):
return True
##
# A message representing the backend requesting an MD5 hashed password
# response. The response will be sent as md5(md5(pwd + login) + salt).
# <p>
# Stability: This is an internal class. No stability guarantee is made.
class AuthenticationMD5Password(AuthenticationRequest):
# Additional message data:
# Byte4 - Hash salt.
def __init__(self, data):
self.salt = "".join(struct.unpack("4c", data))
def ok(self, conn, user, password=None, **kwargs):
if password == None:
raise InterfaceError("server requesting MD5 password authentication, but no password was provided")
pwd = "md5" + hashlib.md5(hashlib.md5(password + user).hexdigest() + self.salt).hexdigest()
conn._send(PasswordMessage(pwd))
conn._flush()
reader = MessageReader(conn)
reader.add_message(AuthenticationRequest, lambda msg, reader: reader.return_value(msg.ok(conn, user)), reader)
reader.add_message(ErrorResponse, self._ok_error)
return reader.handle_messages()
def _ok_error(self, msg):
if msg.code == "28000":
raise InterfaceError("md5 password authentication failed")
else:
raise msg.createException()
authentication_codes = {
0: AuthenticationOk,
5: AuthenticationMD5Password,
}
##
# ParameterStatus message sent from backend, used to inform the frotnend of
# runtime configuration parameter changes.
# <p>
# Stability: This is an internal class. No stability guarantee is made.
class ParameterStatus(object):
def __init__(self, key, value):
self.key = key
self.value = value
# Byte1('S') - Identifies ParameterStatus
# Int32 - Message length, including self.
# String - Runtime parameter name.
# String - Runtime parameter value.
def createFromData(data):
key = data[:data.find("\x00")]
value = data[data.find("\x00")+1:-1]
return ParameterStatus(key, value)
createFromData = staticmethod(createFromData)
##
# BackendKeyData message sent from backend. Contains a connection's process
# ID and a secret key. Can be used to terminate the connection's current
# actions, such as a long running query. Not supported by pg8000 yet.
# <p>
# Stability: This is an internal class. No stability guarantee is made.
class BackendKeyData(object):
def __init__(self, process_id, secret_key):
self.process_id = process_id
self.secret_key = secret_key
# Byte1('K') - Identifier.
# Int32(12) - Message length, including self.
# Int32 - Process ID.
# Int32 - Secret key.
def createFromData(data):
process_id, secret_key = struct.unpack("!2i", data)
return BackendKeyData(process_id, secret_key)
createFromData = staticmethod(createFromData)
##
# Message representing a query with no data.
# <p>
# Stability: This is an internal class. No stability guarantee is made.
class NoData(object):
# Byte1('n') - Identifier.
# Int32(4) - Message length, including self.
def createFromData(data):
return NoData()
createFromData = staticmethod(createFromData)
##
# Message representing a successful Parse.
# <p>
# Stability: This is an internal class. No stability guarantee is made.
class ParseComplete(object):
# Byte1('1') - Identifier.
# Int32(4) - Message length, including self.
def createFromData(data):
return ParseComplete()
createFromData = staticmethod(createFromData)
##
# Message representing a successful Bind.
# <p>
# Stability: This is an internal class. No stability guarantee is made.
class BindComplete(object):
# Byte1('2') - Identifier.
# Int32(4) - Message length, including self.
def createFromData(data):
return BindComplete()
createFromData = staticmethod(createFromData)
##
# Message representing a successful Close.
# <p>
# Stability: This is an internal class. No stability guarantee is made.
class CloseComplete(object):
# Byte1('3') - Identifier.
# Int32(4) - Message length, including self.
def createFromData(data):
return CloseComplete()
createFromData = staticmethod(createFromData)
##
# Message representing data from an Execute has been received, but more data
# exists in the portal.
# <p>
# Stability: This is an internal class. No stability guarantee is made.
class PortalSuspended(object):
# Byte1('s') - Identifier.
# Int32(4) - Message length, including self.
def createFromData(data):
return PortalSuspended()
createFromData = staticmethod(createFromData)
##
# Message representing the backend is ready to process a new query.
# <p>
# Stability: This is an internal class. No stability guarantee is made.
class ReadyForQuery(object):
def __init__(self, status):
self._status = status
##
# I = Idle, T = Idle in Transaction, E = idle in failed transaction.
status = property(lambda self: self._status)
def __repr__(self):
return "<ReadyForQuery %s>" % \
{"I": "Idle", "T": "Idle in Transaction", "E": "Idle in Failed Transaction"}[self.status]
# Byte1('Z') - Identifier.
# Int32(5) - Message length, including self.
# Byte1 - Status indicator.
def createFromData(data):
return ReadyForQuery(data)
createFromData = staticmethod(createFromData)
##
# Represents a notice sent from the server. This is not the same as a
# notification. A notice is just additional information about a query, such
# as a notice that a primary key has automatically been created for a table.
# <p>
# A NoticeResponse instance will have properties containing the data sent
# from the server:
# <ul>
# <li>severity -- "ERROR", "FATAL', "PANIC", "WARNING", "NOTICE", "DEBUG",
# "INFO", or "LOG". Always present.</li>
# <li>code -- the SQLSTATE code for the error. See Appendix A of the
# PostgreSQL documentation for specific error codes. Always present.</li>
# <li>msg -- human-readable error message. Always present.</li>
# <li>detail -- Optional additional information.</li>
# <li>hint -- Optional suggestion about what to do about the issue.</li>
# <li>position -- Optional index into the query string.</li>
# <li>where -- Optional context.</li>
# <li>file -- Source-code file.</li>
# <li>line -- Source-code line.</li>
# <li>routine -- Source-code routine.</li>
# </ul>
# <p>
# Stability: Added in pg8000 v1.03. Required properties severity, code, and
# msg are guaranteed for v1.xx. Other properties should be checked with
# hasattr before accessing.
class NoticeResponse(object):
responseKeys = {
"S": "severity", # always present
"C": "code", # always present
"M": "msg", # always present
"D": "detail",
"H": "hint",
"P": "position",
"p": "_position",
"q": "_query",
"W": "where",
"F": "file",
"L": "line",
"R": "routine",
}
def __init__(self, **kwargs):
for arg, value in kwargs.items():
setattr(self, arg, value)
def __repr__(self):
return "<NoticeResponse %s %s %r>" % (self.severity, self.code, self.msg)
def dataIntoDict(data):
retval = {}
for s in data.split("\x00"):
if not s: continue
key, value = s[0], s[1:]
key = NoticeResponse.responseKeys.get(key, key)
retval[key] = value
return retval
dataIntoDict = staticmethod(dataIntoDict)
# Byte1('N') - Identifier
# Int32 - Message length
# Any number of these, followed by a zero byte:
# Byte1 - code identifying the field type (see responseKeys)
# String - field value
def createFromData(data):
return NoticeResponse(**NoticeResponse.dataIntoDict(data))
createFromData = staticmethod(createFromData)
##
# A message sent in case of a server-side error. Contains the same properties
# that {@link NoticeResponse NoticeResponse} contains.
# <p>
# Stability: Added in pg8000 v1.03. Required properties severity, code, and
# msg are guaranteed for v1.xx. Other properties should be checked with
# hasattr before accessing.
class ErrorResponse(object):
def __init__(self, **kwargs):
for arg, value in kwargs.items():
setattr(self, arg, value)
def __repr__(self):
return "<ErrorResponse %s %s %r>" % (self.severity, self.code, self.msg)
def createException(self):
return ProgrammingError(self.severity, self.code, self.msg)
def createFromData(data):
return ErrorResponse(**NoticeResponse.dataIntoDict(data))
createFromData = staticmethod(createFromData)
##
# A message sent if this connection receives a NOTIFY that it was LISTENing for.
# <p>
# Stability: Added in pg8000 v1.03. When limited to accessing properties from
# a notification event dispatch, stability is guaranteed for v1.xx.
class NotificationResponse(object):
def __init__(self, backend_pid, condition, additional_info):
self._backend_pid = backend_pid
self._condition = condition
self._additional_info = additional_info
##
# An integer representing the process ID of the backend that triggered
# the NOTIFY.
# <p>
# Stability: Added in pg8000 v1.03, stability guaranteed for v1.xx.
backend_pid = property(lambda self: self._backend_pid)
##
# The name of the notification fired.
# <p>
# Stability: Added in pg8000 v1.03, stability guaranteed for v1.xx.
condition = property(lambda self: self._condition)
##
# Currently unspecified by the PostgreSQL documentation as of v8.3.1.
# <p>
# Stability: Added in pg8000 v1.03, stability guaranteed for v1.xx.
additional_info = property(lambda self: self._additional_info)
def __repr__(self):
return "<NotificationResponse %s %s %r>" % (self.backend_pid, self.condition, self.additional_info)
def createFromData(data):
backend_pid = struct.unpack("!i", data[:4])[0]
data = data[4:]
null = data.find("\x00")
condition = data[:null]
data = data[null+1:]
null = data.find("\x00")
additional_info = data[:null]
return NotificationResponse(backend_pid, condition, additional_info)
createFromData = staticmethod(createFromData)
class ParameterDescription(object):
def __init__(self, type_oids):
self.type_oids = type_oids
def createFromData(data):
count = struct.unpack("!h", data[:2])[0]
type_oids = struct.unpack("!" + "i"*count, data[2:])
return ParameterDescription(type_oids)
createFromData = staticmethod(createFromData)
class RowDescription(object):
def __init__(self, fields):
self.fields = fields
def createFromData(data):
count = struct.unpack("!h", data[:2])[0]
data = data[2:]
fields = []
for i in range(count):
null = data.find("\x00")
field = {"name": data[:null]}
data = data[null+1:]
field["table_oid"], field["column_attrnum"], field["type_oid"], field["type_size"], field["type_modifier"], field["format"] = struct.unpack("!ihihih", data[:18])
data = data[18:]
fields.append(field)
return RowDescription(fields)
createFromData = staticmethod(createFromData)
class CommandComplete(object):
def __init__(self, command, rows=None, oid=None):
self.command = command
self.rows = rows
self.oid = oid
def createFromData(data):
values = data[:-1].split(" ")
args = {}
args['command'] = values[0]
if args['command'] in ("INSERT", "DELETE", "UPDATE", "MOVE", "FETCH", "COPY", "SELECT"):
args['rows'] = int(values[-1])
if args['command'] == "INSERT":
args['oid'] = int(values[1])
else:
args['command'] = data[:-1]
return CommandComplete(**args)
createFromData = staticmethod(createFromData)
class DataRow(object):
def __init__(self, fields):
self.fields = fields
def createFromData(data):
count = struct.unpack("!h", data[:2])[0]
data = data[2:]
fields = []
for i in range(count):
val_len = struct.unpack("!i", data[:4])[0]
data = data[4:]
if val_len == -1:
fields.append(None)
else:
fields.append(data[:val_len])
data = data[val_len:]
return DataRow(fields)
createFromData = staticmethod(createFromData)
class CopyData(object):
# "d": CopyData,
def __init__(self, data):
self.data = data
def createFromData(data):
return CopyData(data)
createFromData = staticmethod(createFromData)
def serialize(self):
return 'd' + struct.pack('!i', len(self.data) + 4) + self.data
class CopyDone(object):
# Byte1('c') - Identifier.
# Int32(4) - Message length, including self.
def createFromData(data):
return CopyDone()
createFromData = staticmethod(createFromData)
def serialize(self):
return 'c\x00\x00\x00\x04'
class CopyOutResponse(object):
# Byte1('H')
# Int32(4) - Length of message contents in bytes, including self.
# Int8(1) - 0 textual, 1 binary
# Int16(2) - Number of columns
# Int16(N) - Format codes for each column (0 text, 1 binary)
def __init__(self, is_binary, column_formats):
self.is_binary = is_binary
self.column_formats = column_formats
def createFromData(data):
is_binary, num_cols = struct.unpack('!bh', data[:3])
column_formats = struct.unpack('!' + ('h' * num_cols), data[3:])
return CopyOutResponse(is_binary, column_formats)
createFromData = staticmethod(createFromData)
class CopyInResponse(object):
# Byte1('G')
# Otherwise the same as CopyOutResponse
def __init__(self, is_binary, column_formats):
self.is_binary = is_binary
self.column_formats = column_formats
def createFromData(data):
is_binary, num_cols = struct.unpack('!bh', data[:3])
column_formats = struct.unpack('!' + ('h' * num_cols), data[3:])
return CopyInResponse(is_binary, column_formats)
createFromData = staticmethod(createFromData)
class EmptyQueryResponse(object):
# Byte1('I')
# Response to an empty query string. (This substitutes for CommandComplete.)
def createFromData(data):
return EmptyQueryResponse()
createFromData = staticmethod(createFromData)
class MessageReader(object):
def __init__(self, connection):
self._conn = connection
self._msgs = []
# If true, raise exception from an ErrorResponse after messages are
# processed. This can be used to leave the connection in a usable
# state after an error response, rather than having unconsumed
# messages that won't be understood in another context.
self.delay_raising_exception = False
self.ignore_unhandled_messages = False
def add_message(self, msg_class, handler, *args, **kwargs):
self._msgs.append((msg_class, handler, args, kwargs))
def clear_messages(self):
self._msgs = []
def return_value(self, value):
self._retval = value
def handle_messages(self):
exc = None
while 1:
msg = self._conn._read_message()
msg_handled = False
for (msg_class, handler, args, kwargs) in self._msgs:
if isinstance(msg, msg_class):
msg_handled = True
retval = handler(msg, *args, **kwargs)
if retval:
# The handler returned a true value, meaning that the
# message loop should be aborted.
if exc != None:
raise exc
return retval
elif hasattr(self, "_retval"):
# The handler told us to return -- used for non-true
# return values
if exc != None:
raise exc
return self._retval
if msg_handled:
continue
elif isinstance(msg, ErrorResponse):
exc = msg.createException()
if not self.delay_raising_exception:
raise exc
elif isinstance(msg, NoticeResponse):
self._conn.handleNoticeResponse(msg)
elif isinstance(msg, ParameterStatus):
self._conn.handleParameterStatus(msg)
elif isinstance(msg, NotificationResponse):
self._conn.handleNotificationResponse(msg)
elif not self.ignore_unhandled_messages:
raise InternalError("Unexpected response msg %r" % (msg))
def sync_on_error(fn):
def _fn(self, *args, **kwargs):
try:
self._sock_lock.acquire()
return fn(self, *args, **kwargs)
except:
self._sync()
raise
finally:
self._sock_lock.release()
return _fn
class Connection(object):
def __init__(self, unix_sock=None, host=None, port=5432, socket_timeout=60, ssl=False):
self._client_encoding = "ascii"
self._integer_datetimes = False
self._server_version = None
self._sock_buf = ""
self._sock_buf_pos = 0
self._send_sock_buf = []
self._block_size = 8192
self._sock_lock = threading.Lock()
if unix_sock == None and host != None:
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
elif unix_sock != None:
if not hasattr(socket, "AF_UNIX"):
raise InterfaceError("attempt to connect to unix socket on unsupported platform")
self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
else:
raise ProgrammingError("one of host or unix_sock must be provided")
if unix_sock == None and host != None:
self._sock.connect((host, port))
elif unix_sock != None:
self._sock.connect(unix_sock)
if ssl:
self._sock_lock.acquire()
try:
self._send(SSLRequest())
self._flush()
resp = self._sock.recv(1)
if resp == 'S' and sslmodule is not None:
self._sock = sslmodule.wrap_socket(self._sock)
elif sslmodule is None:
raise InterfaceError("SSL required but ssl module not available in this python installation")
else:
raise InterfaceError("server refuses SSL")
finally:
self._sock_lock.release()
else:
# settimeout causes ssl failure, on windows. Python bug 1462352.
self._sock.settimeout(socket_timeout)
self._state = "noauth"
self._backend_key_data = None
self.NoticeReceived = MulticastDelegate()
self.ParameterStatusReceived = MulticastDelegate()
self.NotificationReceived = MulticastDelegate()
self.ParameterStatusReceived += self._onParameterStatusReceived
def verifyState(self, state):
if self._state != state:
raise InternalError("connection state must be %s, is %s" % (state, self._state))
def _send(self, msg):
assert self._sock_lock.locked()
##print "_send(%r)" % msg
data = msg.serialize()
if not isinstance(data, str):
raise TypeError("bytes data expected")
self._send_sock_buf.append(data)
def _flush(self):
assert self._sock_lock.locked()
self._sock.sendall("".join(self._send_sock_buf))
del self._send_sock_buf[:]
def _read_bytes(self, byte_count):
retval = []
bytes_read = 0
while bytes_read < byte_count:
if self._sock_buf_pos == len(self._sock_buf):
self._sock_buf = self._sock.recv(1024)
self._sock_buf_pos = 0
rpos = min(len(self._sock_buf), self._sock_buf_pos + (byte_count - bytes_read))
addt_data = self._sock_buf[self._sock_buf_pos:rpos]
bytes_read += (rpos - self._sock_buf_pos)
assert bytes_read <= byte_count
self._sock_buf_pos = rpos
retval.append(addt_data)
return "".join(retval)
def _read_message(self):
assert self._sock_lock.locked()
bytes = self._read_bytes(5)
message_code = bytes[0]
data_len = struct.unpack("!i", bytes[1:])[0] - 4
bytes = self._read_bytes(data_len)
assert len(bytes) == data_len
msg = message_types[message_code].createFromData(bytes)
##print "_read_message() -> %r" % msg
return msg
def authenticate(self, user, **kwargs):
self.verifyState("noauth")
self._sock_lock.acquire()
try:
self._send(StartupMessage(user, database=kwargs.get("database",None)))
self._flush()
reader = MessageReader(self)
reader.add_message(AuthenticationRequest, self._authentication_request(user, **kwargs))
reader.handle_messages()
finally:
self._sock_lock.release()
def _authentication_request(self, user, **kwargs):
def _func(msg):
assert self._sock_lock.locked()
if not msg.ok(self, user, **kwargs):
raise InterfaceError("authentication method %s failed" % msg.__class__.__name__)
self._state = "auth"
reader = MessageReader(self)
reader.add_message(ReadyForQuery, self._ready_for_query)
reader.add_message(BackendKeyData, self._receive_backend_key_data)
reader.handle_messages()
return 1
return _func
def _ready_for_query(self, msg):
self._state = "ready"
return True
def _receive_backend_key_data(self, msg):
self._backend_key_data = msg
@sync_on_error
def parse(self, statement, qs, param_types):
self.verifyState("ready")
type_info = [types.pg_type_info(x) for x in param_types]
param_types, param_fc = [x[0] for x in type_info], [x[1] for x in type_info] # zip(*type_info) -- fails on empty arr
if isinstance(qs, unicode):
qs = qs.encode(self._client_encoding)
self._send(Parse(statement, qs, param_types))
self._send(DescribePreparedStatement(statement))
self._send(Flush())
self._flush()
reader = MessageReader(self)
# ParseComplete is good.
reader.add_message(ParseComplete, lambda msg: 0)
# Well, we don't really care -- we're going to send whatever we
# want and let the database deal with it. But thanks anyways!
reader.add_message(ParameterDescription, lambda msg: 0)
# We're not waiting for a row description. Return something
# destinctive to let bind know that there is no output.
reader.add_message(NoData, lambda msg: (None, param_fc))
# Common row description response
reader.add_message(RowDescription, lambda msg: (msg, param_fc))
return reader.handle_messages()
@sync_on_error
def bind(self, portal, statement, params, parse_data, copy_stream):
self.verifyState("ready")
row_desc, param_fc = parse_data
if row_desc == None:
# no data coming out
output_fc = ()
else:
# We've got row_desc that allows us to identify what we're going to
# get back from this statement.
output_fc = [types.py_type_info(f) for f in row_desc.fields]
self._send(Bind(portal, statement, param_fc, params, output_fc, client_encoding = self._client_encoding, integer_datetimes = self._integer_datetimes))
# We need to describe the portal after bind, since the return
# format codes will be different (hopefully, always what we
# requested).
self._send(DescribePortal(portal))
self._send(Flush())
self._flush()
# Read responses from server...
reader = MessageReader(self)
# BindComplete is good -- just ignore
reader.add_message(BindComplete, lambda msg: 0)
# NoData in this case means we're not executing a query. As a
# result, we won't be fetching rows, so we'll never execute the
# portal we just created... unless we execute it right away, which
# we'll do.
reader.add_message(NoData, self._bind_nodata, portal, reader, copy_stream)
# Return the new row desc, since it will have the format types we
# asked the server for
reader.add_message(RowDescription, lambda msg: (msg, None))
return reader.handle_messages()
def _copy_in_response(self, copyin, fileobj, old_reader):
if fileobj == None:
raise CopyQueryWithoutStreamError()
while True:
data = fileobj.read(self._block_size)
if not data:
break
self._send(CopyData(data))
self._flush()
self._send(CopyDone())
self._send(Sync())
self._flush()
def _copy_out_response(self, copyout, fileobj, old_reader):
if fileobj == None:
raise CopyQueryWithoutStreamError()
reader = MessageReader(self)
reader.add_message(CopyData, self._copy_data, fileobj)
reader.add_message(CopyDone, lambda msg: 1)
reader.handle_messages()
def _copy_data(self, copydata, fileobj):
fileobj.write(copydata.data)
def _bind_nodata(self, msg, portal, old_reader, copy_stream):
# Bind message returned NoData, causing us to execute the command.
self._send(Execute(portal, 0))
self._send(Sync())
self._flush()
output = {}
reader = MessageReader(self)
reader.add_message(CopyOutResponse, self._copy_out_response, copy_stream, reader)
reader.add_message(CopyInResponse, self._copy_in_response, copy_stream, reader)
reader.add_message(CommandComplete, lambda msg, out: out.setdefault('msg', msg) and False, output)
reader.add_message(ReadyForQuery, lambda msg: 1)
reader.delay_raising_exception = True
reader.handle_messages()
old_reader.return_value((None, output['msg']))
@sync_on_error
def send_simple_query(self, query_string, copy_stream=None):
"Submit a simple query (PQsendQuery)"
# Only use this for trivial queries, as its use is discouraged because:
# CONS:
# - Parameter are "injected" (they should be escaped by the app)
# - Exesive memory usage (allways returns all rows on completion)
# - Inneficient transmission of data in plain text (except for FETCH)
# - No Prepared Statement support, each query is parsed every time
# - Basic implementation: minimal error recovery and type support
# PROS:
# - compact: equivalent to Parse, Bind, Describe, Execute, Close, Sync
# - doesn't returns ParseComplete, BindComplete, CloseComplete, NoData
# - it supports multiple statements in a single query string
# - it is available when the Streaming Replication Protocol is actived
# NOTE: this is the protocol used by psycopg2
# (they also uses named cursors to overcome some drawbacks)
self.verifyState("ready")
if isinstance(query_string, unicode):
query_string = query_string.encode(self._client_encoding)
self._send(SimpleQuery(query_string))
self._flush()
# define local storage for message handlers:
output = {}
rows = []
# create and add handlers for all the possible messages:
reader = MessageReader(self)
# read row description but continue processing messages... (return false)
reader.add_message(RowDescription, lambda msg, out: out.setdefault('row_desc', msg) and False, output)
reader.add_message(DataRow, lambda msg: self._fetch_datarow(msg, rows, output['row_desc']))
reader.add_message(EmptyQueryResponse, lambda msg: False)
reader.add_message(CommandComplete, lambda msg, out: out.setdefault('complete', msg) and False, output)
reader.add_message(CopyInResponse, self._copy_in_response, copy_stream, reader)
reader.add_message(CopyOutResponse, self._copy_out_response, copy_stream, reader)
# messages indicating that we've hit the end of the available data for this command
reader.add_message(ReadyForQuery, lambda msg: 1)
# process all messages and then raise exceptions (if any)
reader.delay_raising_exception = True
# start processing the messages from the backend:
retval = reader.handle_messages()
# return a dict with command complete / row description message values
return output.get('row_desc'), output.get('complete'), rows
@sync_on_error
def fetch_rows(self, portal, row_count, row_desc):
self.verifyState("ready")
self._send(Execute(portal, row_count))
self._send(Flush())
self._flush()
rows = []
reader = MessageReader(self)
reader.add_message(DataRow, self._fetch_datarow, rows, row_desc)
reader.add_message(PortalSuspended, lambda msg: 1)
reader.add_message(CommandComplete, self._fetch_commandcomplete, portal)
retval = reader.handle_messages()
# retval = 2 when command complete, indicating that we've hit the
# end of the available data for this command
return (retval == 2), rows
def _fetch_datarow(self, msg, rows, row_desc):
rows.append(
[
types.py_value(
msg.fields[i],
row_desc.fields[i],
client_encoding=self._client_encoding,
integer_datetimes=self._integer_datetimes,
)
for i in range(len(msg.fields))
]
)
def _fetch_commandcomplete(self, msg, portal):
self._send(ClosePortal(portal))
self._send(Sync())
self._flush()
reader = MessageReader(self)
reader.add_message(ReadyForQuery, self._fetch_commandcomplete_rfq)
reader.add_message(CloseComplete, lambda msg: False)
reader.handle_messages()
return 2 # signal end-of-data
def _fetch_commandcomplete_rfq(self, msg):
self._state = "ready"
return True
# Send a Sync message, then read and discard all messages until we
# receive a ReadyForQuery message.
def _sync(self):
# it is assumed _sync is called from sync_on_error, which holds
# a _sock_lock throughout the call
self._send(Sync())
self._flush()
reader = MessageReader(self)
reader.ignore_unhandled_messages = True
reader.add_message(ReadyForQuery, lambda msg: True)
reader.handle_messages()
def close_statement(self, statement):
if self._state == "closed":
return
self.verifyState("ready")
self._sock_lock.acquire()
try:
self._send(ClosePreparedStatement(statement))
self._send(Sync())
self._flush()
reader = MessageReader(self)
reader.add_message(CloseComplete, lambda msg: 0)
reader.add_message(ReadyForQuery, lambda msg: 1)
reader.handle_messages()
finally:
self._sock_lock.release()
def close_portal(self, portal):
if self._state == "closed":
return
self.verifyState("ready")
self._sock_lock.acquire()
try:
self._send(ClosePortal(portal))
self._send(Sync())
self._flush()
reader = MessageReader(self)
reader.add_message(CloseComplete, lambda msg: 0)
reader.add_message(ReadyForQuery, lambda msg: 1)
reader.handle_messages()
finally:
self._sock_lock.release()
def close(self):
self._sock_lock.acquire()
try:
self._send(Terminate())
self._flush()
self._sock.close()
self._state = "closed"
finally:
self._sock_lock.release()
def _onParameterStatusReceived(self, msg):
if msg.key == "client_encoding":
self._client_encoding = types.encoding_convert(msg.value)
##print "_onParameterStatusReceived client_encoding", self._client_encoding
elif msg.key == "integer_datetimes":
self._integer_datetimes = (msg.value == "on")
elif msg.key == "server_version":
self._server_version = msg.value
else:
##print "_onParameterStatusReceived ", msg.key, msg.value
pass
def handleNoticeResponse(self, msg):
self.NoticeReceived(msg)
def handleParameterStatus(self, msg):
self.ParameterStatusReceived(msg)
def handleNotificationResponse(self, msg):
self.NotificationReceived(msg)
def fileno(self):
# This should be safe to do without a lock
return self._sock.fileno()
def isready(self):
self._sock_lock.acquire()
try:
rlst, _wlst, _xlst = select.select([self], [], [], 0)
if not rlst:
return False
self._sync()
return True
finally:
self._sock_lock.release()
def server_version(self):
self.verifyState("ready")
if not self._server_version:
raise InterfaceError("Server did not provide server_version parameter.")
return self._server_version
def encoding(self):
return self._client_encoding
message_types = {
"N": NoticeResponse,
"R": AuthenticationRequest,
"S": ParameterStatus,
"K": BackendKeyData,
"Z": ReadyForQuery,
"T": RowDescription,
"E": ErrorResponse,
"D": DataRow,
"C": CommandComplete,
"1": ParseComplete,
"2": BindComplete,
"3": CloseComplete,
"s": PortalSuspended,
"n": NoData,
"I": EmptyQueryResponse,
"t": ParameterDescription,
"A": NotificationResponse,
"c": CopyDone,
"d": CopyData,
"G": CopyInResponse,
"H": CopyOutResponse,
}
| Python |
class MulticastDelegate(object):
def __init__(self):
self.delegates = []
def __iadd__(self, delegate):
self.add(delegate)
return self
def add(self, delegate):
self.delegates.append(delegate)
def __isub__(self, delegate):
self.delegates.remove(delegate)
return self
def __call__(self, *args, **kwargs):
for d in self.delegates:
d(*args, **kwargs)
| Python |
# vim: sw=4:expandtab:foldmethod=marker
#
# Copyright (c) 2007-2009, Mathieu Fenniak
# 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.
# * The name of the author may not be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# 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__ = "Mathieu Fenniak"
import datetime
import decimal
import struct
import math
from errors import (NotSupportedError, ArrayDataParseError, InternalError,
ArrayContentEmptyError, ArrayContentNotHomogenousError,
ArrayContentNotSupportedError, ArrayDimensionsNotConsistentError)
try:
from pytz import utc
except ImportError:
ZERO = datetime.timedelta(0)
class UTC(datetime.tzinfo):
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return ZERO
utc = UTC()
class Bytea(str):
pass
class Interval(object):
def __init__(self, microseconds=0, days=0, months=0):
self.microseconds = microseconds
self.days = days
self.months = months
def _setMicroseconds(self, value):
if not isinstance(value, int) and not isinstance(value, long):
raise TypeError("microseconds must be an int or long")
elif not (min_int8 < value < max_int8):
raise OverflowError("microseconds must be representable as a 64-bit integer")
else:
self._microseconds = value
def _setDays(self, value):
if not isinstance(value, int) and not isinstance(value, long):
raise TypeError("days must be an int or long")
elif not (min_int4 < value < max_int4):
raise OverflowError("days must be representable as a 32-bit integer")
else:
self._days = value
def _setMonths(self, value):
if not isinstance(value, int) and not isinstance(value, long):
raise TypeError("months must be an int or long")
elif not (min_int4 < value < max_int4):
raise OverflowError("months must be representable as a 32-bit integer")
else:
self._months = value
microseconds = property(lambda self: self._microseconds, _setMicroseconds)
days = property(lambda self: self._days, _setDays)
months = property(lambda self: self._months, _setMonths)
def __repr__(self):
return "<Interval %s months %s days %s microseconds>" % (self.months, self.days, self.microseconds)
def __cmp__(self, other):
if other == None: return -1
c = cmp(self.months, other.months)
if c != 0: return c
c = cmp(self.days, other.days)
if c != 0: return c
return cmp(self.microseconds, other.microseconds)
def pg_type_info(typ):
value = None
if isinstance(typ, dict):
value = typ["value"]
typ = typ["type"]
data = py_types.get(typ)
if data == None:
raise NotSupportedError("type %r not mapped to pg type" % typ)
# permit the type data to be determined by the value, if provided
inspect_func = data.get("inspect")
if value != None and inspect_func != None:
data = inspect_func(value)
type_oid = data.get("typeoid")
if type_oid == None:
raise InternalError("type %r has no type_oid" % typ)
elif type_oid == -1:
# special case: NULL values
return type_oid, 0
# prefer bin, but go with whatever exists
if data.get("bin_out"):
format = 1
elif data.get("txt_out"):
format = 0
else:
raise InternalError("no conversion fuction for type %r" % typ)
return type_oid, format
def pg_value(value, fc, **kwargs):
typ = type(value)
data = py_types.get(typ)
if data == None:
raise NotSupportedError("type %r not mapped to pg type" % typ)
# permit the type conversion to be determined by the value, if provided
inspect_func = data.get("inspect")
if value != None and inspect_func != None:
data = inspect_func(value)
# special case: NULL values
if data.get("typeoid") == -1:
return None
if fc == 0:
func = data.get("txt_out")
elif fc == 1:
func = data.get("bin_out")
else:
raise InternalError("unrecognized format code %r" % fc)
if func == None:
raise NotSupportedError("type %r, format code %r not supported" % (typ, fc))
return func(value, **kwargs)
def py_type_info(description):
type_oid = description['type_oid']
data = pg_types.get(type_oid)
if data == None:
raise NotSupportedError("type oid %r not mapped to py type" % type_oid)
# prefer bin, but go with whatever exists
if data.get("bin_in"):
format = 1
elif data.get("txt_in"):
format = 0
else:
raise InternalError("no conversion fuction for type oid %r" % type_oid)
return format
def py_value(v, description, **kwargs):
if v == None:
# special case - NULL value
return None
type_oid = description['type_oid']
format = description['format']
data = pg_types.get(type_oid)
if data == None:
raise NotSupportedError("type oid %r not supported" % type_oid)
if format == 0:
func = data.get("txt_in")
elif format == 1:
func = data.get("bin_in")
else:
raise NotSupportedError("format code %r not supported" % format)
if func == None:
raise NotSupportedError("data response format %r, type %r not supported" % (format, type_oid))
return func(v, **kwargs)
def boolrecv(data, **kwargs):
return data == "\x01"
def boolsend(v, **kwargs):
if v:
return "\x01"
else:
return "\x00"
min_int2, max_int2 = -2 ** 15, 2 ** 15
min_int4, max_int4 = -2 ** 31, 2 ** 31
min_int8, max_int8 = -2 ** 63, 2 ** 63
def int_inspect(value):
if min_int2 < value < max_int2:
return {"typeoid": 21, "bin_out": int2send}
elif min_int4 < value < max_int4:
return {"typeoid": 23, "bin_out": int4send}
elif min_int8 < value < max_int8:
return {"typeoid": 20, "bin_out": int8send}
else:
return {"typeoid": 1700, "bin_out": numeric_send}
def int2recv(data, **kwargs):
return struct.unpack("!h", data)[0]
def int2send(v, **kwargs):
return struct.pack("!h", v)
def int4recv(data, **kwargs):
return struct.unpack("!i", data)[0]
def int4send(v, **kwargs):
return struct.pack("!i", v)
def int8recv(data, **kwargs):
return struct.unpack("!q", data)[0]
def int8send(v, **kwargs):
return struct.pack("!q", v)
def float4recv(data, **kwargs):
return struct.unpack("!f", data)[0]
def float8recv(data, **kwargs):
return struct.unpack("!d", data)[0]
def float8send(v, **kwargs):
return struct.pack("!d", v)
def datetime_inspect(value):
if value.tzinfo != None:
# send as timestamptz if timezone is provided
return {"typeoid": 1184, "bin_out": timestamptz_send}
else:
# otherwise send as timestamp
return {"typeoid": 1114, "bin_out": timestamp_send}
def timestamp_recv(data, integer_datetimes, **kwargs):
if integer_datetimes:
# data is 64-bit integer representing milliseconds since 2000-01-01
val = struct.unpack("!q", data)[0]
return datetime.datetime(2000, 1, 1) + datetime.timedelta(microseconds = val)
else:
# data is double-precision float representing seconds since 2000-01-01
val = struct.unpack("!d", data)[0]
return datetime.datetime(2000, 1, 1) + datetime.timedelta(seconds = val)
# return a timezone-aware datetime instance if we're reading from a
# "timestamp with timezone" type. The timezone returned will always be UTC,
# but providing that additional information can permit conversion to local.
def timestamptz_recv(data, **kwargs):
return timestamp_recv(data, **kwargs).replace(tzinfo=utc)
def timestamp_send(v, integer_datetimes, **kwargs):
delta = v - datetime.datetime(2000, 1, 1)
val = delta.microseconds + (delta.seconds * 1000000) + (delta.days * 86400000000)
if integer_datetimes:
# data is 64-bit integer representing milliseconds since 2000-01-01
return struct.pack("!q", val)
else:
# data is double-precision float representing seconds since 2000-01-01
return struct.pack("!d", val / 1000.0 / 1000.0)
def timestamptz_send(v, **kwargs):
# timestamps should be sent as UTC. If they have zone info,
# convert them.
return timestamp_send(v.astimezone(utc).replace(tzinfo=None), **kwargs)
def date_in(data, **kwargs):
year = int(data[0:4])
month = int(data[5:7])
day = int(data[8:10])
return datetime.date(year, month, day)
def date_out(v, **kwargs):
return v.isoformat()
def time_in(data, **kwargs):
hour = int(data[0:2])
minute = int(data[3:5])
sec = decimal.Decimal(data[6:])
return datetime.time(hour, minute, int(sec), int((sec - int(sec)) * 1000000))
def time_out(v, **kwargs):
return v.isoformat()
def numeric_in(data, **kwargs):
if data.find(".") == -1:
return int(data)
else:
return decimal.Decimal(data)
def numeric_recv(data, **kwargs):
num_digits, weight, sign, scale = struct.unpack("!hhhh", data[:8])
data = data[8:]
digits = struct.unpack("!" + ("h" * num_digits), data)
weight = decimal.Decimal(weight)
retval = 0
for d in digits:
d = decimal.Decimal(d)
retval += d * (10000 ** weight)
weight -= 1
if sign:
retval *= -1
return retval
DEC_DIGITS = 4
def numeric_send(d, **kwargs):
# This is a very straight port of src/backend/utils/adt/numeric.c set_var_from_str()
s = str(d)
pos = 0
sign = 0
if s[0] == '-':
sign = 0x4000 # NEG
pos=1
elif s[0] == '+':
sign = 0 # POS
pos=1
have_dp = False
decdigits = [0, 0, 0, 0]
dweight = -1
dscale = 0
for char in s[pos:]:
if char.isdigit():
decdigits.append(int(char))
if not have_dp:
dweight += 1
else:
dscale += 1
pos+=1
elif char == '.':
have_dp = True
pos+=1
else:
break
if len(s) > pos:
char = s[pos]
if char == 'e' or char == 'E':
pos+=1
exponent = int(s[pos:])
dweight += exponent
dscale -= exponent
if dscale < 0: dscale = 0
if dweight >= 0:
weight = (dweight + 1 + DEC_DIGITS - 1) / DEC_DIGITS - 1
else:
weight = -((-dweight - 1) / DEC_DIGITS + 1)
offset = (weight + 1) * DEC_DIGITS - (dweight + 1)
ndigits = (len(decdigits)-DEC_DIGITS + offset + DEC_DIGITS - 1) / DEC_DIGITS
i = DEC_DIGITS - offset
decdigits.extend([0, 0, 0])
ndigits_ = ndigits
digits = ''
while ndigits_ > 0:
# ifdef DEC_DIGITS == 4
digits += struct.pack("!h", ((decdigits[i] * 10 + decdigits[i + 1]) * 10 + decdigits[i + 2]) * 10 + decdigits[i + 3])
ndigits_ -= 1
i += DEC_DIGITS
# strip_var()
if ndigits == 0:
sign = 0x4000 # pos
weight = 0
# ----------
retval = struct.pack("!hhhh", ndigits, weight, sign, dscale) + digits
return retval
def numeric_out(v, **kwargs):
return str(v)
# PostgreSQL encodings:
# http://www.postgresql.org/docs/8.3/interactive/multibyte.html
# Python encodings:
# http://www.python.org/doc/2.4/lib/standard-encodings.html
#
# Commented out encodings don't require a name change between PostgreSQL and
# Python. If the py side is None, then the encoding isn't supported.
pg_to_py_encodings = {
# Not supported:
"mule_internal": None,
"euc_tw": None,
# Name fine as-is:
#"euc_jp",
#"euc_jis_2004",
#"euc_kr",
#"gb18030",
#"gbk",
#"johab",
#"sjis",
#"shift_jis_2004",
#"uhc",
#"utf8",
# Different name:
"euc_cn": "gb2312",
"iso_8859_5": "is8859_5",
"iso_8859_6": "is8859_6",
"iso_8859_7": "is8859_7",
"iso_8859_8": "is8859_8",
"koi8": "koi8_r",
"latin1": "iso8859-1",
"latin2": "iso8859_2",
"latin3": "iso8859_3",
"latin4": "iso8859_4",
"latin5": "iso8859_9",
"latin6": "iso8859_10",
"latin7": "iso8859_13",
"latin8": "iso8859_14",
"latin9": "iso8859_15",
"sql_ascii": "ascii",
"win866": "cp886",
"win874": "cp874",
"win1250": "cp1250",
"win1251": "cp1251",
"win1252": "cp1252",
"win1253": "cp1253",
"win1254": "cp1254",
"win1255": "cp1255",
"win1256": "cp1256",
"win1257": "cp1257",
"win1258": "cp1258",
}
def encoding_convert(encoding):
return pg_to_py_encodings.get(encoding.lower(), encoding)
def varcharin(data, client_encoding, **kwargs):
return unicode(data, encoding_convert(client_encoding))
def textout(v, client_encoding, **kwargs):
if isinstance(v, unicode):
return v.encode(encoding_convert(client_encoding))
else:
return v
def byteasend(v, **kwargs):
return str(v)
def bytearecv(data, **kwargs):
return Bytea(data)
# interval support does not provide a Python-usable interval object yet
def interval_recv(data, integer_datetimes, **kwargs):
if integer_datetimes:
microseconds, days, months = struct.unpack("!qii", data)
else:
seconds, days, months = struct.unpack("!dii", data)
microseconds = int(seconds * 1000 * 1000)
return Interval(microseconds, days, months)
def interval_send(data, integer_datetimes, **kwargs):
if integer_datetimes:
return struct.pack("!qii", data.microseconds, data.days, data.months)
else:
return struct.pack("!dii", data.microseconds / 1000.0 / 1000.0, data.days, data.months)
def array_recv(data, **kwargs):
dim, hasnull, typeoid = struct.unpack("!iii", data[:12])
data = data[12:]
# get type conversion method for typeoid
conversion = pg_types[typeoid]["bin_in"]
# Read dimension info
dim_lengths = []
element_count = 1
for idim in range(dim):
dim_len, dim_lbound = struct.unpack("!ii", data[:8])
data = data[8:]
dim_lengths.append(dim_len)
element_count *= dim_len
# Read all array values
array_values = []
for i in range(element_count):
if len(data):
element_len, = struct.unpack("!i", data[:4])
data = data[4:]
if element_len == -1:
array_values.append(None)
else:
array_values.append(conversion(data[:element_len], **kwargs))
data = data[element_len:]
if data != "":
raise ArrayDataParseError("unexpected data left over after array read")
# at this point, {{1,2,3},{4,5,6}}::int[][] looks like [1,2,3,4,5,6].
# go through the dimensions and fix up the array contents to match
# expected dimensions
for dim_length in reversed(dim_lengths[1:]):
val = []
while array_values:
val.append(array_values[:dim_length])
array_values = array_values[dim_length:]
array_values = val
return array_values
def array_inspect(value):
# Check if array has any values. If not, we can't determine the proper
# array typeoid.
first_element = array_find_first_element(value)
if first_element == None:
raise ArrayContentEmptyError("array has no values")
# supported array output
typ = type(first_element)
if issubclass(typ, int) or issubclass(typ, long):
# special int array support -- send as smallest possible array type
special_int_support = True
int2_ok, int4_ok, int8_ok = True, True, True
for v in array_flatten(value):
if v == None:
continue
if min_int2 < v < max_int2:
continue
int2_ok = False
if min_int4 < v < max_int4:
continue
int4_ok = False
if min_int8 < v < max_int8:
continue
int8_ok = False
if int2_ok:
array_typeoid = 1005 # INT2[]
elif int4_ok:
array_typeoid = 1007 # INT4[]
elif int8_ok:
array_typeoid = 1016 # INT8[]
else:
raise ArrayContentNotSupportedError("numeric not supported as array contents")
else:
special_int_support = False
array_typeoid = py_array_types.get(typ)
if array_typeoid == None:
raise ArrayContentNotSupportedError("type %r not supported as array contents" % typ)
# check for homogenous array
for v in array_flatten(value):
if v != None and not (isinstance(v, typ) or (typ == long and isinstance(v, int)) or (typ == int and isinstance(v, long))):
raise ArrayContentNotHomogenousError("not all array elements are of type %r" % typ)
# check that all array dimensions are consistent
array_check_dimensions(value)
type_data = py_types[typ]
if special_int_support:
if array_typeoid == 1005:
type_data = {"typeoid": 21, "bin_out": int2send}
elif array_typeoid == 1007:
type_data = {"typeoid": 23, "bin_out": int4send}
elif array_typeoid == 1016:
type_data = {"typeoid": 20, "bin_out": int8send}
else:
type_data = py_types[typ]
return {
"typeoid": array_typeoid,
"bin_out": array_send(type_data["typeoid"], type_data["bin_out"])
}
def array_find_first_element(arr):
for v in array_flatten(arr):
if v != None:
return v
return None
def array_flatten(arr):
for v in arr:
if isinstance(v, list):
for v2 in array_flatten(v):
yield v2
else:
yield v
def array_check_dimensions(arr):
v0 = arr[0]
if isinstance(v0, list):
req_len = len(v0)
req_inner_lengths = array_check_dimensions(v0)
for v in arr:
inner_lengths = array_check_dimensions(v)
if len(v) != req_len or inner_lengths != req_inner_lengths:
raise ArrayDimensionsNotConsistentError("array dimensions not consistent")
retval = [req_len]
retval.extend(req_inner_lengths)
return retval
else:
# make sure nothing else at this level is a list
for v in arr:
if isinstance(v, list):
raise ArrayDimensionsNotConsistentError("array dimensions not consistent")
return []
def array_has_null(arr):
for v in array_flatten(arr):
if v == None:
return True
return False
def array_dim_lengths(arr):
v0 = arr[0]
if isinstance(v0, list):
retval = [len(v0)]
retval.extend(array_dim_lengths(v0))
else:
return [len(arr)]
return retval
class array_send(object):
def __init__(self, typeoid, bin_out_func):
self.typeoid = typeoid
self.bin_out_func = bin_out_func
def __call__(self, arr, **kwargs):
has_null = array_has_null(arr)
dim_lengths = array_dim_lengths(arr)
data = struct.pack("!iii", len(dim_lengths), has_null, self.typeoid)
for i in dim_lengths:
data += struct.pack("!ii", i, 1)
for v in array_flatten(arr):
if v == None:
data += struct.pack("!i", -1)
else:
inner_data = self.bin_out_func(v, **kwargs)
data += struct.pack("!i", len(inner_data))
data += inner_data
return data
py_types = {
bool: {"typeoid": 16, "bin_out": boolsend},
int: {"inspect": int_inspect},
long: {"inspect": int_inspect},
str: {"typeoid": 25, "bin_out": textout},
unicode: {"typeoid": 25, "bin_out": textout},
float: {"typeoid": 701, "bin_out": float8send},
decimal.Decimal: {"typeoid": 1700, "bin_out": numeric_send},
Bytea: {"typeoid": 17, "bin_out": byteasend},
datetime.datetime: {"typeoid": 1114, "bin_out": timestamp_send, "inspect": datetime_inspect},
datetime.date: {"typeoid": 1082, "txt_out": date_out},
datetime.time: {"typeoid": 1083, "txt_out": time_out},
Interval: {"typeoid": 1186, "bin_out": interval_send},
type(None): {"typeoid": -1},
list: {"inspect": array_inspect},
}
# py type -> pg array typeoid
py_array_types = {
float: 1022,
bool: 1000,
str: 1009, # TEXT[]
unicode: 1009, # TEXT[]
decimal.Decimal: 1231, # NUMERIC[]
}
pg_types = {
16: {"bin_in": boolrecv},
17: {"bin_in": bytearecv},
19: {"bin_in": varcharin}, # name type
20: {"bin_in": int8recv},
21: {"bin_in": int2recv},
23: {"bin_in": int4recv, "txt_in": numeric_in},
25: {"bin_in": varcharin, "txt_in": varcharin}, # TEXT type
26: {"txt_in": numeric_in}, # oid type
142: {"bin_in": varcharin, "txt_in": varcharin}, # XML
194: {"bin_in": varcharin}, # "string representing an internal node tree"
700: {"bin_in": float4recv},
701: {"bin_in": float8recv},
705: {"txt_in": varcharin}, # UNKNOWN
829: {"txt_in": varcharin}, # MACADDR type
1000: {"bin_in": array_recv}, # BOOL[]
1003: {"bin_in": array_recv}, # NAME[]
1005: {"bin_in": array_recv}, # INT2[]
1007: {"bin_in": array_recv, "txt_in": varcharin}, # INT4[]
1009: {"bin_in": array_recv}, # TEXT[]
1014: {"bin_in": array_recv}, # CHAR[]
1015: {"bin_in": array_recv}, # VARCHAR[]
1016: {"bin_in": array_recv}, # INT8[]
1021: {"bin_in": array_recv}, # FLOAT4[]
1022: {"bin_in": array_recv}, # FLOAT8[]
1042: {"bin_in": varcharin}, # CHAR type
1043: {"bin_in": varcharin}, # VARCHAR type
1082: {"txt_in": date_in},
1083: {"txt_in": time_in},
1114: {"bin_in": timestamp_recv},
1184: {"bin_in": timestamptz_recv}, # timestamp w/ tz
1186: {"bin_in": interval_recv},
1231: {"bin_in": array_recv}, # NUMERIC[]
1263: {"bin_in": array_recv}, # cstring[]
1700: {"bin_in": numeric_recv},
2275: {"bin_in": varcharin}, # cstring
}
| Python |
# vim: sw=4:expandtab:foldmethod=marker
#
# Copyright (c) 2007-2009, Mathieu Fenniak
# 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.
# * The name of the author may not be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# 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__ = "Mathieu Fenniak"
import dbapi as DBAPI
pg8000_dbapi = DBAPI
from interface import *
from types import Bytea
| Python |
# vim: sw=4:expandtab:foldmethod=marker
#
# Copyright (c) 2007-2009, Mathieu Fenniak
# 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.
# * The name of the author may not be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# 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__ = "Mathieu Fenniak"
import socket
import protocol
import threading
from errors import *
def conninfo_parse(conninfo):
"Conninfo parser routine based on libpq conninfo_parse"
options = {}
buf = conninfo + " "
tmp = pname = ""
quoted_string = False
cp = 0
while cp < len(buf):
# Skip blanks before the parameter name
c = buf[cp]
if c.isspace() and tmp and not quoted_string and pname:
options[pname] = tmp
tmp = pname = ""
elif c == "'":
quoted_string = not quoted_string
elif c == '\\':
cp += 1
tmp += buf[cp]
elif c == "=":
if not tmp:
raise RuntimeError("missing parameter name (conninfo:%s)" % cp)
pname = tmp
tmp = ""
elif not c.isspace() or quoted_string:
tmp += c
cp += 1
if quoted_string:
raise RuntimeError("unterminated quoted string (conninfo:%s)" % cp)
return options
class DataIterator(object):
def __init__(self, obj, func):
self.obj = obj
self.func = func
def __iter__(self):
return self
def next(self):
retval = self.func(self.obj)
if retval == None:
raise StopIteration()
return retval
statement_number_lock = threading.Lock()
statement_number = 0
##
# This class represents a prepared statement. A prepared statement is
# pre-parsed on the server, which reduces the need to parse the query every
# time it is run. The statement can have parameters in the form of $1, $2, $3,
# etc. When parameters are used, the types of the parameters need to be
# specified when creating the prepared statement.
# <p>
# As of v1.01, instances of this class are thread-safe. This means that a
# single PreparedStatement can be accessed by multiple threads without the
# internal consistency of the statement being altered. However, the
# responsibility is on the client application to ensure that one thread reading
# from a statement isn't affected by another thread starting a new query with
# the same statement.
# <p>
# Stability: Added in v1.00, stability guaranteed for v1.xx.
#
# @param connection An instance of {@link Connection Connection}.
#
# @param statement The SQL statement to be represented, often containing
# parameters in the form of $1, $2, $3, etc.
#
# @param types Python type objects for each parameter in the SQL
# statement. For example, int, float, str.
class PreparedStatement(object):
##
# Determines the number of rows to read from the database server at once.
# Reading more rows increases performance at the cost of memory. The
# default value is 100 rows. The affect of this parameter is transparent.
# That is, the library reads more rows when the cache is empty
# automatically.
# <p>
# Stability: Added in v1.00, stability guaranteed for v1.xx. It is
# possible that implementation changes in the future could cause this
# parameter to be ignored.
row_cache_size = 100
def __init__(self, connection, statement, *types, **kwargs):
global statement_number
if connection == None or connection.c == None:
raise InterfaceError("connection not provided")
try:
statement_number_lock.acquire()
self._statement_number = statement_number
statement_number += 1
finally:
statement_number_lock.release()
self.c = connection.c
self._portal_name = None
self._statement_name = kwargs.get("statement_name", "pg8000_statement_%s" % self._statement_number)
self._row_desc = None
self._cached_rows = []
self._ongoing_row_count = 0
self._command_complete = True
self._parse_row_desc = self.c.parse(self._statement_name, statement, types)
self._lock = threading.RLock()
def close(self):
if self._statement_name != "": # don't close unnamed statement
self.c.close_statement(self._statement_name)
if self._portal_name != None:
self.c.close_portal(self._portal_name)
self._portal_name = None
row_description = property(lambda self: self._getRowDescription())
def _getRowDescription(self):
if self._row_desc == None:
return None
return self._row_desc.fields
##
# Run the SQL prepared statement with the given parameters.
# <p>
# Stability: Added in v1.00, stability guaranteed for v1.xx.
def execute(self, *args, **kwargs):
self._lock.acquire()
try:
if not self._command_complete:
# cleanup last execute
self._cached_rows = []
self._ongoing_row_count = 0
if self._portal_name != None:
self.c.close_portal(self._portal_name)
self._command_complete = False
self._portal_name = "pg8000_portal_%s" % self._statement_number
self._row_desc, cmd = self.c.bind(self._portal_name, self._statement_name, args, self._parse_row_desc, kwargs.get("stream"))
if self._row_desc:
# We execute our cursor right away to fill up our cache. This
# prevents the cursor from being destroyed, apparently, by a rogue
# Sync between Bind and Execute. Since it is quite likely that
# data will be read from us right away anyways, this seems a safe
# move for now.
self._fill_cache()
else:
self._command_complete = True
self._ongoing_row_count = -1
if cmd != None and cmd.rows != None:
self._ongoing_row_count = cmd.rows
finally:
self._lock.release()
def _fill_cache(self):
self._lock.acquire()
try:
if self._cached_rows:
raise InternalError("attempt to fill cache that isn't empty")
end_of_data, rows = self.c.fetch_rows(self._portal_name, self.row_cache_size, self._row_desc)
self._cached_rows = rows
if end_of_data:
self._command_complete = True
finally:
self._lock.release()
def _fetch(self):
if not self._row_desc:
raise ProgrammingError("no result set")
self._lock.acquire()
try:
if not self._cached_rows:
if self._command_complete:
return None
self._fill_cache()
if self._command_complete and not self._cached_rows:
# fill cache tells us the command is complete, but yet we have
# no rows after filling our cache. This is a special case when
# a query returns no rows.
return None
row = self._cached_rows.pop(0)
self._ongoing_row_count += 1
return tuple(row)
finally:
self._lock.release()
##
# Return a count of the number of rows relevant to the executed statement.
# For a SELECT, this is the number of rows returned. For UPDATE or DELETE,
# this the number of rows affected. For INSERT, the number of rows
# inserted. This property may have a value of -1 to indicate that there
# was no row count.
# <p>
# During a result-set query (eg. SELECT, or INSERT ... RETURNING ...),
# accessing this property requires reading the entire result-set into
# memory, as reading the data to completion is the only way to determine
# the total number of rows. Avoid using this property in with
# result-set queries, as it may cause unexpected memory usage.
# <p>
# Stability: Added in v1.03, stability guaranteed for v1.xx.
row_count = property(lambda self: self._get_row_count())
def _get_row_count(self):
self._lock.acquire()
try:
if not self._command_complete:
end_of_data, rows = self.c.fetch_rows(self._portal_name, 0, self._row_desc)
self._cached_rows += rows
if end_of_data:
self._command_complete = True
else:
raise InternalError("fetch_rows(0) did not hit end of data")
return self._ongoing_row_count + len(self._cached_rows)
finally:
self._lock.release()
##
# Read a row from the database server, and return it in a dictionary
# indexed by column name/alias. This method will raise an error if two
# columns have the same name. Returns None after the last row.
# <p>
# Stability: Added in v1.00, stability guaranteed for v1.xx.
def read_dict(self):
row = self._fetch()
if row == None:
return row
retval = {}
for i in range(len(self._row_desc.fields)):
col_name = self._row_desc.fields[i]['name']
if retval.has_key(col_name):
raise InterfaceError("cannot return dict of row when two columns have the same name (%r)" % (col_name,))
retval[col_name] = row[i]
return retval
##
# Read a row from the database server, and return it as a tuple of values.
# Returns None after the last row.
# <p>
# Stability: Added in v1.00, stability guaranteed for v1.xx.
def read_tuple(self):
return self._fetch()
##
# Return an iterator for the output of this statement. The iterator will
# return a tuple for each row, in the same manner as {@link
# #PreparedStatement.read_tuple read_tuple}.
# <p>
# Stability: Added in v1.00, stability guaranteed for v1.xx.
def iterate_tuple(self):
return DataIterator(self, PreparedStatement.read_tuple)
##
# Return an iterator for the output of this statement. The iterator will
# return a dict for each row, in the same manner as {@link
# #PreparedStatement.read_dict read_dict}.
# <p>
# Stability: Added in v1.00, stability guaranteed for v1.xx.
def iterate_dict(self):
return DataIterator(self, PreparedStatement.read_dict)
class SimpleStatement(PreparedStatement):
"Internal wrapper to Simple Query protocol emulating a PreparedStatement"
# This should be used internally only for trivial queries
# (not a true Prepared Statement, in fact it can have multiple statements)
# See Simple Query Protocol limitations and trade-offs (send_simple_query)
row_cache_size = None
def __init__(self, connection, statement):
if connection == None or connection.c == None:
raise InterfaceError("connection not provided")
self.c = connection.c
self._row_desc = None
self._cached_rows = []
self._ongoing_row_count = -1
self._command_complete = True
self.statement = statement
self._lock = threading.RLock()
def close(self):
# simple query doesn't have portals
pass
def execute(self, *args, **kwargs):
"Run the SQL simple query stataments"
self._lock.acquire()
try:
self._row_desc, cmd_complete, self._cached_rows = \
self.c.send_simple_query(self.statement, kwargs.get("stream"))
self._command_complete = True
self._ongoing_row_count = -1
if cmd_complete is not None and cmd_complete.rows is not None:
self._ongoing_row_count = cmd_complete.rows
finally:
self._lock.release()
def _fill_cache(self):
# data rows are already fetched in _cached_rows
pass
def _fetch(self):
if not self._row_desc:
raise ProgrammingError("no result set")
self._lock.acquire()
try:
if not self._cached_rows:
return None
row = self._cached_rows.pop(0)
return tuple(row)
finally:
self._lock.release()
def _get_row_count(self):
return self._ongoing_row_count
##
# The Cursor class allows multiple queries to be performed concurrently with a
# single PostgreSQL connection. The Cursor object is implemented internally by
# using a {@link PreparedStatement PreparedStatement} object, so if you plan to
# use a statement multiple times, you might as well create a PreparedStatement
# and save a small amount of reparsing time.
# <p>
# As of v1.01, instances of this class are thread-safe. See {@link
# PreparedStatement PreparedStatement} for more information.
# <p>
# Stability: Added in v1.00, stability guaranteed for v1.xx.
#
# @param connection An instance of {@link Connection Connection}.
class Cursor(object):
def __init__(self, connection):
self.connection = connection
self._stmt = None
def require_stmt(func):
def retval(self, *args, **kwargs):
if self._stmt == None:
raise ProgrammingError("attempting to use unexecuted cursor")
return func(self, *args, **kwargs)
return retval
row_description = property(lambda self: self._getRowDescription())
def _getRowDescription(self):
if self._stmt == None:
return None
return self._stmt.row_description
##
# Run an SQL statement using this cursor. The SQL statement can have
# parameters in the form of $1, $2, $3, etc., which will be filled in by
# the additional arguments passed to this function.
# <p>
# Stability: Added in v1.00, stability guaranteed for v1.xx.
# @param query The SQL statement to execute.
def execute(self, query, *args, **kwargs):
if self.connection.is_closed:
raise ConnectionClosedError()
self.connection._unnamed_prepared_statement_lock.acquire()
try:
if kwargs.get("simple_query"):
# no arguments and no statement name,
# use PostgreSQL Simple Query Protocol
## print "SimpleQuery:", query
self._stmt = SimpleStatement(self.connection, query)
else:
# use PostgreSQL Extended Query Protocol
self._stmt = PreparedStatement(self.connection, query, statement_name="", *[{"type": type(x), "value": x} for x in args])
self._stmt.execute(*args, **kwargs)
finally:
self.connection._unnamed_prepared_statement_lock.release()
##
# Return a count of the number of rows currently being read. If possible,
# please avoid using this function. It requires reading the entire result
# set from the database to determine the number of rows being returned.
# <p>
# Stability: Added in v1.03, stability guaranteed for v1.xx.
# Implementation currently requires caching entire result set into memory,
# avoid using this property.
row_count = property(lambda self: self._get_row_count())
@require_stmt
def _get_row_count(self):
return self._stmt.row_count
##
# Read a row from the database server, and return it in a dictionary
# indexed by column name/alias. This method will raise an error if two
# columns have the same name. Returns None after the last row.
# <p>
# Stability: Added in v1.00, stability guaranteed for v1.xx.
@require_stmt
def read_dict(self):
return self._stmt.read_dict()
##
# Read a row from the database server, and return it as a tuple of values.
# Returns None after the last row.
# <p>
# Stability: Added in v1.00, stability guaranteed for v1.xx.
@require_stmt
def read_tuple(self):
return self._stmt.read_tuple()
##
# Return an iterator for the output of this statement. The iterator will
# return a tuple for each row, in the same manner as {@link
# #PreparedStatement.read_tuple read_tuple}.
# <p>
# Stability: Added in v1.00, stability guaranteed for v1.xx.
@require_stmt
def iterate_tuple(self):
return self._stmt.iterate_tuple()
##
# Return an iterator for the output of this statement. The iterator will
# return a dict for each row, in the same manner as {@link
# #PreparedStatement.read_dict read_dict}.
# <p>
# Stability: Added in v1.00, stability guaranteed for v1.xx.
@require_stmt
def iterate_dict(self):
return self._stmt.iterate_dict()
def close(self):
if self._stmt != None:
self._stmt.close()
self._stmt = None
##
# Return the fileno of the underlying socket for this cursor's connection.
# <p>
# Stability: Added in v1.07, stability guaranteed for v1.xx.
def fileno(self):
return self.connection.fileno()
##
# Poll the underlying socket for this cursor and sync if there is data waiting
# to be read. This has the effect of flushing asynchronous messages from the
# backend. Returns True if messages were read, False otherwise.
# <p>
# Stability: Added in v1.07, stability guaranteed for v1.xx.
def isready(self):
return self.connection.isready()
##
# This class represents a connection to a PostgreSQL database.
# <p>
# The database connection is derived from the {@link #Cursor Cursor} class,
# which provides a default cursor for running queries. It also provides
# transaction control via the 'begin', 'commit', and 'rollback' methods.
# Without beginning a transaction explicitly, all statements will autocommit to
# the database.
# <p>
# As of v1.01, instances of this class are thread-safe. See {@link
# PreparedStatement PreparedStatement} for more information.
# <p>
# Stability: Added in v1.00, stability guaranteed for v1.xx.
#
# @param user The username to connect to the PostgreSQL server with. This
# parameter is required.
#
# @keyparam host The hostname of the PostgreSQL server to connect with.
# Providing this parameter is necessary for TCP/IP connections. One of either
# host, or unix_sock, must be provided.
#
# @keyparam unix_sock The path to the UNIX socket to access the database
# through, for example, '/tmp/.s.PGSQL.5432'. One of either unix_sock or host
# must be provided. The port parameter will have no affect if unix_sock is
# provided.
#
# @keyparam port The TCP/IP port of the PostgreSQL server instance. This
# parameter defaults to 5432, the registered and common port of PostgreSQL
# TCP/IP servers.
#
# @keyparam database The name of the database instance to connect with. This
# parameter is optional, if omitted the PostgreSQL server will assume the
# database name is the same as the username.
#
# @keyparam password The user password to connect to the server with. This
# parameter is optional. If omitted, and the database server requests password
# based authentication, the connection will fail. On the other hand, if this
# parameter is provided and the database does not request password
# authentication, then the password will not be used.
#
# @keyparam socket_timeout Socket connect timeout measured in seconds.
# Defaults to 60 seconds.
#
# @keyparam ssl Use SSL encryption for TCP/IP socket. Defaults to False.
class Connection(Cursor):
def __init__(self, dsn="", user=None, host=None, unix_sock=None, port=5432, database=None, password=None, socket_timeout=60, ssl=False):
self._row_desc = None
if dsn:
# update connection parameters parsed of the conninfo dsn
opts = conninfo_parse(dsn)
database = opts.get("dbname", database)
user = opts.get("user", user)
password = opts.get("password", user)
host = opts.get("host", host)
port = int(opts.get("port", port))
ssl = opts.get("sslmode", 'disable') != 'disable'
try:
self.c = protocol.Connection(unix_sock=unix_sock, host=host, port=port, socket_timeout=socket_timeout, ssl=ssl)
self.c.authenticate(user, password=password, database=database)
except socket.error, e:
raise InterfaceError("communication error", e)
Cursor.__init__(self, self)
self._begin = PreparedStatement(self, "BEGIN TRANSACTION")
self._commit = PreparedStatement(self, "COMMIT TRANSACTION")
self._rollback = PreparedStatement(self, "ROLLBACK TRANSACTION")
self._unnamed_prepared_statement_lock = threading.RLock()
self.in_transaction = False
self.autocommit = False
##
# An event handler that is fired when NOTIFY occurs for a notification that
# has been LISTEN'd for. The value of this property is a
# util.MulticastDelegate. A callback can be added by using
# connection.NotificationReceived += SomeMethod. The method will be called
# with a single argument, an object that has properties: backend_pid,
# condition, and additional_info. Callbacks can be removed with the -=
# operator.
# <p>
# Stability: Added in v1.03, stability guaranteed for v1.xx.
NotificationReceived = property(
lambda self: getattr(self.c, "NotificationReceived"),
lambda self, value: setattr(self.c, "NotificationReceived", value)
)
##
# An event handler that is fired when the database server issues a notice.
# The value of this property is a util.MulticastDelegate. A callback can
# be added by using connection.NotificationReceived += SomeMethod. The
# method will be called with a single argument, an object that has
# properties: severity, code, msg, and possibly others (detail, hint,
# position, where, file, line, and routine). Callbacks can be removed with
# the -= operator.
# <p>
# Stability: Added in v1.03, stability guaranteed for v1.xx.
NoticeReceived = property(
lambda self: getattr(self.c, "NoticeReceived"),
lambda self, value: setattr(self.c, "NoticeReceived", value)
)
##
# An event handler that is fired when a runtime configuration option is
# changed on the server. The value of this property is a
# util.MulticastDelegate. A callback can be added by using
# connection.NotificationReceived += SomeMethod. Callbacks can be removed
# with the -= operator. The method will be called with a single argument,
# an object that has properties "key" and "value".
# <p>
# Stability: Added in v1.03, stability guaranteed for v1.xx.
ParameterStatusReceived = property(
lambda self: getattr(self.c, "ParameterStatusReceived"),
lambda self, value: setattr(self.c, "ParameterStatusReceived", value)
)
##
# Begins a new transaction.
# <p>
# Stability: Added in v1.00, stability guaranteed for v1.xx.
def begin(self):
if self.is_closed:
raise ConnectionClosedError()
if self.autocommit:
return
self._begin.execute()
self.in_transaction = True
##
# Commits the running transaction.
# <p>
# Stability: Added in v1.00, stability guaranteed for v1.xx.
def commit(self):
if self.is_closed:
raise ConnectionClosedError()
self._commit.execute()
self.in_transaction = False
##
# Rolls back the running transaction.
# <p>
# Stability: Added in v1.00, stability guaranteed for v1.xx.
def rollback(self):
if self.is_closed:
raise ConnectionClosedError()
self._rollback.execute()
self.in_transaction = False
##
# Closes an open connection.
def close(self):
if self.is_closed:
raise ConnectionClosedError()
self.c.close()
self.c = None
is_closed = property(lambda self: self.c == None)
##
# Return the fileno of the underlying socket for this connection.
# <p>
# Stability: Added in v1.07, stability guaranteed for v1.xx.
def fileno(self):
return self.c.fileno()
##
# Poll the underlying socket for this connection and sync if there is data
# waiting to be read. This has the effect of flushing asynchronous
# messages from the backend. Returns True if messages were read, False
# otherwise.
# <p>
# Stability: Added in v1.07, stability guaranteed for v1.xx.
def isready(self):
return self.c.isready()
##
# Return the server_version as reported from the connected server.
# Raises InterfaceError if no version has been reported from the server.
def server_version(self):
return self.c.server_version()
def encoding(self, encoding=None):
"Returns the client_encoding as reported from the connected server"
return self.c.encoding() | Python |
# vim: sw=4:expandtab:foldmethod=marker
#
# Copyright (c) 2007-2009, Mathieu Fenniak
# 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.
# * The name of the author may not be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# 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__ = "Mathieu Fenniak"
class Warning(StandardError):
pass
class Error(StandardError):
pass
class InterfaceError(Error):
pass
class ConnectionClosedError(InterfaceError):
def __init__(self):
InterfaceError.__init__(self, "connection is closed")
class CursorClosedError(InterfaceError):
def __init__(self):
InterfaceError.__init__(self, "cursor is closed")
class DatabaseError(Error):
pass
class DataError(DatabaseError):
pass
class OperationalError(DatabaseError):
pass
class IntegrityError(DatabaseError):
pass
class InternalError(DatabaseError):
pass
class ProgrammingError(DatabaseError):
pass
class NotSupportedError(DatabaseError):
pass
##
# An exception that is thrown when an internal error occurs trying to
# decode binary array data from the server.
class ArrayDataParseError(InternalError):
pass
##
# Thrown when attempting to transmit an array of unsupported data types.
class ArrayContentNotSupportedError(NotSupportedError):
pass
##
# Thrown when attempting to send an array that doesn't contain all the same
# type of objects (eg. some floats, some ints).
class ArrayContentNotHomogenousError(ProgrammingError):
pass
##
# Attempted to pass an empty array in, but it's not possible to determine the
# data type for an empty array.
class ArrayContentEmptyError(ProgrammingError):
pass
##
# Attempted to use a multidimensional array with inconsistent array sizes.
class ArrayDimensionsNotConsistentError(ProgrammingError):
pass
# A cursor's copy_to or copy_from argument was not provided a table or query
# to operate on.
class CopyQueryOrTableRequiredError(ProgrammingError):
pass
# Raised if a COPY query is executed without using copy_to or copy_from
# functions to provide a data stream.
class CopyQueryWithoutStreamError(ProgrammingError):
pass
# When query parameters don't match up with query args.
class QueryParameterIndexError(ProgrammingError):
pass
# Some sort of parse error occured during query parameterization.
class QueryParameterParseError(ProgrammingError):
pass
| 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
"Queues(Pipe)-based independent remote client-server Python Debugger"
__author__ = "Mariano Reingart (reingart@gmail.com)"
__copyright__ = "Copyright (C) 2011 Mariano Reingart"
__license__ = "LGPL 3.0"
__version__ = "1.01b"
# remote debugger queue-based (jsonrpc-like interface):
# - bidirectional communication (request - response calls in both ways)
# - request with id == null is a notification (do not send a response)
# - request with a value for id is a normal call, wait response
# based on idle, inspired by pythonwin implementation, taken many code from pdb
import bdb
import inspect
import linecache
import os
import sys
import traceback
import cmd
import pydoc
import threading
class Qdb(bdb.Bdb):
"Qdb Debugger Backend"
def __init__(self, pipe, redirect_stdio=True, allow_interruptions=False,
skip=[__name__]):
kwargs = {}
if sys.version_info > (2, 7):
kwargs['skip'] = skip
bdb.Bdb.__init__(self, **kwargs)
self.frame = None
self.i = 1 # sequential RPC call id
self.waiting = False
self.pipe = pipe # for communication
self._wait_for_mainpyfile = False
self._wait_for_breakpoint = False
self.mainpyfile = ""
self._lineno = None # last listed line numbre
# replace system standard input and output (send them thru the pipe)
if redirect_stdio:
sys.stdin = self
sys.stdout = self
sys.stderr = self
if allow_interruptions:
# fake breakpoint to prevent removing trace_dispatch on set_continue
self.breaks[None] = []
self.allow_interruptions = allow_interruptions
self.burst = 0 # do not send notifications ("burst" mode)
self.params = {} # optional parameters for interaction
def pull_actions(self):
# receive a remote procedure call from the frontend:
# returns True if action processed
# None when 'run' notification is received (see 'startup')
request = self.pipe.recv()
if request.get("method") == 'run':
return None
response = {'version': '1.1', 'id': request.get('id'),
'result': None,
'error': None}
try:
# dispatch message (JSON RPC like)
method = getattr(self, request['method'])
response['result'] = method.__call__(*request['args'],
**request.get('kwargs', {}))
except Exception, e:
response['error'] = {'code': 0, 'message': str(e)}
# send the result for normal method calls, not for notifications
if request.get('id'):
self.pipe.send(response)
return True
# Override Bdb methods
def trace_dispatch(self, frame, event, arg):
# check for non-interaction rpc (set_breakpoint, interrupt)
while self.allow_interruptions and self.pipe.poll():
self.pull_actions()
# process the frame (see Bdb.trace_dispatch)
if self.quitting:
return # None
if event == 'line':
return self.dispatch_line(frame)
if event == 'call':
return self.dispatch_call(frame, arg)
if event == 'return':
return self.dispatch_return(frame, arg)
if event == 'exception':
return self.dispatch_exception(frame, arg)
return self.trace_dispatch
def user_call(self, frame, argument_list):
"""This method is called when there is the remote possibility
that we ever need to stop in this function."""
if self._wait_for_mainpyfile or self._wait_for_breakpoint:
return
if self.stop_here(frame):
self.interaction(frame, None)
def user_line(self, frame):
"""This function is called when we stop or break at this line."""
if self._wait_for_mainpyfile:
if (not self.canonic(frame.f_code.co_filename).startswith(self.mainpyfile)
or frame.f_lineno<= 0):
return
self._wait_for_mainpyfile = 0
if self._wait_for_breakpoint:
if not self.break_here(frame):
return
self._wait_for_breakpoint = 0
self.interaction(frame)
def user_exception(self, frame, info):
"""This function is called if an exception occurs,
but only if we are to stop at or just below this level."""
if self._wait_for_mainpyfile or self._wait_for_breakpoint:
return
extype, exvalue, trace = info
# pre-process stack trace as it isn't pickeable (cannot be sent pure)
msg = ''.join(traceback.format_exception(extype, exvalue, trace))
trace = traceback.extract_tb(trace)
title = traceback.format_exception_only(extype, exvalue)[0]
# send an Exception notification
msg = {'method': 'exception',
'args': (title, extype.__name__, exvalue, trace, msg),
'id': None}
self.pipe.send(msg)
self.interaction(frame, info)
def run(self, code, interp=None, *args, **kwargs):
try:
return bdb.Bdb.run(self, code, *args, **kwargs)
finally:
pass
def runcall(self, function, interp=None, *args, **kwargs):
try:
self.interp = interp
return bdb.Bdb.runcall(self, function, *args, **kwargs)
finally:
pass
def _runscript(self, filename):
# The script has to run in __main__ namespace (clear it)
import __main__
import imp
__main__.__dict__.clear()
__main__.__dict__.update({"__name__" : "__main__",
"__file__" : filename,
"__builtins__": __builtins__,
"imp" : imp, # need for run
})
# avoid stopping before we reach the main script
self._wait_for_mainpyfile = 1
self.mainpyfile = self.canonic(filename)
self._user_requested_quit = 0
statement = 'imp.load_source("__main__", "%s")' % filename
# notify and wait frontend to set initial params and breakpoints
self.pipe.send({'method': 'startup', 'args': (__version__, )})
while self.pull_actions() is not None:
pass
self.run(statement)
# General interaction function
def interaction(self, frame, info=None):
# chache frame locals to ensure that modifications are not overwritten
self.frame_locals = frame and frame.f_locals or {}
# extract current filename and line number
code, lineno = frame.f_code, frame.f_lineno
filename = code.co_filename
basename = os.path.basename(filename)
message = "%s:%s" % (basename, lineno)
if code.co_name != "?":
message = "%s: %s()" % (message, code.co_name)
# wait user events
self.waiting = True
self.frame = frame
try:
while self.waiting:
# sync_source_line()
if frame and filename[:1] + filename[-1:] != "<>" and os.path.exists(filename):
line = linecache.getline(filename, self.frame.f_lineno,
self.frame.f_globals)
else:
line = ""
# send the notification (debug event) - DOESN'T WAIT RESPONSE
self.burst -= 1
if self.burst < 0:
kwargs = {}
if self.params.get('call_stack'):
kwargs['call_stack'] = self.do_where()
if self.params.get('environment'):
kwargs['environment'] = self.do_environment()
self.pipe.send({'method': 'interaction', 'id': None,
'args': (filename, self.frame.f_lineno, line),
'kwargs': kwargs})
self.pull_actions()
finally:
self.waiting = False
self.frame = None
def do_debug(self, mainpyfile=None, wait_breakpoint=1):
self.reset()
if not wait_breakpoint or mainpyfile:
self._wait_for_mainpyfile = 1
if not mainpyfile:
frame = sys._getframe().f_back
mainpyfile = frame.f_code.co_filename
self.mainpyfile = self.canonic(mainpyfile)
self._wait_for_breakpoint = wait_breakpoint
sys.settrace(self.trace_dispatch)
def set_trace(self, frame=None):
# start debugger interaction immediatelly
if frame is None:
frame = sys._getframe().f_back
self._wait_for_mainpyfile = frame.f_code.co_filename
self._wait_for_breakpoint = 0
bdb.Bdb.set_trace(self, frame)
# Command definitions, called by interaction()
def do_continue(self):
self.set_continue()
self.waiting = False
def do_step(self):
self.set_step()
self.waiting = False
def do_return(self):
self.set_return(self.frame)
self.waiting = False
def do_next(self):
self.set_next(self.frame)
self.waiting = False
def interrupt(self):
self.set_step()
def do_quit(self):
self.set_quit()
self.waiting = False
def do_jump(self, lineno):
arg = int(lineno)
try:
self.frame.f_lineno = arg
return arg
except ValueError, e:
print '*** Jump failed:', e
return False
def do_list(self, arg):
last = None
if arg:
if isinstance(arg, tuple):
first, last = arg
else:
first = arg
elif not self._lineno:
first = max(1, self.frame.f_lineno - 5)
else:
first = self._lineno + 1
if last is None:
last = first + 10
filename = self.frame.f_code.co_filename
breaklist = self.get_file_breaks(filename)
lines = []
for lineno in range(first, last+1):
line = linecache.getline(filename, lineno,
self.frame.f_globals)
if not line:
lines.append((filename, lineno, '', current, "<EOF>\n"))
break
else:
breakpoint = "B" if lineno in breaklist else ""
current = "->" if self.frame.f_lineno == lineno else ""
lines.append((filename, lineno, breakpoint, current, line))
self._lineno = lineno
return lines
def do_read(self, filename):
return open(filename, "Ur").read()
def do_set_breakpoint(self, filename, lineno, temporary=0, cond=None):
return self.set_break(filename, int(lineno), temporary, cond)
def do_list_breakpoint(self):
breaks = []
if self.breaks: # There's at least one
for bp in bdb.Breakpoint.bpbynumber:
if bp:
breaks.append((bp.number, bp.file, bp.line,
bp.temporary, bp.enabled, bp.hits, bp.cond, ))
return breaks
def do_clear_breakpoint(self, filename, lineno):
self.clear_break(filename, lineno)
def do_clear_file_breakpoints(self, filename):
self.clear_all_file_breaks(filename)
def do_clear(self, arg):
# required by BDB to remove temp breakpoints!
err = self.clear_bpbynumber(arg)
if err:
print '*** DO_CLEAR failed', err
def do_eval(self, arg, safe=True):
ret = eval(arg, self.frame.f_globals,
self.frame_locals)
if safe:
ret = pydoc.cram(repr(ret), 255)
return ret
def do_exec(self, arg):
locals = self.frame_locals
globals = self.frame.f_globals
code = compile(arg + '\n', '<stdin>', 'single')
save_displayhook = sys.displayhook
self.displayhook_value = None
try:
sys.displayhook = self.displayhook
exec code in globals, locals
finally:
sys.displayhook = save_displayhook
return self.displayhook_value
def do_where(self):
"print_stack_trace"
stack, curindex = self.get_stack(self.frame, None)
lines = []
for frame, lineno in stack:
filename = frame.f_code.co_filename
line = linecache.getline(filename, lineno)
lines.append((filename, lineno, "", "", line, ))
return lines
def do_environment(self):
"return current frame local and global environment"
env = {'locals': {}, 'globals': {}}
# converts the frame global and locals to a short text representation:
if self.frame:
for name, value in self.frame_locals.items():
env['locals'][name] = pydoc.cram(repr(value), 255), repr(type(value))
for name, value in self.frame.f_globals.items():
env['globals'][name] = pydoc.cram(repr(value), 20), repr(type(value))
return env
def get_autocomplete_list(self, expression):
"Return list of auto-completion options for expression"
try:
obj = self.do_eval(expression)
except:
return []
else:
return dir(obj)
def get_call_tip(self, expression):
"Return list of auto-completion options for expression"
try:
obj = self.do_eval(expression)
except Exception, e:
return ('', '', str(e))
else:
name = ''
try:
name = obj.__name__
except AttributeError:
pass
argspec = ''
drop_self = 0
f = None
try:
if inspect.isbuiltin(obj):
pass
elif inspect.ismethod(obj):
# Get the function from the object
f = obj.im_func
drop_self = 1
elif inspect.isclass(obj):
# Get the __init__ method function for the class.
if hasattr(obj, '__init__'):
f = obj.__init__.im_func
else:
for base in object.__bases__:
if hasattr(base, '__init__'):
f = base.__init__.im_func
break
if f is not None:
drop_self = 1
elif callable(obj):
# use the obj as a function by default
f = obj
# Get the __call__ method instead.
f = obj.__call__.im_func
drop_self = 0
except AttributeError:
pass
if f:
argspec = apply(inspect.formatargspec, inspect.getargspec(f))
doc = ''
if callable(obj):
try:
doc = inspect.getdoc(obj)
except:
pass
return (name, argspec[1:-1], doc.strip())
def set_burst(self, val):
"Set burst mode -multiple command count- (shut up notifications)"
self.burst = val
def set_params(self, params):
"Set parameters for interaction"
self.params.update(params)
def displayhook(self, obj):
"""Custom displayhook for the do_exec which prevents
assignment of the _ variable in the builtins.
"""
self.displayhook_value = repr(obj)
def reset(self):
bdb.Bdb.reset(self)
self.waiting = False
self.frame = None
def post_mortem(self, t=None):
# handling the default
if t is None:
# sys.exc_info() returns (type, value, traceback) if an exception is
# being handled, otherwise it returns None
t = sys.exc_info()[2]
if t is None:
raise ValueError("A valid traceback must be passed if no "
"exception is being handled")
self.reset()
# get last frame:
while t is not None:
frame = t.tb_frame
t = t.tb_next
code, lineno = frame.f_code, frame.f_lineno
filename = code.co_filename
line = linecache.getline(filename, lineno)
#(filename, lineno, "", current, line, )}
self.interaction(frame)
# console file-like object emulation
def readline(self):
"Replacement for stdin.readline()"
msg = {'method': 'readline', 'args': (), 'id': self.i}
self.pipe.send(msg)
msg = self.pipe.recv()
self.i += 1
return msg['result']
def readlines(self):
"Replacement for stdin.readlines()"
lines = []
while lines[-1:] != ['\n']:
lines.append(self.readline())
return lines
def write(self, text):
"Replacement for stdout.write()"
msg = {'method': 'write', 'args': (text, ), 'id': None}
self.pipe.send(msg)
def writelines(self, l):
map(self.write, l)
def flush(self):
pass
def isatty(self):
return 0
class QueuePipe(object):
"Simulated pipe for threads (using two queues)"
def __init__(self, name, in_queue, out_queue):
self.__name = name
self.in_queue = in_queue
self.out_queue = out_queue
def send(self, data):
self.out_queue.put(data, block=True)
def recv(self, count=None, timeout=None):
data = self.in_queue.get(block=True, timeout=timeout)
return data
def poll(self, timeout=None):
return not self.in_queue.empty()
def close(self):
pass
class RPCError(RuntimeError):
"Remote Error (not user exception)"
pass
class Frontend(object):
"Qdb generic Frontend interface"
def __init__(self, pipe):
self.i = 1
self.pipe = pipe
self.notifies = []
self.read_lock = threading.RLock()
self.write_lock = threading.RLock()
def recv(self):
self.read_lock.acquire()
try:
return self.pipe.recv()
finally:
self.read_lock.release()
def send(self, data):
self.write_lock.acquire()
try:
return self.pipe.send(data)
finally:
self.write_lock.release()
def startup(self):
self.send({'method': 'run', 'args': (), 'id': None})
def interaction(self, filename, lineno, line, *kwargs):
raise NotImplementedError
def exception(self, title, extype, exvalue, trace, request):
"Show a user_exception"
raise NotImplementedError
def write(self, text):
"Console output (print)"
raise NotImplementedError
def readline(self, text):
"Console input/rawinput"
raise NotImplementedError
def run(self):
"Main method dispatcher (infinite loop)"
if self.pipe:
if not self.notifies:
# wait for a message...
request = self.recv()
else:
# process an asyncronus notification received earlier
request = self.notifies.pop(0)
return self.process_message(request)
def process_message(self, request):
if request:
result = None
if request.get("error"):
# it is not supposed to get an error here
# it should be raised by the method call
raise RPCError(res['error']['message'])
elif request.get('method') == 'interaction':
self.interaction(*request.get("args"), **request.get("kwargs"))
elif request.get('method') == 'startup':
self.startup()
elif request.get('method') == 'exception':
self.exception(*request['args'])
elif request.get('method') == 'write':
self.write(*request.get("args"))
elif request.get('method') == 'readline':
result = self.readline()
if result:
response = {'version': '1.1', 'id': request.get('id'),
'result': result,
'error': None}
self.send(response)
return True
def call(self, method, *args):
"Actually call the remote method (inside the thread)"
req = {'method': method, 'args': args, 'id': self.i}
self.send(req)
self.i += 1 # increment the id
while 1:
# wait until command acknowledge (response id match the request)
res = self.recv()
if 'id' not in res or not res['id']:
# nested notification received (i.e. write)! process it!
self.process_message(res)
elif 'result' not in res:
# nested request received (i.e. readline)! process it!
self.process_message(res)
elif long(req['id']) != long(res['id']):
print "DEBUGGER wrong packet received: expecting id", req['id'], res['id']
# protocol state is unknown
elif 'error' in res and res['error']:
raise RPCError(res['error']['message'])
else:
return res['result']
def do_step(self, arg=None):
"Execute the current line, stop at the first possible occasion"
self.call('do_step')
def do_next(self, arg=None):
"Execute the current line, do not stop at function calls"
self.call('do_next')
def do_continue(self, arg=None):
"Continue execution, only stop when a breakpoint is encountered."
self.call('do_continue')
def do_return(self, arg=None):
"Continue execution until the current function returns"
self.call('do_return')
def do_jump(self, arg):
"Set the next line that will be executed."
res = self.call('do_jump', arg)
print res
def do_where(self, arg=None):
"Print a stack trace, with the most recent frame at the bottom."
return self.call('do_where')
def do_quit(self, arg=None):
"Quit from the debugger. The program being executed is aborted."
self.call('do_quit')
def do_eval(self, expr):
"Inspect the value of the expression"
return self.call('do_eval', expr)
def do_environment(self):
"List all the locals and globals variables (string representation)"
return self.call('do_environment')
def do_list(self, arg=None):
"List source code for the current file"
return self.call('do_list', arg)
def do_read(self, filename):
"Read and send a local filename"
return self.call('do_read', filename)
def do_set_breakpoint(self, filename, lineno, temporary=0, cond=None):
"Set a breakpoint at filename:breakpoint"
self.call('do_set_breakpoint', filename, lineno, temporary, cond)
def do_clear_breakpoint(self, filename, lineno):
"Remove a breakpoint at filename:breakpoint"
self.call('do_clear_breakpoint', filename, lineno)
def do_clear_file_breakpoints(self, filename):
"Remove all breakpoints at filename"
self.call('do_clear_breakpoints', filename, lineno)
def do_list_breakpoint(self):
"List all breakpoints"
return self.call('do_list_breakpoint')
def do_exec(self, statement):
return self.call('do_exec', statement)
def get_autocomplete_list(self, expression):
return self.call('get_autocomplete_list', expression)
def get_call_tip(self, expression):
return self.call('get_call_tip', expression)
def interrupt(self):
"Immediately stop at the first possible occasion (outside interaction)"
# this is a notification!, do not expect a response
req = {'method': 'interrupt', 'args': ()}
self.send(req)
def set_burst(self, value):
req = {'method': 'set_burst', 'args': (value, )}
self.send(req)
def set_params(self, params):
req = {'method': 'set_params', 'args': (params, )}
self.send(req)
class Cli(Frontend, cmd.Cmd):
"Qdb Front-end command line interface"
def __init__(self, pipe, completekey='tab', stdin=None, stdout=None, skip=None):
cmd.Cmd.__init__(self, completekey, stdin, stdout)
Frontend.__init__(self, pipe)
# redefine Frontend methods:
def run(self):
while 1:
try:
Frontend.run(self)
except KeyboardInterrupt:
print "Interupting..."
self.interrupt()
def interaction(self, filename, lineno, line):
print "> %s(%d)\n-> %s" % (filename, lineno, line),
self.filename = filename
self.cmdloop()
def exception(self, title, extype, exvalue, trace, request):
print "=" * 80
print "Exception", title
print request
print "-" * 80
def write(self, text):
print text,
def readline(self):
return raw_input()
def postcmd(self, stop, line):
return not line.startswith("h") # stop
do_h = cmd.Cmd.do_help
do_s = Frontend.do_step
do_n = Frontend.do_next
do_c = Frontend.do_continue
do_r = Frontend.do_return
do_j = Frontend.do_jump
do_q = Frontend.do_quit
def do_eval(self, args):
"Inspect the value of the expression"
print Frontend.do_eval(self, args)
def do_list(self, args):
"List source code for the current file"
lines = Frontend.do_list(self, eval(args, {}, {}) if args else None)
self.print_lines(lines)
def do_where(self, args):
"Print a stack trace, with the most recent frame at the bottom."
lines = Frontend.do_where(self)
self.print_lines(lines)
def do_environment(self, args=None):
env = Frontend.do_environment(self)
for key in env:
print "=" * 78
print key.capitalize()
print "-" * 78
for name, value in env[key].items():
print "%-12s = %s" % (name, value)
def do_list_breakpoint(self, arg=None):
"List all breakpoints"
breaks = Frontend.do_list_breakpoint(self)
print "Num File Line Temp Enab Hits Cond"
for bp in breaks:
print '%-4d%-30s%4d %4s %4s %4d %s' % bp
print
def do_set_breakpoint(self, arg):
"Set a breakpoint at filename:breakpoint"
if arg:
if ':' in arg:
args = arg.split(":")
else:
args = (self.filename, arg)
Frontend.do_set_breakpoint(self, *args)
else:
self.do_list_breakpoint()
do_b = do_set_breakpoint
do_l = do_list
do_p = do_eval
do_w = do_where
do_e = do_environment
def default(self, line):
"Default command"
if line[:1] == '!':
print self.do_exec(line[1:])
else:
print "*** Unknown command: ", line
def print_lines(self, lines):
for filename, lineno, bp, current, source in lines:
print "%s:%4d%s%s\t%s" % (filename, lineno, bp, current, source),
print
def test():
def f(pipe):
print "creating debugger"
qdb = Qdb(pipe=pipe, redirect_stdio=False)
print "set trace"
my_var = "Mariano!"
qdb.set_trace()
print "hello world!"
print "good by!"
saraza
if '--process' in sys.argv:
from multiprocessing import Process, Pipe
pipe, child_conn = Pipe()
p = Process(target=f, args=(child_conn,))
else:
from threading import Thread
from Queue import Queue
parent_queue, child_queue = Queue(), Queue()
front_conn = QueuePipe("parent", parent_queue, child_queue)
child_conn = QueuePipe("child", child_queue, parent_queue)
p = Thread(target=f, args=(child_conn,))
p.start()
import time
class Test(Frontend):
def interaction(self, *args):
print "interaction!", args
def exception(self, *args):
print "exception", args
#raise RuntimeError("exception %s" % repr(args))
qdb = Test(front_conn)
time.sleep(5)
while 1:
print "running..."
Frontend.run(qdb)
time.sleep(1)
print "do_next"
qdb.do_next()
p.join()
def connect(host="localhost", port=6000, authkey='secret password'):
"Connect to a running debugger backend"
address = (host, port)
from multiprocessing.connection import Client
print "qdb debugger fronted: waiting for connection to", address
conn = Client(address, authkey=authkey)
try:
Cli(conn).run()
except EOFError:
pass
finally:
conn.close()
def main(host='localhost', port=6000, authkey='secret password'):
"Debug a script and accept a remote frontend"
if not sys.argv[1:] or sys.argv[1] in ("--help", "-h"):
print "usage: pdb.py scriptfile [arg] ..."
sys.exit(2)
mainpyfile = sys.argv[1] # Get script filename
if not os.path.exists(mainpyfile):
print 'Error:', mainpyfile, 'does not exist'
sys.exit(1)
del sys.argv[0] # Hide "pdb.py" from argument list
# Replace pdb's dir with script's dir in front of module search path.
sys.path[0] = os.path.dirname(mainpyfile)
from multiprocessing.connection import Listener
address = (host, port) # family is deduced to be 'AF_INET'
listener = Listener(address, authkey=authkey)
print "qdb debugger backend: waiting for connection at", address
conn = listener.accept()
print 'qdb debugger backend: connected to', listener.last_accepted
# create the backend
qdb = Qdb(conn, redirect_stdio=True, allow_interruptions=True)
try:
print "running", mainpyfile
qdb._runscript(mainpyfile)
print "The program finished"
except SystemExit:
# In most cases SystemExit does not warrant a post-mortem session.
print "The program exited via sys.exit(). Exit status: ",
print sys.exc_info()[1]
raise
except:
raise
conn.close()
listener.close()
qdb = None
def set_trace(host='localhost', port=6000, authkey='secret password'):
"Simplified interface to debug running programs"
global qdb, listener, conn
from multiprocessing.connection import Listener
# only create it if not currently instantiated
if not qdb:
address = (host, port) # family is deduced to be 'AF_INET'
listener = Listener(address, authkey=authkey)
conn = listener.accept()
# create the backend
qdb = Qdb(conn)
# start debugger backend:
qdb.set_trace()
def quit():
"Remove trace and quit"
global qdb, listener, conn
if qdb:
sys.settrace(None)
qdb = None
if conn:
conn.close()
conn = None
if listener:
listener.close()
listener = None
if __name__ == '__main__':
# When invoked as main program:
if '--test' in sys.argv:
test()
# Check environment for configuration parameters:
kwargs = {}
for param in 'host', 'port', 'authkey':
if 'QDB_%s' % param.upper() in os.environ:
kwargs[param] = os.environ['QDB_%s' % param.upper()]
if not sys.argv[1:]:
# connect to a remote debbuger
connect(**kwargs)
else:
# start the debugger on a script
# reimport as global __main__ namespace is destroyed
import qdb
qdb.main(**kwargs)
| 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
def clear(self, key):
key = '%s/%s' % (self.request.application, key)
self.delete(key)
| 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. &) 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 |
import urllib
import simplejson
class Stripe:
"""
Usage:
key='<api key>'
d = Stripe(key).charge(
amount=100,
currency='usd',
card_number='4242424242424242',
card_exp_month='5',
card_exp_year='2012',
card_cvc_check='123',
description='test charge')
print d
print Stripe(key).check(d['id'])
print Stripe(key).refund(d['id'])
Sample output (python dict):
{u'fee': 0, u'description': u'test charge', u'created': 1321242072, u'refunded': False, u'livemode': False, u'object': u'charge', u'currency': u'usd', u'amount': 100, u'paid': True, u'id': u'ch_sdjasgfga83asf', u'card': {u'exp_month': 5, u'country': u'US', u'object': u'card', u'last4': u'4242', u'exp_year': 2012, u'type': u'Visa'}}
if paid is True than transaction was processed
"""
def __init__(self,key):
self.key = key
def charge(self,
amount,
currency='usd',
card_number='4242424242424242',
card_exp_month='5',
card_exp_year='2012',
card_cvc_check='123',
description='test charge'):
params = urllib.urlencode({'amount':amount,
'currency':currency,
'card[number]':card_number,
'card[exp_month]':card_exp_month,
'card[exp_year]':card_exp_year,
'card[cvc_check]':card_cvc_check,
'description':description})
u = urllib.urlopen('https://%s:@api.stripe.com/v1/charges' % \
self.key,params)
return simplejson.loads(u.read())
def check(self,charge_id):
u = urllib.urlopen('https://%s:@api.stripe.com/v1/charges/%s' % \
(self.key,charge_id))
return simplejson.loads(u.read())
def refund(self,charge_id):
params = urllib.urlencode({})
u = urllib.urlopen('https://%s:@api.stripe.com/v1/charges/%s/refund'%\
(self.key,charge_id),params)
return simplejson.loads(u.read())
if __name__=='__main__':
key = raw_input('user>')
d=Stripe(key).charge(100)
print 'charged',d['paid']
s = Stripe(key).check(d[u'id'])
print 'paid',s['paid'],s['amount'] ,s['currency']
s = Stripe(key).refund(d[u'id'])
print 'refunded',s['refunded']
| Python |
"""
DowCommerce class to process credit card payments with DowCommerce.com
Modifications to support Dow Commerce API from code originally 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 Dave Stoll dave.stoll@gmail.com
- modifed to support Dow Commerce API
"""
__all__ = ['DowCommerce']
from operator import itemgetter
import urllib
class DowCommerce:
class DowCommerceError(Exception):
def __init__(self, value):
self.parameter = value
def __str__(self):
return str(self.parameter)
def __init__(self, username=None, password=None, demomode=False):
if not demomode:
if str(username).strip() == '' or username == None:
raise DowCommerce.DowCommerceError('No username provided')
if str(password).strip() == '' or password == None:
raise DowCommerce.DowCommerceError('No password provided')
else:
username = 'demo'
password = 'password'
self.proxy = None;
self.delimiter = '&'
self.results = {}
self.error = True
self.success = False
self.declined = False
self.url = 'https://secure.dowcommerce.net/api/transact.php'
self.parameters = {}
self.setParameter('username', username)
self.setParameter('password', password)
def process(self):
encoded_args = urllib.urlencode(self.parameters)
if self.proxy == None:
results = str(urllib.urlopen(self.url, encoded_args).read()).split(self.delimiter)
else:
opener = urllib.FancyURLopener(self.proxy)
opened = opener.open(self.url, encoded_args)
try:
results = str(opened.read()).split(self.delimiter)
finally:
opened.close()
for result in results:
(key,val) = result.split('=')
self.results[key] = val
if self.results['response'] == '1':
self.error = False
self.success = True
self.declined = False
elif self.results['response'] == '2':
self.error = False
self.success = False
self.declined = True
elif self.results['response'] == '3':
self.error = True
self.success = False
self.declined = False
else:
self.error = True
self.success = False
self.declined = False
raise DowCommerce.DowCommerceError(self.results)
def setTransaction(self, creditcard, expiration, total, cvv=None, orderid=None, orderdescription=None,
ipaddress=None, tax=None, shipping=None,
firstname=None, lastname=None, company=None, address1=None, address2=None, city=None, state=None, zipcode=None,
country=None, phone=None, fax=None, emailaddress=None, website=None,
shipping_firstname=None, shipping_lastname=None, shipping_company=None, shipping_address1=None, shipping_address2=None,
shipping_city=None, shipping_state=None, shipping_zipcode = None, shipping_country=None, shipping_emailaddress=None):
if str(creditcard).strip() == '' or creditcard == None:
raise DowCommerce.DowCommerceError('No credit card number passed to setTransaction(): {0}'.format(creditcard))
if str(expiration).strip() == '' or expiration == None:
raise DowCommerce.DowCommerceError('No expiration number passed to setTransaction(): {0}'.format(expiration))
if str(total).strip() == '' or total == None:
raise DowCommerce.DowCommerceError('No total amount passed to setTransaction(): {0}'.format(total))
self.setParameter('ccnumber', creditcard)
self.setParameter('ccexp', expiration)
self.setParameter('amount', total)
if cvv:
self.setParameter('cvv', cvv)
if orderid:
self.setParameter('orderid', orderid)
if orderdescription:
self.setParameter('orderdescription', orderdescription)
if ipaddress:
self.setParameter('ipaddress', ipaddress)
if tax:
self.setParameter('tax', tax)
if shipping:
self.setParameter('shipping', shipping)
## billing info
if firstname:
self.setParameter('firstname', firstname)
if lastname:
self.setParameter('lastname', lastname)
if company:
self.setParameter('company', company)
if address1:
self.setParameter('address1', address1)
if address2:
self.setParameter('address2', address2)
if city:
self.setParameter('city', city)
if state:
self.setParameter('state', state)
if zipcode:
self.setParameter('zip', zipcode)
if country:
self.setParameter('country', country)
if phone:
self.setParameter('phone', phone)
if fax:
self.setParameter('fax', fax)
if emailaddress:
self.setParameter('email', emailaddress)
if website:
self.setParameter('website', website)
## shipping info
if shipping_firstname:
self.setParameter('shipping_firstname', shipping_firstname)
if shipping_lastname:
self.setParameter('shipping_lastname', shipping_lastname)
if shipping_company:
self.setParameter('shipping_company', shipping_company)
if shipping_address1:
self.setParameter('shipping_address1', shipping_address1)
if shipping_address2:
self.setParameter('shipping_address2', shipping_address2)
if shipping_city:
self.setParameter('shipping_city', shipping_city)
if shipping_state:
self.setParameter('shipping_state', shipping_state)
if shipping_zipcode:
self.setParameter('shipping_zip', shipping_zipcode)
if shipping_country:
self.setParameter('shipping_country', shipping_country)
def setTransactionType(self, transtype=None):
types = ['sale', 'auth', 'credit']
if transtype.lower() not in types:
raise DowCommerce.DowCommerceError('Incorrect Transaction Type passed to setTransactionType(): {0}'.format(transtype))
self.setParameter('type', transtype.lower())
def setProxy(self, proxy=None):
if str(proxy).strip() == '' or proxy == None:
raise DowCommerce.DowCommerceError('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 DowCommerce.DowCommerceError('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 getResultResponseShort(self):
responses = ['', 'Approved', 'Declined', 'Error']
return responses[int(self.results['response'])]
def getFullResponse(self):
return self.results
def getResponseText(self):
return self.results['responsetext']
def test():
import socket
import sys
from time import time
## TEST VALUES FROM API DOC:
# Visa: 4111111111111111
# MasterCard 5431111111111111
# DiscoverCard: 6011601160116611
# American Express: 341111111111111
# Expiration: 10/10
# Amount: > 1.00 (( passing less than $1.00 will cause it to be declined ))
# CVV: 999
creditcard = '4111111111111111'
expiration = '1010'
total = '1.00'
cvv = '999'
tax = '0.00'
orderid = str(time())[4:10] # get a random invoice number
try:
payment = DowCommerce(demomode=True)
payment.setTransaction(creditcard, expiration, total, cvv=cvv, tax=tax, orderid=orderid, orderdescription='Test Transaction',
firstname='John', lastname='Doe', company='Acme', address1='123 Min Street', city='Hometown', state='VA',
zipcode='12345', country='US', phone='888-555-1212', emailaddress='john@noemail.local', ipaddress='192.168.1.1')
payment.process()
if payment.isApproved():
print 'Payment approved!'
print payment.getFullResponse()
elif payment.isDeclined():
print 'Your credit card was declined by your bank'
elif payment.isError():
raise DowCommerce.DowCommerceError('An uncaught error occurred')
except DowCommerce.DowCommerceError, 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
# 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('"', '"')
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 = [
('&', '&'),
('<', '<'),
('>', '>'),
]
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: 
# - 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('"', '"')
else:
title_str = ''
if is_img:
result = '<img src="%s" alt="%s"%s%s' \
% (url.replace('"', '"'),
link_text.replace('"', '"'),
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('"', '"'),
link_text.replace('"', '"'),
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.
('&', '&'),
# Do the angle bracket song and dance:
('<', '<'),
('>', '>'),
# 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.">'
'↩</a>' % (id, i+1))
if footer[-1].endswith("</p>"):
footer[-1] = footer[-1][:-len("</p>")] \
+ ' ' + 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('&', text)
# Encode naked <'s
text = self._naked_lt_re.sub('<', text)
# Encode naked >'s
# Note: Other markdown implementations (e.g. Markdown.pl, PHP
# Markdown) don't do this.
text = self._naked_gt_re.sub('>', 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="mailto:foo@e
# xample.com">foo
# @example.com</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('"', '"') # 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 (requires Tornado 2.1)
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, HTTP
from gluon.html import markmin_serializer, TAG, HTML, BODY, UL, XML, H1
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)
return XML(ouput)
except (TypeError, ValueError), e:
raise HTTP(405, '%s serialization error' % e)
except ImportError, e:
raise HTTP(405, '%s not available' % e)
except Exception, e:
raise HTTP(405, '%s error' % e)
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,warnings,errors=markmin2pdf(markmin)
if errors:
current.response.headers['Content-Type']='text/html'
raise HTTP(405,HTML(BODY(H1('errors'),
UL(*errors),
H1('warnings'),
UL(*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, compute=False):
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 compute and field.compute:
continue
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)
if len(options)>0:
record[fieldname] = options[random.randint(0,len(options)-1)][0]
else:
record[fieldname] = None
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 =='integer':
try:
record[fieldname] = random.randint(field.requires.minimum,field.requires.maximum-1)
except:
record[fieldname] = random.randint(0,1000)
elif field.type == 'double' or str(field.type).startswith('decimal'):
if hasattr(field.requires,'minimum'):
rand=random.random()
if str(field.type).startswith('decimal'):
import decimal
rand=decimal.Decimal(rand)
record[fieldname] = field.requires.minimum+ \
rand*(field.requires.maximum-field.requires.minimum)
else:
record[fieldname] = random.random()*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 = portalocker.LockedFile(filename, 'r')
lang_text = fp.read().replace('\r\n', '\n')
fp.close()
if not lang_text.strip():
return {}
try:
return eval(lang_text)
except:
logging.error('Syntax error in %s' % filename)
return {'__corrupted__':True}
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):
if contents.get('__corrupted__',False):
return
try:
fp = portalocker.LockedFile(filename, 'w')
except (IOError, OSError):
if not is_gae:
logging.warning('Unable to write to file %s' % filename)
return
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')
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 = [lang for lang in 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] is 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, lazy=None):
if lazy is None:
lazy = self.lazy
if not language:
if 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, lazy=lazy)
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
"""
#for some reason languages.py gets executed before gaehandler.py
# is able to set web2py_runtime_gae, so re-check here
is_gae = settings.global_settings.web2py_runtime_gae
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 is 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 or symbols == "":
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 = portalocker.LockedFile(file, 'r')
data = fp.read()
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 logging
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=None,
):
"""
layer here is some description of where in the system the exception
occurred.
"""
if environment is None: environment = {}
self.layer = layer
self.code = code
self.output = output
self.environment = environment
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=self.environment)
except:
self.snapshot = {}
else:
self.traceback = '(no error)'
self.snapshot = {}
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 __str__(self):
# safely show an useful message to the user
try:
output = self.output
if isinstance(output, unicode):
output = output.encode("utf8")
elif not isinstance(output, str):
output = str(output)
except:
output = ""
return output
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=None, 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.
"""
if environment is None: environment = {}
environment['__file__'] = layer
environment['__name__'] = '__restricted__'
try:
if type(code) == types.CodeType:
ccode = code
else:
ccode = compile2(code,layer)
exec ccode in environment
except HTTP:
raise
except RestrictedError:
# do not encapsulate (obfuscate) the original RestrictedError
raise
except Exception, error:
# extract the exception type and value (used as output message)
etype, evalue, tb = sys.exc_info()
# XXX Show exception in Wing IDE if running in debugger
if __debug__ and 'WINGDB_ACTIVE' in os.environ:
sys.excepthook(etype, evalue, tb)
output = "%s %s" % (etype, evalue)
raise RestrictedError(layer, code, output, 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, 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', 'LOAD', '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
from compileapp import LOAD
# Dummy code to enable code completion in IDE's.
if 0:
from globals import Request, Response, Session
from cache import Cache
from languages import translator
request = Request()
response = Response()
session = Session()
cache = Cache(request)
T = translator(request)
| 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
import datetime
from http import HTTP
from gzip import open as gzopen
from settings import global_settings
__all__ = [
'parse_version',
'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 parse_version(version = "Version 1.99.0 (2011-09-19 08:23:26)"):
re_version = re.compile('[^\d]+ (\d+)\.(\d+)\.(\d+)\s*\((?P<datetime>.+?)\)\s*(?P<type>[a-z]+)?')
m = re_version.match(version)
a,b,c = int(m.group(1)),int(m.group(2)),int(m.group(3)),
s = m.group('type') or 'dev'
d = datetime.datetime.strptime(m.group('datetime'),'%Y-%m-%d %H:%M:%S')
return (a,b,c,d,s)
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, URL
from http import HTTP, redirect
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
try:
from gluon.contrib.minify import minify
have_minify = True
except ImportError:
have_minify = False
regex_session_id = re.compile('^([\w\-]+/)?[\w\-\.]+$')
__all__ = ['Request', 'Response', 'Session']
current = threading.local() # thread-local storage for request-scope globals
css_template = '<link href="%s" rel="stylesheet" type="text/css" />'
js_template = '<script src="%s" type="text/javascript"></script>'
coffee_template = '<script src="%s" type="text/coffee"></script>'
less_template = '<link href="%s" rel="stylesheet/less" type="text/css" />'
css_inline = '<style type="text/css">\n%s\n</style>'
js_inline = '<script type="text/javascript">\n%s\n</script>'
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 = 'html'
self.now = datetime.datetime.now()
self.utcnow = datetime.datetime.utcnow()
self.is_restful = False
self.is_https = False
self.is_local = False
self.global_settings = settings.global_settings
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
user_agent = session._user_agent = session._user_agent or \
user_agent_parser.detect(self.env.http_user_agent)
user_agent = Storage(user_agent)
for key,value in user_agent.items():
if isinstance(value,dict): user_agent[key] = Storage(value)
return user_agent
def requires_https(self):
"""
If request comes in over HTTP, redirect it to HTTPS
and secure the session.
"""
if not global_settings.cronjob and not self.is_https:
redirect(URL(scheme='https', args=self.args, vars=self.vars))
current.session.secure()
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)
current.response.headers['Content-Type'] = \
contenttype(_self.extension.lower())
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.delimiters = ('{{','}}')
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 include_meta(self):
s = ''
for key,value in (self.meta or {}).items():
s += '<meta name="%s" content="%s" />' % (key,xmlescape(value))
self.write(s,escape=False)
def include_files(self):
"""
Caching method for writing out files.
By default, caches in ram for 5 minutes. To change,
response.cache_includes = (cache_method, time_expire).
Example: (cache.disk, 60) # caches to disk for 1 minute.
"""
from gluon import URL
files = []
for item in self.files:
if not item in files: files.append(item)
if have_minify and (self.optimize_css or self.optimize_js):
# cache for 5 minutes by default
cache = self.cache_includes or (current.cache.ram, 60*5)
def call_minify():
return minify.minify(files,
URL('static','temp'),
current.request.folder,
self.optimize_css,
self.optimize_js)
if cache:
cache_model, time_expire = cache
files = cache_model('response.files.minified',
call_minify,
time_expire)
else:
files = call_minify()
s = ''
for item in files:
if isinstance(item,str):
f = item.lower()
if f.endswith('.css'): s += css_template % item
elif f.endswith('.js'): s += js_template % item
elif f.endswith('.coffee'): s += coffee_template % item
elif f.endswith('.less'): s += less_template % item
elif isinstance(item,(list,tuple)):
f = item[0]
if f=='css:inline': s += css_inline % item[1]
elif f=='js:inline': s += js_inline % item[1]
self.write(s, escape=False)
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 not request:
request = current.request
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
# Internet Explorer < 9.0 will not allow downloads over SSL unless caching is enabled
if request.is_https and isinstance(request.env.http_user_agent,str) and \
not re.search(r'Opera', request.env.http_user_agent) and \
re.search(r'MSIE [5-8][^0-9]', request.env.http_user_agent):
self.headers['Pragma'] = 'cache'
self.headers['Cache-Control'] = 'private'
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
if hasattr(thread,'instances'):
dbstats = [TABLE(*[TR(PRE(row[0]),'%.2fms' % (row[1]*1000)) \
for row in i.db._timings]) \
for i in thread.instances]
else:
dbstats = [] # if no db or on GAE
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 and 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.client.replace(':','.'),
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.rss2 as rss2
try:
import json as json_parser # try stdlib (Python 2.6)
except ImportError:
try:
import simplejson as json_parser # try external module
except:
import contrib.simplejson as json_parser # fallback to pure-Python module
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, quote=True):
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, '',quote)) \
for k, v in value.items()])
elif isinstance(value, list):
return TAG[key](*[TAG.item(xml_rec(item, '',quote)) for item in value])
elif hasattr(value,'as_list') and callable(value.as_list):
return str(xml_rec(value.as_list(),'',quote))
elif hasattr(value,'as_dict') and callable(value.as_dict):
return str(xml_rec(value.as_dict(),'',quote))
else:
return xmlescape(value,quote)
def xml(value, encoding='UTF-8', key='document', quote=True):
return ('<?xml version="1.0" encoding="%s"?>' % encoding) + str(xml_rec(value,key,quote))
def json(value,default=custom_json):
return json_parser.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 is None or offset < bytes:
if not bytes is 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, Response
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
import platform
try:
import py_compile
except:
logger.warning('unable to import py_compile')
is_pypy = hasattr(platform,'python_implementation') and \
platform.python_implementation() == 'PyPy'
settings.global_settings.is_pypy = is_pypy
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)
def LOAD(c=None, f='index', args=None, vars=None,
extension=None, target=None,ajax=False,ajax_trap=False,
url=None,user_signature=False, timeout=None, times=1,
content='loading...',**attr):
""" LOAD a component into the action's document
Timing options:
-times: An integer or string ("infinity"/"continuous")
specifies how many times the component is requested
-timeout (milliseconds): specifies the time to wait before
starting the request or the frequency if times is greater than
1 or "infinity".
Timing options default to the normal behavior. The component
is added on page loading without delay.
"""
from html import TAG, DIV, URL, SCRIPT, XML
if args is None: args = []
vars = Storage(vars or {})
target = target or 'c'+str(random.random())[2:]
attr['_id']=target
request = current.request
if '.' in f:
f, extension = f.split('.',1)
if url or ajax:
url = url or URL(request.application, c, f, r=request,
args=args, vars=vars, extension=extension,
user_signature=user_signature)
# timing options
if isinstance(times, basestring):
if times.upper() in ("INFINITY", "CONTINUOUS"):
times = "Infinity"
else:
raise TypeError("Unsupported times argument %s" % times)
elif isinstance(times, int):
if times <= 0:
raise ValueError("Times argument must be greater than zero, 'Infinity' or None")
else:
raise TypeError("Unsupported times argument type %s" % type(times))
if timeout is not None:
if not isinstance(timeout, (int, long)):
raise ValueError("Timeout argument must be an integer or None")
elif timeout <= 0:
raise ValueError("Timeout argument must be greater than zero or None")
statement = "web2py_component('%s','%s', %s, %s);" \
% (url, target, timeout, times)
else:
statement = "web2py_component('%s','%s');" % (url, target)
script = SCRIPT(statement, _type="text/javascript")
if not content is None:
return TAG[''](script, DIV(content,**attr))
else:
return TAG[''](script)
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 = Response()
other_request.env.path_info = '/' + \
'/'.join([request.application,c,f] + \
map(str, other_request.args))
other_request.env.query_string = \
vars and 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(current.globalenv) ### NASTY
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 = 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 SCRIPT(js,_type="text/javascript") or ''
return TAG[''](DIV(XML(page),**attr),script)
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=None, vars=None,
extension=None, target=None,ajax=False,ajax_trap=False,
url=None,user_signature=False, content='loading...',**attr):
if args is None: args = []
vars = Storage(vars or {})
import globals
target = target or 'c'+str(random.random())[2:]
attr['_id']=target
request = self.environment['request']
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, reload_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 reload_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.globalenv = environment
current.request = request
current.response = response
current.session = session
current.T = t
current.cache = c
global __builtins__
if is_jython: # jython hack
__builtins__ = mybuiltin()
elif is_pypy: # apply the same hack to pypy too
__builtins__ = mybuiltin()
else:
__builtins__['__import__'] = __builtin__.__import__ ### WHY?
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'] = LOAD
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')
elif hasattr(vars,'xml') and callable(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=None,
):
"""
Initialise highlighter:
mode = language (PYTHON, WEB2PY,C, CPP, HTML, HTML_PLAIN)
"""
styles = styles or {}
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|COL|COLGROUP|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 not new_mode is 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 not self.span_style is None:
self.output.append('</span>')
if not style is None:
self.output.append('<span style="%s">' % style)
self.span_style = style
def highlight(
code,
language,
link='/examples/globals/vars/',
counter=1,
styles=None,
highlight_line=None,
context_lines=None,
attributes=None,
):
styles = styles or {}
attributes = attributes or {}
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])
if context_lines:
if lineno + context_lines < len(lines):
del lines[lineno + context_lines:]
del linenumbers[lineno + context_lines:]
if lineno -context_lines > 0:
del lines[0:lineno - context_lines]
del linenumbers[0:lineno - context_lines]
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 is 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, parse_version
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, raise_ex=False):
"""
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, e:
if raise_ex:
raise
return False
def app_pack_compiled(app, request, raise_ex=False):
"""
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, e:
if raise_ex:
raise
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 = parse_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, web2py_uuid
__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',
]
try:
from globals import current
have_current = True
except ImportError:
have_current = False
def translate(text):
if text is None:
return None
elif isinstance(text,(str,unicode)) and have_current:
if hasattr(current,'T'):
return str(current.T(text))
return str(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('hell')('hello')
('hello', 'invalid expression')
>>> IS_MATCH('hell.*', strict=False)('hello')
('hello', None)
>>> IS_MATCH('hello')('shello')
('shello', 'invalid expression')
>>> IS_MATCH('hello', search=True)('shello')
('hello', None)
>>> IS_MATCH('hello', search=True, strict=False)('shellox')
('hello', None)
>>> IS_MATCH('.*hello.*', search=True, strict=False)('shellox')
('shellox', None)
>>> IS_MATCH('.+')('')
('', 'invalid expression')
"""
def __init__(self, expression, error_message='invalid expression',
strict=False, search=False, extract=False):
if strict or not search:
if not expression.startswith('^'):
expression = '^(%s)' % expression
if strict:
if not expression.endswith('$'):
expression = '(%s)$' % expression
self.regex = re.compile(expression)
self.error_message = error_message
self.extract = extract
def __call__(self, value):
match = self.regex.search(value)
if match is not None:
return (self.extract and match.group() or value, 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 not self.zero is 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 is 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):
table = self.dbset.db[self.ktable]
if self.fields == 'all':
fields = [f for f in table]
else:
fields = [table[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(table).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(table).select(table.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 not self.zero is 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 str(x) in self.theset]:
return (values, None)
elif self.theset:
if str(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=[],
ignore_common_filters=False,
):
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
self.ignore_common_filters = ignore_common_filters
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('.')
table = self.dbset.db[tablename]
field = table[fieldname]
rows = self.dbset(field == value, ignore_common_filters = self.ignore_common_filters).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][table._id.name]) != 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)
def str2dec(number):
s = str(number)
if not '.' in s: s+='.00'
else: s+='0'*(2-len(s.split('.')[1]))
return s
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):
return str2dec(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 str2dec(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 is 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 is 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 not scheme is 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] is 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 is 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] is 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] is 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 not methodResult[1] is 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 not value.group('m') is None:
m = int(value.group('m'))
if not value.group('s') is 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 = translate(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 = translate(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"
extremes = dict(min=minimum, max=maximum)
IS_DATE.__init__(self,
format = format,
error_message = translate(error_message) % extremes)
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, self.error_message)
if self.maximum and value > self.maximum:
return (value, 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"
extremes = dict(min = minimum, max = maximum)
IS_DATETIME.__init__(self,
format = format,
error_message = translate(error_message) % extremes)
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, self.error_message)
if self.maximum and value > self.maximum:
return (value, self.error_message)
return (value, None)
class IS_LIST_OF(Validator):
def __init__(self, other=None, minimum=0, maximum=100,
error_message = None):
self.other = other
self.minimum = minimum
self.maximum = maximum
self.error_message = error_message or "enter between %(min)g and %(max)g values"
def __call__(self, value):
ivalue = value
if not isinstance(value, list):
ivalue = [ivalue]
if not self.minimum is None and len(ivalue)<self.minimum:
return (ivalue, translate(self.error_message) % dict(min=self.minimum,max=self.maximum))
if not self.maximum is None and len(ivalue)>self.maximum:
return (ivalue, translate(self.error_message) % dict(min=self.minimum,max=self.maximum))
new_value = []
if self.other:
for item in ivalue:
(v, e) = self.other(item)
if e:
return (value, e)
else:
new_value.append(v)
ivalue = new_value
return (ivalue, 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&123')
('abc123', None)
>>> IS_SLUG()('abc&123&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.
min_length is the minimal password length (default 4) - IS_STRONG for serious security
error_message is the message if password is too short
Notice that an empty password is accepted but invalid. It will not allow login back.
Stores junk as hashed password.
"""
def __init__(self, key=None, digest_alg='md5', min_length=0, error_message='too short'):
self.key = key
self.digest_alg = digest_alg
self.min_length = min_length
self.error_message = error_message
def __call__(self, value):
if len(value)<self.min_length:
return ('', translate(self.error_message))
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 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 is None or self.is_localhost == \
(number == self.localhost)):
ok = False
if not (self.is_private is None or self.is_private == \
(sum([number[0] <= number <= number[1] for number in self.private]) > 0)):
ok = False
if not (self.is_automatic is 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, CAT, UL, LI, TEXTAREA, BR, IMG, SCRIPT
from html import FORM, INPUT, LABEL, OPTION, SELECT, MENU
from html import TABLE, THEAD, TBODY, TR, TD, TH, STYLE
from html import URL, truncate_string
from dal import DAL, Table, Row, CALLABLETYPES, smart_query
from storage import Storage
from utils import md5_hash
from validators import IS_EMPTY_OR, IS_NOT_EMPTY, IS_LIST_OF
import urllib
import re
import cStringIO
table_field = re.compile('[\w_]+\.[\w_]+')
widget_class = re.compile('^\w*')
def trap_class(_class=None,trap=True):
return (trap and 'w2p_trap' or '')+(_class and ' '+_class or '')
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 getattr(f, 'im_self', None): n -= 1
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
"""
_class = 'generic-widget'
@classmethod
def _attributes(cls, 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 = cls._class or \
widget_class.match(str(field.type)).group(),
_name = field.name,
requires = field.requires,
)
attr.update(widget_attributes)
attr.update(attributes)
return attr
@classmethod
def widget(cls, 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):
_class = 'string'
@classmethod
def widget(cls, field, value, **attributes):
"""
generates an INPUT text tag.
see also: :meth:`FormWidget.widget`
"""
default = dict(
_type = 'text',
value = (not value is None and str(value)) or '',
)
attr = cls._attributes(field, default, **attributes)
return INPUT(**attr)
class IntegerWidget(StringWidget):
_class = 'integer'
class DoubleWidget(StringWidget):
_class = 'double'
class DecimalWidget(StringWidget):
_class = 'decimal'
class TimeWidget(StringWidget):
_class = 'time'
class DateWidget(StringWidget):
_class = 'date'
class DatetimeWidget(StringWidget):
_class = 'datetime'
class TextWidget(FormWidget):
_class = 'text'
@classmethod
def widget(cls, field, value, **attributes):
"""
generates a TEXTAREA tag.
see also: :meth:`FormWidget.widget`
"""
default = dict(value = value)
attr = cls._attributes(field, default,
**attributes)
return TEXTAREA(**attr)
class BooleanWidget(FormWidget):
_class = 'boolean'
@classmethod
def widget(cls, field, value, **attributes):
"""
generates an INPUT checkbox tag.
see also: :meth:`FormWidget.widget`
"""
default=dict(_type='checkbox', value=value)
attr = cls._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')
@classmethod
def widget(cls, field, value, **attributes):
"""
generates a SELECT tag, including OPTIONs (only 1 option allowed)
see also: :meth:`FormWidget.widget`
"""
default = dict(value=value)
attr = cls._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):
@classmethod
def widget(cls, field, value, **attributes):
_id = '%s_%s' % (field._tablename, field.name)
_name = field.name
if field.type=='list:integer': _class = 'integer'
else: _class = 'string'
requires = field.requires if isinstance(field.requires, (IS_NOT_EMPTY, IS_LIST_OF)) else None
items=[LI(INPUT(_id=_id, _class=_class, _name=_name, value=v, hideerror=True, requires=requires)) \
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):
@classmethod
def widget(cls, 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):
@classmethod
def widget(cls, field, value, **attributes):
"""
generates a TABLE tag, including INPUT radios (only 1 option allowed)
see also: :meth:`FormWidget.widget`
"""
attr = cls._attributes(field, {}, **attributes)
attr['_class'] = attr.get('_class','web2py_radiowidget')
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
#widget style
wrappers = dict(
table=(TABLE,TR,TD),
ul=(DIV,UL,LI),
divs=(CAT,DIV,DIV)
)
parent, child, inner = wrappers[attributes.get('style','table')]
for r_index in range(rows):
tds = []
for k, v in options[r_index*cols:(r_index+1)*cols]:
checked={'_checked':'checked'} if k==value else {}
tds.append(inner(INPUT(_type='radio',
_id='%s%s' % (field.name,k),
_name=field.name,
requires=attr.get('requires',None),
hideerror=True, _value=k,
value=value,
**checked),
LABEL(v,_for='%s%s' % (field.name,k))))
opts.append(child(tds))
if opts:
opts[-1][0][0]['hideerror'] = False
return parent(*opts, **attr)
class CheckboxesWidget(OptionsWidget):
@classmethod
def widget(cls, 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 = cls._attributes(field, {}, **attributes)
attr['_class'] = attr.get('_class','web2py_checkboxeswidget')
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
#widget style
wrappers = dict(
table=(TABLE,TR,TD),
ul=(DIV,UL,LI),
divs=(CAT,DIV,DIV)
)
parent, child, inner = wrappers[attributes.get('style','table')]
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(inner(INPUT(_type='checkbox',
_id='%s%s' % (field.name,k),
_name=field.name,
requires=attr.get('requires', None),
hideerror=True, _value=k,
value=r_value),
LABEL(v,_for='%s%s' % (field.name,k))))
opts.append(child(tds))
if opts:
opts[-1][0][0]['hideerror'] = False
return parent(*opts, **attr)
class PasswordWidget(FormWidget):
_class = 'password'
DEFAULT_PASSWORD_DISPLAY = 8*('*')
@classmethod
def widget(cls, 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 cls.DEFAULT_PASSWORD_DISPLAY) or '',
)
attr = cls._attributes(field, default, **attributes)
return INPUT(**attr)
class UploadWidget(FormWidget):
_class = 'upload'
DEFAULT_WIDTH = '150px'
ID_DELETE_SUFFIX = '__delete'
GENERIC_DESCRIPTION = 'file'
DELETE_FILE = 'delete'
@classmethod
def widget(cls, 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 = cls._attributes(field, default, **attributes)
inp = INPUT(**attr)
if download_url and value:
if callable(download_url):
url = download_url(value)
else:
url = download_url + '/' + value
(br, image) = ('', '')
if UploadWidget.is_image(value):
br = BR()
image = IMG(_src = url, _width = cls.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 + cls.ID_DELETE_SUFFIX,
_id=field.name + cls.ID_DELETE_SUFFIX),
LABEL(cls.DELETE_FILE,
_for=field.name + cls.ID_DELETE_SUFFIX),
']', br, image)
else:
inp = DIV(inp, '[',
A(cls.GENERIC_DESCRIPTION, _href = url),
']', br, image)
return inp
@classmethod
def represent(cls, 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 = cls.GENERIC_DESCRIPTION
if download_url and value:
if callable(download_url):
url = download_url(value)
else:
url = download_url + '/' + value
if cls.is_image(value):
inp = IMG(_src = url, _width = cls.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):
_class = 'string'
def __init__(self, request, field, id_field=None, db=None,
orderby=None, limitby=(0,10),
keyword='_autocomplete_%(fieldname)s',
min_length=2):
self.help_fields = kwargs.get('help_fields',[])
self.help_string = kwargs.get('help_string',None)
if self.help_fields and not self.help_string:
self.help_string = ' '.join('%%(%s)s' for f in self.help_fields)
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(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]
if self.help_fields:
options = [OPTION(self.help_string % dict([(h.name,s[h.name]) for h in self.fields[:1]+self.help_fields]),
_value=s[id_field.name], _selected=(k==0)) for k,s in enumerate(rows)]
else:
options = [OPTION(s[field.name],_value=s[id_field.name],
_selected=(k==0)) for k,s in enumerate(rows)]
raise HTTP(200,SELECT(_id=self.keyword,_class='autocomplete',
_size=len(rows),_multiple=(len(rows)==1),
*options).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 = (not value is 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(f='table/db/')
"""
self.ignore_rw = ignore_rw
self.formstyle = formstyle
nbsp = XML(' ') # 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 is 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:
self.record_id = dict([(k,record and str(record[k]) or 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()
# default id field name
self.id_field_name = table._id.name
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 is None:
comment = ''
self.custom.comment[fieldname] = comment
if not labels is 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, label and 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 = ''
# store the id field name (for legacy databases)
self.id_field_name = field.name
if record:
if showid and field.name in record and field.readable:
v = record[field.name]
widget = SPAN(v, _id=field_id)
self.custom.dspval.id = str(v)
xfields.append((row_id,label, widget,comment))
self.record_id = str(record[field.name])
self.custom.widget.id = widget
continue
self.readonly = readonly
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:
field_type = widget_class.match(str(field.type)).group()
field_type = field_type in self.widgets and field_type or 'string'
inp = self.widgets[field_type].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[self.id_field_name]))
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,separator,
_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:
if 'submit' in buttons:
widget = self.custom.submit = INPUT(_type='submit',
_value=submit_button)
elif buttons:
widget = self.custom.submit = DIV(*buttons)
if self.custom.submit:
xfields.append(('submit_record' + SQLFORM.ID_ROW_SUFFIX,
'', widget, col3.get('submit_button', '')))
# 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[table._id.name]
(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 callable(self.formstyle):
table = TABLE()
for id,a,b,c in xfields:
raw_b = self.field_parent[id] = b
newrows = self.formstyle(id,a,raw_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 self.readonly: return False
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.get(k,None)) \
for k in self.table._primarykey)
else:
(formname_id, record_id) = (self.record[self.id_field_name],
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
self.deleted = \
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 self.deleted
# 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
if field.type.startswith('list:') and \
isinstance(value, str):
value = [value]
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
self.accepted = ret
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 and not keyed:
self.vars.id = self.record[self.id_field_name]
if self.deleted 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[self.id_field_name]
self.table._db(qry).delete()
self.errors.clear()
for component in self.elements('input, select, textarea'):
component['_disabled'] = True
self.accepted = 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) is 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 is 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, field.uploadfolder)
# 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 is None and field.type != 'blob':
self.errors[fieldname] = 'no data'
self.accepted = False
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 not value is None:
fields[fieldname] = safe_int(value)
elif field.type.startswith('reference'):
if not value is None and isinstance(self.table, Table) and not keyed:
fields[fieldname] = safe_int(value)
elif field.type == 'double':
if not value is 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 \
and field.update is None:
if record_id and self.record:
fields[field.name] = self.record[field.name]
elif not self.table[field.name].default is 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[self.id_field_name]
if fields:
self.table._db(self.table._id == self.record[self.id_field_name]).update(**fields)
else:
self.vars.id = self.table.insert(**fields)
self.accepted = ret
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)
@staticmethod
def build_query(fields,keywords):
from gluon import current
request = current.request
if isinstance(keywords,(tuple,list)):
keywords = keywords[0]
request.vars.keywords = keywords
key = keywords.strip()
if key and not ' ' in key and not '"' in key and not "'" in key:
SEARCHABLE_TYPES = ('string','text','list:string')
parts = [field.contains(key) for field in fields if field.type in SEARCHABLE_TYPES]
else:
parts = None
if parts:
return reduce(lambda a,b: a|b,parts)
else:
return smart_query(fields,key)
@staticmethod
def search_menu(fields,search_options=None):
from gluon import current
T = current.T
search_options = search_options or {
'string':['=','!=','<','>','<=','>=','starts with','contains'],
'text':['=','!=','<','>','<=','>=','starts with','contains'],
'date':['=','!=','<','>','<=','>='],
'time':['=','!=','<','>','<=','>='],
'datetime':['=','!=','<','>','<=','>='],
'integer':['=','!=','<','>','<=','>='],
'double':['=','!=','<','>','<=','>='],
'boolean':['=','!=']}
if fields[0]._db._adapter.dbengine=='google:datastore':
search_options['string'] = ['=','!=','<','>','<=','>=']
search_options['text'] = ['=','!=','<','>','<=','>=']
criteria = []
selectfields = []
for field in fields:
name = str(field).replace('.','-')
criterion = []
options = search_options.get(field.type,None)
if options:
label = isinstance(field.label,str) and T(field.label) or field.label
selectfields.append((str(field),label))
operators = SELECT(*[T(option) for option in options])
if field.type=='boolean':
value_input = SELECT(
OPTION(T("True"),_value="T"),OPTION(T("False"),_value="F"),
_id="w2p_value_"+name)
else:
value_input = INPUT(_type='text',_id="w2p_value_"+name,_class=field.type)
new_button = INPUT(_type="button", _value=T('New'),
_onclick="w2p_build_query('new','"+str(field)+"')")
and_button = INPUT(_type="button", _value=T('And'),
_onclick="w2p_build_query('and','"+str(field)+"')")
or_button = INPUT(_type="button", _value=T('Or'),
_onclick="w2p_build_query('or','"+str(field)+"')")
criterion.extend([operators,value_input,new_button,and_button,or_button])
criteria.append(DIV(criterion, _id='w2p_field_%s' % name,
_class='w2p_query_row hidden'))
criteria.insert(0,SELECT(
_id="w2p_query_fields",
_onchange="jQuery('.w2p_query_row').hide();jQuery('#w2p_field_'+jQuery('#w2p_query_fields').val().replace('.','-')).show();",
*[OPTION(label, _value=fname) for fname,label in selectfields]))
fadd = SCRIPT("""
jQuery('#w2p_query_panel input,#w2p_query_panel select').css(
'width','auto').css('float','left');
jQuery(function(){web2py_ajax_fields('#w2p_query_panel');});
function w2p_build_query(aggregator,a){
var b=a.replace('.','-');
var option = jQuery('#w2p_field_'+b+' select').val();
var value = jQuery('#w2p_value_'+b).val().replace('"','\\\\"');
var s=a+' '+option+' "'+value+'"';
var k=jQuery('#web2py_keywords');
var v=k.val();
if(aggregator=='new') k.val(s); else k.val((v?(v+' '+ aggregator +' '):'')+s);
jQuery('#w2p_query_panel').slideUp();
}
""")
return CAT(
INPUT(
_value=T("Query"),_type="button",_id="w2p_query_trigger",
_onclick="jQuery('#w2p_query_fields').change();jQuery('#w2p_query_panel').slideToggle();"),
DIV(_id="w2p_query_panel",
_style='position:absolute;z-index:1000',
_class='hidden',
*criteria),
fadd)
@staticmethod
def grid(query,
fields=None,
field_id=None,
left=None,
headers={},
orderby=None,
searchable=True,
sortable=True,
paginate=20,
deletable=True,
editable=True,
details=True,
selectable=None,
create=True,
csv=True,
links=None,
links_in_grid=True,
upload = '<default>',
args=[],
user_signature = True,
maxtextlengths={},
maxtextlength=20,
onvalidation=None,
oncreate=None,
onupdate=None,
ondelete=None,
sorter_icons=(XML('↑'),XML('↓')),
ui = 'web2py',
showbuttontext=True,
_class="web2py_grid",
formname='web2py_grid',
search_widget='default',
ignore_rw = False,
formstyle = 'table3cols',
):
# jQuery UI ThemeRoller classes (empty if ui is disabled)
if ui == 'jquery-ui':
ui = dict(widget='ui-widget',
header='ui-widget-header',
content='ui-widget-content',
default='ui-state-default',
cornerall='ui-corner-all',
cornertop='ui-corner-top',
cornerbottom='ui-corner-bottom',
button='ui-button-text-icon-primary',
buttontext='ui-button-text',
buttonadd='ui-icon ui-icon-plusthick',
buttonback='ui-icon ui-icon-arrowreturnthick-1-w',
buttonexport='ui-icon ui-icon-transferthick-e-w',
buttondelete='ui-icon ui-icon-trash',
buttonedit='ui-icon ui-icon-pencil',
buttontable='ui-icon ui-icon-triangle-1-e',
buttonview='ui-icon ui-icon-zoomin',
)
elif ui == 'web2py':
ui = dict(widget='',
header='',
content='',
default='',
cornerall='',
cornertop='',
cornerbottom='',
button='button',
buttontext='buttontext button',
buttonadd='icon plus',
buttonback='icon leftarrow',
buttonexport='icon downarrow',
buttondelete='icon trash',
buttonedit='icon pen',
buttontable='icon rightarrow',
buttonview='icon magnifier',
)
elif not isinstance(ui,dict):
raise RuntimeError,'SQLFORM.grid ui argument must be a dictionary'
from gluon import current, redirect
db = query._db
T = current.T
request = current.request
session = current.session
response = current.response
wenabled = (not user_signature or (session.auth and session.auth.user))
create = wenabled and create
editable = wenabled and editable
deletable = wenabled and deletable
def url(**b):
b['args'] = args+b.get('args',[])
b['user_signature'] = user_signature
return URL(**b)
def gridbutton(buttonclass='buttonadd',buttontext='Add',
buttonurl=url(args=[]),callback=None,delete=None,trap=True):
if showbuttontext:
if callback:
return A(SPAN(_class=ui.get(buttonclass,'')),
SPAN(T(buttontext),_title=buttontext,
_class=ui.get('buttontext','')),
callback=callback,delete=delete,
_class=trap_class(ui.get('button',''),trap))
else:
return A(SPAN(_class=ui.get(buttonclass,'')),
SPAN(T(buttontext),_title=buttontext,
_class=ui.get('buttontext','')),
_href=buttonurl,
_class=trap_class(ui.get('button',''),trap))
else:
if callback:
return A(SPAN(_class=ui.get(buttonclass,'')),
callback=callback,delete=delete,
_title=buttontext,
_class=trap_class(ui.get('buttontext',''),trap))
else:
return A(SPAN(_class=ui.get(buttonclass,'')),
_href=buttonurl,_title=buttontext,
_class=trap_class(ui.get('buttontext',''),trap))
dbset = db(query)
tablenames = db._adapter.tables(dbset.query)
if left!=None: tablenames+=db._adapter.tables(left)
tables = [db[tablename] for tablename in tablenames]
if not fields:
fields = reduce(lambda a,b:a+b,
[[field for field in table] for table in tables])
if not field_id:
field_id = tables[0]._id
columns = [str(field) for field in fields \
if field._tablename in tablenames]
if not str(field_id) in [str(f) for f in fields]:
fields.append(field_id)
table = field_id.table
tablename = table._tablename
referrer = session.get('_web2py_grid_referrer_'+formname, url())
def check_authorization():
if user_signature:
if not URL.verify(request,user_signature=user_signature):
session.flash = T('not authorized')
redirect(referrer)
if upload=='<default>':
upload = lambda filename: url(args=['download',filename])
if len(request.args)>1 and request.args[-2]=='download':
check_authorization()
stream = response.download(request,db)
raise HTTP(200,stream,**response.headers)
def buttons(edit=False,view=False,record=None):
buttons = DIV(gridbutton('buttonback', 'Back', referrer),
_class='form_header row_buttons %(header)s %(cornertop)s' % ui)
if edit:
args = ['edit',table._tablename,request.args[-1]]
buttons.append(gridbutton('buttonedit', 'Edit',
url(args=args)))
if view:
args = ['view',table._tablename,request.args[-1]]
buttons.append(gridbutton('buttonview', 'View',
url(args=args)))
if record and links:
for link in links:
if isinstance(link,dict):
buttons.append(link['body'](record))
elif link(record):
buttons.append(link(record))
return buttons
formfooter = DIV(
_class='form_footer row_buttons %(header)s %(cornerbottom)s' % ui)
create_form = edit_form = None
if create and len(request.args)>1 and request.args[-2]=='new':
check_authorization()
table = db[request.args[-1]]
create_form = SQLFORM(
table, ignore_rw = ignore_rw, formstyle = formstyle,
_class='web2py_form').process(
next=referrer,
onvalidation=onvalidation,
onsuccess=oncreate,
formname=formname)
res = DIV(buttons(),create_form,formfooter,_class=_class)
res.create_form = create_form
res.edit_form = None
res.update_form = None
return res
elif details and len(request.args)>2 and request.args[-3]=='view':
check_authorization()
table = db[request.args[-2]]
record = table(request.args[-1]) or redirect(URL('error'))
form = SQLFORM(table,record,upload=upload,ignore_rw=ignore_rw,
formstyle=formstyle, readonly=True,_class='web2py_form')
res = DIV(buttons(edit=editable,record=record),form,
formfooter,_class=_class)
res.create_form = None
res.edit_form = None
res.update_form = None
return res
elif editable and len(request.args)>2 and request.args[-3]=='edit':
check_authorization()
table = db[request.args[-2]]
record = table(request.args[-1]) or redirect(URL('error'))
edit_form = SQLFORM(table,record,upload=upload,ignore_rw=ignore_rw,
formstyle=formstyle,deletable=deletable,
_class='web2py_form',
submit_button = T('Submit'),
delete_label = T('Check to delete'))
edit_form.process(formname=formname,
onvalidation=onvalidation,
onsuccess=onupdate,
next=referrer)
res = DIV(buttons(view=details,record=record),
edit_form,formfooter,_class=_class)
res.create_form = None
res.edit_form = edit_form
res.update_form = None
return res
elif deletable and len(request.args)>2 and request.args[-3]=='delete':
check_authorization()
table = db[request.args[-2]]
if ondelete:
ondelete(table,request.args[-1])
ret = db(table[table._id.name]==request.args[-1]).delete()
return ret
elif csv and len(request.args)>0 and request.args[-1]=='csv':
if request.vars.keywords:
try:
dbset=dbset(SQLFORM.build_query(
fields,
request.vars.get('keywords','')))
except:
raise HTTP(400)
check_authorization()
response.headers['Content-Type'] = 'text/csv'
response.headers['Content-Disposition'] = \
'attachment;filename=rows.csv;'
raise HTTP(200,str(dbset.select()),
**{'Content-Type':'text/csv',
'Content-Disposition':'attachment;filename=rows.csv;'})
elif request.vars.records and not isinstance(
request.vars.records,list):
request.vars.records=[request.vars.records]
elif not request.vars.records:
request.vars.records=[]
session['_web2py_grid_referrer_'+formname] = \
URL(args=request.args,vars=request.vars,
user_signature=user_signature)
console = DIV(_class='web2py_console %(header)s %(cornertop)s' % ui)
error = None
search_form = None
if searchable:
if search_widget=='default':
search_widget = lambda sfield, url: FORM(
SQLFORM.search_menu(sfields),
INPUT(_name='keywords',_value=request.vars.keywords,
_id='web2py_keywords'),
INPUT(_type='submit',_value=T('Search')),
INPUT(_type='submit',_value=T('Clear'),
_onclick="jQuery('#web2py_keywords').val('');"),
_method="GET",_action=url)
sfields = reduce(lambda a,b:a+b,
[[f for f in t if f.readable] for t in tables])
form = search_widget and search_widget(sfields,url()) or ''
search_form = form
console.append(form)
keywords = request.vars.get('keywords','')
try:
if callable(searchable):
subquery = searchable(sfields, keywords)
else:
subquery = SQLFORM.build_query(sfields, keywords)
except RuntimeError:
subquery = None
error = T('Invalid query')
else:
subquery = None
if subquery:
dbset = dbset(subquery)
try:
if left:
nrows = dbset.select('count(*)',left=left).first()['count(*)']
else:
nrows = dbset.count()
except:
nrows = 0
error = T('Unsupported query')
search_actions = DIV(_class='web2py_search_actions')
if create:
search_actions.append(gridbutton(
buttonclass='buttonadd',
buttontext=T('Add'),
buttonurl=url(args=['new',tablename])))
if csv:
search_actions.append(gridbutton(
buttonclass='buttonexport',
buttontext=T('Export'),
trap = False,
buttonurl=url(args=['csv'],
vars=dict(keywords=request.vars.keywords or ''))))
console.append(search_actions)
order = request.vars.order or ''
if sortable:
if order and not order=='None':
tablename,fieldname = order.split('~')[-1].split('.',1)
sort_field = db[tablename][fieldname]
exception = sort_field.type in ('date','datetime','time')
if exception:
orderby = (order[:1]=='~' and sort_field) or ~sort_field
else:
orderby = (order[:1]=='~' and ~sort_field) or sort_field
head = TR(_class=ui.get('header',''))
if selectable:
head.append(TH(_class=ui.get('default','')))
for field in fields:
if columns and not str(field) in columns: continue
if not field.readable: continue
key = str(field)
header = headers.get(str(field),
hasattr(field,'label') and field.label or key)
if sortable:
if key == order:
key, marker = '~'+order, sorter_icons[0]
elif key == order[1:]:
marker = sorter_icons[1]
else:
marker = ''
header = A(header,marker,_href=url(vars=dict(
keywords=request.vars.keywords or '',
order=key)),_class=trap_class())
head.append(TH(header, _class=ui.get('default','')))
if links and links_in_grid:
for link in links:
if isinstance(link,dict):
head.append(TH(link['header'], _class=ui.get('default','')))
# Include extra column for buttons if needed.
include_buttons_column = (details or editable or deletable or
(links and links_in_grid and
not all([isinstance(link, dict) for link in links])))
if include_buttons_column:
head.append(TH(_class=ui.get('default','')))
paginator = UL()
if paginate and paginate<nrows:
npages,reminder = divmod(nrows,paginate)
if reminder: npages+=1
try: page = int(request.vars.page or 1)-1
except ValueError: page = 0
limitby = (paginate*page,paginate*(page+1))
def self_link(name,p):
d = dict(page=p+1)
if order: d['order']=order
if request.vars.keywords: d['keywords']=request.vars.keywords
return A(name,_href=url(vars=d),_class=trap_class())
NPAGES = 5 # window is 2*NPAGES
if page>NPAGES+1:
paginator.append(LI(self_link('<<',0)))
if page>NPAGES:
paginator.append(LI(self_link('<',page-1)))
pages = range(max(0,page-NPAGES),min(page+NPAGES,npages))
for p in pages:
if p == page:
paginator.append(LI(A(p+1,_onclick='return false'),
_class=trap_class('current')))
else:
paginator.append(LI(self_link(p+1,p)))
if page<npages-NPAGES:
paginator.append(LI(self_link('>',page+1)))
if page<npages-NPAGES-1:
paginator.append(LI(self_link('>>',npages-1)))
else:
limitby = None
try:
table_fields = [f for f in fields if f._tablename in tablenames]
rows = dbset.select(left=left,orderby=orderby,limitby=limitby,*table_fields)
except SyntaxError:
rows = None
error = T("Query Not Supported")
message = error or T('%(nrows)s records found') % dict(nrows=nrows)
console.append(DIV(message,_class='web2py_counter'))
if rows:
htmltable = TABLE(THEAD(head))
tbody = TBODY()
numrec=0
for row in rows:
if numrec % 2 == 0:
classtr = 'even'
else:
classtr = 'odd'
numrec+=1
id = row[field_id]
if id:
rid = id
if callable(rid): ### can this ever be callable?
rid = rid(row)
tr = TR(_id=rid, _class='%s %s' % (classtr, 'with_id'))
else:
tr = TR(_class=classtr)
if selectable:
tr.append(INPUT(_type="checkbox",_name="records",_value=id,
value=request.vars.records))
for field in fields:
if not str(field) in columns: continue
if not field.readable: continue
if field.type=='blob': continue
value = row[field]
maxlength = maxtextlengths.get(str(field),maxtextlength)
if field.represent:
try:
value=field.represent(value,row)
except KeyError:
try:
value=field.represent(value,row[field._tablename])
except KeyError:
pass
elif field.type=='boolean':
value = INPUT(_type="checkbox",_checked = value,
_disabled=True)
elif field.type=='upload':
if value:
if callable(upload):
value = A('File', _href=upload(value))
elif upload:
value = A('File',
_href='%s/%s' % (upload, value))
else:
value = ''
elif isinstance(value,str):
value = truncate_string(value,maxlength)
else:
value = field.formatter(value)
tr.append(TD(value))
row_buttons = TD(_class='row_buttons')
if links and links_in_grid:
for link in links:
if isinstance(link, dict):
tr.append(TD(link['body'](row)))
else:
if link(row):
row_buttons.append(link(row))
if include_buttons_column:
if details and (not callable(details) or details(row)):
row_buttons.append(gridbutton(
'buttonview', 'View',
url(args=['view',tablename,id])))
if editable and (not callable(editable) or editable(row)):
row_buttons.append(gridbutton(
'buttonedit', 'Edit',
url(args=['edit',tablename,id])))
if deletable and (not callable(deletable) or deletable(row)):
row_buttons.append(gridbutton(
'buttondelete', 'Delete',
callback=url(args=['delete',tablename,id]),
delete='tr'))
tr.append(row_buttons)
tbody.append(tr)
htmltable.append(tbody)
htmltable = DIV(htmltable,_style='width:100%;overflow-x:auto')
if selectable:
htmltable = FORM(htmltable,INPUT(_type="submit"))
if htmltable.process(formname=formname).accepted:#
htmltable.vars.records = htmltable.vars.records or []
htmltable.vars.records = htmltable.vars.records if type(htmltable.vars.records) == list else [htmltable.vars.records]
records = [int(r) for r in htmltable.vars.records]
selectable(records)
redirect(referrer)
else:
htmltable = DIV(T('No records found'))
res = DIV(console,
DIV(htmltable,_class="web2py_table"),
DIV(paginator,_class=\
"web2py_paginator %(header)s %(cornerbottom)s" % ui),
_class='%s %s' % (_class, ui.get('widget','')))
res.create_form = create_form
res.edit_form = edit_form
res.search_form = search_form
return res
@staticmethod
def smartgrid(table, constraints=None, linked_tables=None,
links=None, links_in_grid=True,
args=None, user_signature=True,
**kwargs):
"""
@auth.requires_login()
def index():
db.define_table('person',Field('name'),format='%(name)s')
db.define_table('dog',
Field('name'),Field('owner',db.person),format='%(name)s')
db.define_table('comment',Field('body'),Field('dog',db.dog))
if db(db.person).isempty():
from gluon.contrib.populate import populate
populate(db.person,300)
populate(db.dog,300)
populate(db.comment,1000)
db.commit()
form=SQLFORM.smartgrid(db[request.args(0) or 'person']) #***
return dict(form=form)
*** builds a complete interface to navigate all tables links
to the request.args(0)
table: pagination, search, view, edit, delete,
children, parent, etc.
constraints is a dict {'table',query} that limits which
records can be accessible
links is a dict like
{'tablename':[lambda row: A(....), ...]}
that will add buttons when table tablename is displayed
linked_tables is a optional list of tablenames of tables
to be linked
"""
from gluon import current, A, URL, DIV, H3, redirect
request, T = current.request, current.T
if args is None: args = []
db = table._db
breadcrumbs = []
if request.args(len(args)) != table._tablename:
request.args[:]=args+[table._tablename]
if links is None: links = {}
if constraints is None: constraints = {}
try:
nargs = len(args)+1
previous_tablename,previous_fieldname,previous_id = \
table._tablename,None,None
while len(request.args)>nargs:
key = request.args(nargs)
if '.' in key:
id = request.args(nargs+1)
tablename,fieldname = key.split('.',1)
table = db[tablename]
field = table[fieldname]
field.default = id
referee = field.type[10:]
if referee!=previous_tablename:
raise HTTP(400)
cond = constraints.get(referee,None)
if cond:
record = db(db[referee].id==id)(cond).select().first()
else:
record = db[referee](id)
if previous_id:
if record[previous_fieldname] != int(previous_id):
raise HTTP(400)
previous_tablename,previous_fieldname,previous_id = \
tablename,fieldname,id
try:
format = db[referee]._format
if callable(format): name = format(record)
else: name = format % record
except TypeError:
name = id
breadcrumbs += [A(T(db[referee]._plural),
_class=trap_class(),
_href=URL(args=request.args[:nargs])),
' > ',
A(name,_class=trap_class(),
_href=URL(args=request.args[:nargs]+[
'view',referee,id],user_signature=True)),
' > ']
nargs+=2
else:
break
if nargs>len(args)+1:
query = (field == id)
if linked_tables is None or referee in linked_tables:
field.represent = lambda id,r=None,referee=referee,rep=field.represent: A(callable(rep) and rep(id) or id,_class=trap_class(),_href=URL(args=request.args[:nargs]+['view',referee,id], user_signature=user_signature))
except (KeyError,ValueError,TypeError):
redirect(URL(args=table._tablename))
if nargs==len(args)+1:
query = table.id>0
# filter out data info for displayed table
if table._tablename in constraints:
query = query & constraints[table._tablename]
if isinstance(links,dict):
links = links.get(table._tablename,[])
for key in 'columns,orderby,searchable,sortable,paginate,deletable,editable,details,selectable,create'.split(','):
if isinstance(kwargs.get(key,None),dict):
if table._tablename in kwargs[key]:
kwargs[key] = kwargs[key][table._tablename]
else:
del kwargs[key]
for tablename,fieldname in table._referenced_by:
id_field_name = table._id.name
if linked_tables is None or tablename in linked_tables:
args0 = tablename+'.'+fieldname
links.append(
lambda row,t=T(db[tablename]._plural),nargs=nargs,args0=args0:\
A(SPAN(t),_class=trap_class(),_href=URL(
args=request.args[:nargs]+[args0,row[id_field_name]])))
grid=SQLFORM.grid(query,args=request.args[:nargs],links=links,
links_in_grid=links_in_grid,
user_signature=user_signature,**kwargs)
if isinstance(grid,DIV):
breadcrumbs.append(A(T(table._plural),_class=trap_class(),
_href=URL(args=request.args[:nargs])))
grid.insert(0,DIV(H3(*breadcrumbs),_class='web2py_breadcrumbs'))
return grid
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(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] = c.split('.')[-1].replace('_',' ').title()
elif headers=='labels':
headers = {}
for c in columns:
(t,f) = c.split('.')
field = sqlrows.db[t][f]
headers[c] = field.label
if headers is None:
headers = {}
else:
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 not selectid is None: #new implement
if record[self.id_field_name]==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))
if headers!={}: #new implement dict
if isinstance(headers[colname],dict):
if isinstance(headers[colname]['truncate'], int):
r = truncate_string(r, headers[colname]['truncate'])
elif not truncate is None:
r = truncate_string(r, truncate)
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, TicketStorage
from gluon import DAL
SLEEP_MINUTES = 5
errors_path = os.path.join(request.folder, 'errors')
try:
db_string = open(os.path.join(request.folder, 'private', 'ticket_storage.txt')).read().replace('\r','').replace('\n','').strip()
except:
db_string = 'sqlite://storage.db'
db_path = os.path.join(request.folder, 'databases')
tk_db = DAL(db_string, folder=db_path, auto_import=True)
ts = TicketStorage(db=tk_db)
tk_table = ts._get_table(db=tk_db, tablename=ts.tablename, app=request.application)
hashes = {}
while 1:
if request.tickets_db:
print "You're storing tickets yet in database"
sys.exit(1)
for file in os.listdir(errors_path):
filename = os.path.join(errors_path, file)
modified_time = os.stat(filename)[stat.ST_MTIME]
modified_time = datetime.datetime.fromtimestamp(modified_time)
ticket_id = file
ticket_data = open(filename).read()
tk_table.insert(ticket_id=ticket_id,
ticket_data=ticket_data,
created_datetime=modified_time
)
tk_db.commit()
os.unlink(filename)
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 |
USAGE = """
from web2py main folder
python scripts/make_min_web2py.py /path/to/minweb2py
it will mkdir minweb2py and build a minimal web2py installation
- no admin, no examples, one line welcome
- no scripts
- drops same rarely used contrib modules
- more modules could be dropped but minimal difference
"""
# files to include from top level folder (default.py will be rebuilt)
REQUIRED = """
VERSION
web2py.py
fcgihandler.py
gaehandler.py
wsgihandler.py
anyserver.py
applications/__init__.py
applications/welcome/controllers/default.py
"""
# files and folders to exclude from gluon folder (comment with # if needed)
IGNORED = """
gluon/contrib/comet_messaging.py
gluon/contrib/feedparser.py
gluon/contrib/generics.py
gluon/contrib/gql.py
gluon/contrib/populate.py
gluon/contrib/sms_utils.py
gluon/contrib/spreadsheet.py
gluon/tests/
gluon/contrib/markdown/
gluon/contrib/pyfpdf/
gluon/contrib/pymysql/
gluon/contrib/pyrtf/
gluon/contrib/pysimplesoap/
"""
import sys, os, shutil, glob
def main():
global REQUIRED, IGNORED
if len(sys.argv)<2:
print USAGE
# make target folder
target = sys.argv[1]
os.mkdir(target)
# change to os specificsep
REQUIRED = REQUIRED.replace('/',os.sep)
IGNORED = IGNORED.replace('/',os.sep)
# make a list of all files to include
files = [x.strip() for x in REQUIRED.split('\n') \
if x and not x[0]=='#']
ignore = [x.strip() for x in IGNORED.split('\n') \
if x and not x[0]=='#']
def accept(filename):
for p in ignore:
if filename.startswith(p):
return False
return True
pattern = os.path.join('gluon','*.py')
while True:
newfiles = [x for x in glob.glob(pattern) if accept(x)]
if not newfiles: break
files += newfiles
pattern = os.path.join(pattern[:-3],'*.py')
# copy all files, make missing folder, build default.py
files.sort()
defaultpy = os.path.join('applications','welcome','controllers','default.py')
for f in files:
dirs = f.split(os.path.sep)
for i in range(1,len(dirs)):
try: os.mkdir(target+os.sep+os.path.join(*dirs[:i]))
except OSError: pass
if f==defaultpy:
open(os.path.join(target,f),'w').write('def index(): return "hello"\n')
else:
shutil.copyfile(f,os.path.join(target,f))
if __name__=='__main__': main()
| 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 |
import glob
import os
import zipfile
import sys
import re
from BeautifulSoup import BeautifulSoup as BS
def head(styles):
title = '<title>{{=response.title or request.application}}</title>'
items = '\n'.join(["{{response.files.append(URL(request.application,'static','%s'))}}" % (style) for style in styles])
loc="""<style>
div.flash {
position: absolute;
float: right;
padding: 10px;
top: 0px;
right: 0px;
opacity: 0.75;
margin: 10px 10px 10px 10px;
text-align: center;
clear: both;
color: #fff;
font-size: 11pt;
text-align: center;
vertical-align: middle;
cursor: pointer;
background: black;
border: 2px solid #fff;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
z-index: 2;
}
div.error {
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
background-color: red;
color: white;
padding: 3px;
border: 1px solid #666;
}
</style>"""
return "\n%s\n%s\n{{include 'web2py_ajax.html'}}\n%s" % (title,items,loc)
def content():
return """<div class="flash">{{=response.flash or ''}}</div>{{include}}"""
def process(folder):
indexfile = open(os.path.join(folder,'index.html'),'rb')
try:
soup = BS(indexfile.read())
finally:
indexfile.close()
styles = [x['href'] for x in soup.findAll('link')]
soup.find('head').contents=BS(head(styles))
try:
soup.find('h1').contents=BS('{{=response.title or request.application}}')
soup.find('h2').contents=BS("{{=response.subtitle or '=response.subtitle'}}")
except:
pass
for match in (soup.find('div',id='menu'),
soup.find('div',{'class':'menu'}),
soup.find('div',id='nav'),
soup.find('div',{'class':'nav'})):
if match:
match.contents=BS('{{=MENU(response.menu)}}')
break
done=False
for match in (soup.find('div',id='content'),
soup.find('div',{'class':'content'}),
soup.find('div',id='main'),
soup.find('div',{'class':'main'})):
if match:
match.contents=BS(content())
done=True
break
if done:
page = soup.prettify()
page = re.compile("\s*\{\{=response\.flash or ''\}\}\s*",re.MULTILINE)\
.sub("{{=response.flash or ''}}",page)
print page
else:
raise Exception, "Unable to convert"
if __name__=='__main__':
if len(sys.argv)<2:
print """USAGE:
1) start a new web2py application
2) Download a sample free layout from the web into the static/ folder of
your web2py application (make sure a sample index.html is there)
3) run this script with
python layout_make.py /path/to/web2py/applications/app/static/
> /path/to/web2py/applications/app/views/layout.html
"""
elif not os.path.exists(sys.argv[1]):
print 'Folder %s does not exist' % sys.argv[1]
else:
process(sys.argv[1])
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
sessions2trash.py
Run this script in a web2py environment shell e.g. python web2py.py -S app
If models are loaded (-M option) auth.settings.expiration is assumed
for sessions without an expiration. If models are not loaded, sessions older
than 60 minutes are removed. Use the --expiration option to override these
values.
Typical usage:
# Delete expired sessions every 5 minutes
nohup python web2py.py -S app -M -R scripts/sessions2trash.py &
# Delete sessions older than 60 minutes regardless of expiration,
# with verbose output, then exit.
python web2py.py -S app -M -R scripts/sessions2trash.py -A -o -x 3600 -f -v
# Delete all sessions regardless of expiry and exit.
python web2py.py -S app -M -R scripts/sessions2trash.py -A -o -x 0
"""
from gluon.storage import Storage
from optparse import OptionParser
import cPickle
import datetime
import os
import stat
import time
EXPIRATION_MINUTES = 60
SLEEP_MINUTES = 5
VERSION = 0.3
class SessionSet(object):
"""Class representing a set of sessions"""
def __init__(self, expiration, force, verbose):
self.expiration = expiration
self.force = force
self.verbose = verbose
def get(self):
"""Get session files/records."""
raise NotImplementedError
def trash(self):
"""Trash expired sessions."""
now = datetime.datetime.now()
for item in self.get():
status = 'OK'
last_visit = item.last_visit_default()
try:
session = item.get()
if session.auth:
if session.auth.expiration and not self.force:
self.expiration = session.auth.expiration
if session.auth.last_visit:
last_visit = session.auth.last_visit
except:
pass
age = 0
if last_visit:
age = total_seconds(now - last_visit)
if age > self.expiration or not self.expiration:
item.delete()
status = 'trashed'
if self.verbose > 1:
print 'key: %s' % str(item)
print 'expiration: %s seconds' % self.expiration
print 'last visit: %s' % str(last_visit)
print 'age: %s seconds' % age
print 'status: %s' % status
print ''
elif self.verbose > 0:
print('%s %s' % (str(item), status))
class SessionSetDb(SessionSet):
"""Class representing a set of sessions stored in database"""
def __init__(self, expiration, force, verbose):
SessionSet.__init__(self, expiration, force, verbose)
def get(self):
"""Return list of SessionDb instances for existing sessions."""
sessions = []
tablename = 'web2py_session'
if request.application:
tablename = 'web2py_session_' + request.application
if tablename in db:
for row in db(db[tablename].id > 0).select():
sessions.append(SessionDb(row))
return sessions
class SessionSetFiles(SessionSet):
"""Class representing a set of sessions stored in flat files"""
def __init__(self, expiration, force, verbose):
SessionSet.__init__(self, expiration, force, verbose)
def get(self):
"""Return list of SessionFile instances for existing sessions."""
path = os.path.join(request.folder, 'sessions')
return [SessionFile(os.path.join(path, x)) for x in os.listdir(path)]
class SessionDb(object):
"""Class representing a single session stored in database"""
def __init__(self, row):
self.row = row
def delete(self):
self.row.delete_record()
db.commit()
def get(self):
session = Storage()
session.update(cPickle.loads(self.row.session_data))
return session
def last_visit_default(self):
return self.row.modified_datetime
def __str__(self):
return self.row.unique_key
class SessionFile(object):
"""Class representing a single session stored as a flat file"""
def __init__(self, filename):
self.filename = filename
def delete(self):
os.unlink(self.filename)
def get(self):
session = Storage()
with open(self.filename, 'rb+') as f:
session.update(cPickle.load(f))
return session
def last_visit_default(self):
return datetime.datetime.fromtimestamp(
os.stat(self.filename)[stat.ST_MTIME])
def __str__(self):
return self.filename
def total_seconds(delta):
"""
Adapted from Python 2.7's timedelta.total_seconds() method.
Args:
delta: datetime.timedelta instance.
"""
return (delta.microseconds + (delta.seconds + (delta.days * 24 * 3600)) * \
10 ** 6) / 10 ** 6
def main():
"""Main processing."""
usage = '%prog [options]' + '\nVersion: %s' % VERSION
parser = OptionParser(usage=usage)
parser.add_option('-f', '--force',
action='store_true', dest='force', default=False,
help=('Ignore session expiration. '
'Force expiry based on -x option or auth.settings.expiration.')
)
parser.add_option('-o', '--once',
action='store_true', dest='once', default=False,
help='Delete sessions, then exit.',
)
parser.add_option('-s', '--sleep',
dest='sleep', default=SLEEP_MINUTES * 60, type="int",
help='Number of seconds to sleep between executions. Default 300.',
)
parser.add_option('-v', '--verbose',
default=0, action='count',
help="print verbose output, a second -v increases verbosity")
parser.add_option('-x', '--expiration',
dest='expiration', default=None, type="int",
help='Expiration value for sessions without expiration (in seconds)',
)
(options, unused_args) = parser.parse_args()
expiration = options.expiration
if expiration is None:
try:
expiration = auth.settings.expiration
except:
expiration = EXPIRATION_MINUTES * 60
set_db = SessionSetDb(expiration, options.force, options.verbose)
set_files = SessionSetFiles(expiration, options.force, options.verbose)
while True:
set_db.trash()
set_files.trash()
if options.once:
break
else:
if options.verbose:
print 'Sleeping %s seconds' % (options.sleep)
time.sleep(options.sleep)
main()
| Python |
#!/usr/bin/env python
import sys, os, time, subprocess
class Base:
def run_command(self, *args):
"""
Returns the output of a command as a tuple (output, error).
"""
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return p.communicate()
class ServiceBase(Base):
def __init__(self, name, label, stdout=None, stderr=None):
self.name = name
self.label = label
self.stdout = stdout
self.stderr = stderr
self.config_file = None
def load_configuration(self):
"""
Loads the configuration required to build the command-line string
for running web2py. Returns a tuple (command_args, config_dict).
"""
s = os.path.sep
default = dict(
python = 'python',
web2py = os.path.join(s.join(__file__.split(s)[:-3]), 'web2py.py'),
http_enabled = True,
http_ip = '0.0.0.0',
http_port = 8000,
https_enabled = True,
https_ip = '0.0.0.0',
https_port = 8001,
https_key = '',
https_cert = '',
password = '<recycle>',
)
config = default
if self.config_file:
try:
f = open(self.config_file, 'r')
lines = f.readlines()
f.close()
for line in lines:
fields = line.split('=', 1)
if len(fields) == 2:
key, value = fields
key = key.strip()
value = value.strip()
config[key] = value
except:
pass
web2py_path = os.path.dirname(config['web2py'])
os.chdir(web2py_path)
args = [config['python'], config['web2py']]
interfaces = []
ports = []
if config['http_enabled']:
ip = config['http_ip']
port = config['http_port']
interfaces.append('%s:%s' % (ip, port))
ports.append(port)
if config['https_enabled']:
ip = config['https_ip']
port = config['https_port']
key = config['https_key']
cert = config['https_cert']
if key != '' and cert != '':
interfaces.append('%s:%s:%s:%s' % (ip, port, cert, key))
ports.append(ports)
if len(interfaces) == 0:
sys.exit('Configuration error. Must have settings for http and/or https')
password = config['password']
if not password == '<recycle>':
from gluon import main
for port in ports:
main.save_password(password, port)
password = '<recycle>'
args.append('-a "%s"' % password)
interfaces = ';'.join(interfaces)
args.append('--interfaces=%s' % interfaces)
if 'log_filename' in config.key():
log_filename = config['log_filename']
args.append('--log_filename=%s' % log_filename)
return (args, config)
def start(self):
pass
def stop(self):
pass
def restart(self):
pass
def status(self):
pass
def run(self):
pass
def install(self):
pass
def uninstall(self):
pass
def check_permissions(self):
"""
Does the script have permissions to install, uninstall, start, and stop services?
Return value must be a tuple (True/False, error_message_if_False).
"""
return (False, 'Permissions check not implemented')
class WebServerBase(Base):
def install(self):
pass
def uninstall(self):
pass
def get_service():
service_name = 'web2py'
service_label = 'web2py Service'
if sys.platform == 'linux2':
from linux import LinuxService as Service
elif sys.platform == 'darwin':
# from mac import MacService as Service
sys.exit('Mac OS X is not yet supported.\n')
elif sys.platform == 'win32':
# from windows import WindowsService as Service
sys.exit('Windows is not yet supported.\n')
else:
sys.exit('The following platform is not supported: %s.\n' % sys.platform)
service = Service(service_name, service_label)
return service
if __name__ == '__main__':
service = get_service()
is_root, error_message = service.check_permissions()
if not is_root:
sys.exit(error_message)
if len(sys.argv) >= 2:
command = sys.argv[1]
if command == 'start':
service.start()
elif command == 'stop':
service.stop()
elif command == 'restart':
service.restart()
elif command == 'status':
print service.status() + '\n'
elif command == 'run':
service.run()
elif command == 'install':
service.install()
elif command == 'uninstall':
service.uninstall()
elif command == 'install-apache':
# from apache import Apache
# server = Apache()
# server.install()
sys.exit('Configuring Apache is not yet supported.\n')
elif command == 'uninstall-apache':
# from apache import Apache
# server = Apache()
# server.uninstall()
sys.exit('Configuring Apache is not yet supported.\n')
else:
sys.exit('Unknown command: %s' % command)
else:
print 'Usage: %s [command] \n' % sys.argv[0] + \
'\tCommands:\n' + \
'\t\tstart Starts the service\n' + \
'\t\tstop Stop the service\n' + \
'\t\trestart Restart the service\n' + \
'\t\tstatus Check if the service is running\n' + \
'\t\trun Run service is blocking mode\n' + \
'\t\t (Press Ctrl + C to exit)\n' + \
'\t\tinstall Install the service\n' + \
'\t\tuninstall Uninstall the service\n' + \
'\t\tinstall-apache Install as an Apache site\n' + \
'\t\tuninstall-apache Uninstall from Apache\n'
| Python |
from service import ServiceBase
import os, sys, time, subprocess, atexit
from signal import SIGTERM
class LinuxService(ServiceBase):
def __init__(self, name, label, stdout='/dev/null', stderr='/dev/null'):
ServiceBase.__init__(self, name, label, stdout, stderr)
self.pidfile = '/tmp/%s.pid' % name
self.config_file = '/etc/%s.conf' % name
def daemonize(self):
"""
do the UNIX double-fork magic, see Stevens' "Advanced
Programming in the UNIX Environment" for details (ISBN 0201563177)
http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
"""
try:
pid = os.fork()
if pid > 0:
# exit first parent
sys.exit(0)
except OSError, e:
sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror))
return
# decouple from parent environment
os.chdir("/")
os.setsid()
os.umask(0)
# do second fork
try:
pid = os.fork()
if pid > 0:
# exit from second parent
sys.exit(0)
except OSError, e:
sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
return
# redirect standard file descriptors
sys.stdout.flush()
sys.stderr.flush()
si = file('/dev/null', 'r')
so = file(self.stdout or '/dev/null', 'a+')
se = file(self.stderr or '/dev/null', 'a+')
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
def getpid(self):
# Check for a pidfile to see if the daemon already runs
try:
pf = file(self.pidfile,'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
return pid
def status(self):
pid = self.getpid()
if pid:
return 'Service running with PID %s.' % pid
else:
return 'Service is not running.'
def check_permissions(self):
if not os.geteuid() == 0:
return (False, 'This script must be run with root permissions.')
else:
return (True, '')
def start(self):
"""
Start the daemon
"""
pid = self.getpid()
if pid:
message = "Service already running under PID %s\n"
sys.stderr.write(message % self.pidfile)
return
# Start the daemon
self.daemonize()
self.run()
def stop(self):
"""
Stop the daemon
"""
pid = self.getpid()
if not pid:
message = "Service is not running\n"
sys.stderr.write(message)
return # not an error in a restart
# Try killing the daemon process
try:
while 1:
os.kill(pid, SIGTERM)
time.sleep(0.5)
except OSError, err:
err = str(err)
if err.find("No such process") > 0:
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
else:
print str(err)
return
def restart(self):
"""
Restart the daemon
"""
self.stop()
self.start()
def run(self):
atexit.register(self.terminate)
args = self.load_configuration()[0]
stdout = open(self.stdout, 'a+')
stderr = open(self.stderr, 'a+')
process = subprocess.Popen(args, stdout=stdout, stderr=stderr)
file(self.pidfile,'w+').write("%s\n" % process.pid)
process.wait()
self.terminate()
def terminate(self):
try:
os.remove(self.pidfile)
except:
pass
def install(self):
env = self.detect_environment()
src_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'service.py')
# make sure this script is executable
self.run_command('chmod', '+x', src_path)
# link this daemon to the service directory
dest_path = env['rc.d-path'] + self.name
os.symlink(src_path, dest_path)
# start the service at boot
install_command = self.get_service_installer_command(env)
result = self.run_command(*install_command)
self.start()
def uninstall(self):
self.stop()
env = self.detect_environment()
# stop the service from autostarting
uninstall_command = self.get_service_uninstaller_command(env)
result = self.run_command(*uninstall_command)
# remove link to the script from the service directory
path = env['rc.d-path'] + self.name
os.remove(path)
def detect_environment(self):
"""
Returns a dictionary of command/path to the required command-line applications.
One key is 'dist' which will either be 'debian' or 'redhat', which is the best
guess as to which Linux distribution the current system is based on.
"""
check_for = [
'chkconfig',
'service',
'update-rc.d',
'rpm',
'dpkg',
]
env = dict()
for cmd in check_for:
result = self.run_command('which', cmd)
if result[0]:
env[cmd] = result[0].replace('\n', '')
if 'rpm' in env:
env['dist'] = 'redhat'
env['rc.d-path'] = '/etc/rc.d/init.d/'
elif 'dpkg' in env:
env['dist'] = 'debian'
env['rc.d-path'] = '/etc/init.d/'
else:
env['dist'] = 'unknown'
env['rc.d-path'] = '/dev/null/'
return env
def get_service_installer_command(self, env):
"""
Returns list of args required to set a service to run on boot.
"""
if env['dist'] == 'redhat':
cmd = env['chkconfig']
return [cmd, self.name, 'on']
else:
cmd = env['update-rc.d']
return [cmd, self.name, 'defaults']
def get_service_uninstaller_command(self, env):
"""
Returns list of arge required to stop a service from running at boot.
"""
if env['dist'] == 'redhat':
cmd = env['chkconfig']
return [cmd, self.name, 'off']
else:
cmd = env['update-rc.d']
return [cmd, self.name, 'remove']
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# TODO: Comment this code
import sys
import shutil
import os
from gluon.languages import findT, utf8_repr
sys.path.insert(0, '.')
file = sys.argv[1]
apps = sys.argv[2:]
def sync_language(d, data):
''' this function makes sure a translated string will be prefered over an untranslated
string when syncing languages between apps. when both are translated, it prefers the
latter app, as did the original script
'''
for key in data:
# if this string is not in the allready translated data, add it
if key not in d:
d[key] = data[key]
# see if there is a translated string in the original list, but not in the new list
elif (
((d[key] != '') or (d[key] != key)) and
((data[key] == '') or (data[key] == key))
):
d[key] = d[key]
# any other case (wether there is or there isn't a translated string)
else:
d[key] = data[key]
return d
d = {}
for app in apps:
path = 'applications/%s/' % app
findT(path, file)
langfile = open(os.path.join(path, 'languages', '%s.py' % file))
try:
data = eval(langfile.read())
finally:
langfile.close()
d = sync_language(d, data)
path = 'applications/%s/' % apps[-1]
file1 = os.path.join(path, 'languages', '%s.py' % file)
f = open(file1, 'w')
try:
f.write('# coding: utf8\n')
f.write('{\n')
keys = d.keys()
keys.sort()
for key in keys:
f.write('%s:%s,\n' % (utf8_repr(key), utf8_repr(str(d[key]))))
f.write('}\n')
finally:
f.close()
oapps = reversed(apps[:-1])
for app in oapps:
path2 = 'applications/%s/' % app
file2 = os.path.join(path2, 'languages', '%s.py' % file)
shutil.copyfile(file1, file2)
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Create web2py model (python code) to represent PostgreSQL tables.
Features:
* Uses ANSI Standard INFORMATION_SCHEMA (might work with other RDBMS)
* Detects legacy "keyed" tables (not having an "id" PK)
* Connects directly to running databases, no need to do a SQL dump
* Handles notnull, unique and referential constraints
* Detects most common datatypes and default values
* Support PostgreSQL columns comments (ie. for documentation)
Requeriments:
* Needs PostgreSQL pyscopg2 python connector (same as web2py)
* If used against other RDBMS, import and use proper connector (remove pg_ code)
Created by Mariano Reingart, based on a script to "generate schemas from dbs"
(mysql) by Alexandre Andrade
"""
_author__ = "Mariano Reingart <reingart@gmail.com>"
HELP = """
USAGE: extract_pgsql_models db host port user passwd
Call with PostgreSQL database connection parameters,
web2py model will be printed on standard output.
EXAMPLE: python extract_pgsql_models.py mydb localhost 5432 reingart saraza
"""
# Config options
DEBUG = False # print debug messages to STDERR
SCHEMA = 'public' # change if not using default PostgreSQL schema
# Constant for Field keyword parameter order (and filter):
KWARGS = ('type', 'length', 'default', 'required', 'ondelete',
'notnull', 'unique', 'label', 'comment')
import sys
def query(conn, sql,*args):
"Execute a SQL query and return rows as a list of dicts"
cur = conn.cursor()
ret = []
try:
if DEBUG: print >> sys.stderr, "QUERY: ", sql % args
cur.execute(sql, args)
for row in cur:
dic = {}
for i, value in enumerate(row):
field = cur.description[i][0]
dic[field] = value
if DEBUG: print >> sys.stderr, "RET: ", dic
ret.append(dic)
return ret
finally:
cur.close()
def get_tables(conn, schema=SCHEMA):
"List table names in a given schema"
rows = query(conn, """SELECT table_name FROM information_schema.tables
WHERE table_schema = %s
ORDER BY table_name""", schema)
return [row['table_name'] for row in rows]
def get_fields(conn, table):
"Retrieve field list for a given table"
if DEBUG: print >> sys.stderr, "Processing TABLE", table
rows = query(conn, """
SELECT column_name, data_type,
is_nullable,
character_maximum_length,
numeric_precision, numeric_precision_radix, numeric_scale,
column_default
FROM information_schema.columns
WHERE table_name=%s
ORDER BY ordinal_position""", table)
return rows
def define_field(conn, table, field, pks):
"Determine field type, default value, references, etc."
f={}
ref = references(conn, table, field['column_name'])
if ref:
f.update(ref)
elif field['column_default'] and \
field['column_default'].startswith("nextval") and \
field['column_name'] in pks:
# postgresql sequence (SERIAL) and primary key!
f['type'] = "'id'"
elif field['data_type'].startswith('character'):
f['type'] = "'string'"
if field['character_maximum_length']:
f['length'] = field['character_maximum_length']
elif field['data_type'] in ('text', ):
f['type'] = "'text'"
elif field['data_type'] in ('boolean', 'bit'):
f['type'] = "'boolean'"
elif field['data_type'] in ('integer', 'smallint', 'bigint'):
f['type'] = "'integer'"
elif field['data_type'] in ('double precision', 'real' ):
f['type'] = "'double'"
elif field['data_type'] in ('timestamp', 'timestamp without time zone'):
f['type'] = "'datetime'"
elif field['data_type'] in ('date', ):
f['type'] = "'date'"
elif field['data_type'] in ('time', 'time without time zone'):
f['type'] = "'time'"
elif field['data_type'] in ('numeric', 'currency'):
f['type'] = "'decimal'"
f['precision'] = field['numeric_precision']
f['scale'] = field['numeric_scale'] or 0
elif field['data_type'] in ('bytea', ):
f['type'] = "'blob'"
elif field['data_type'] in ('point', 'lseg', 'polygon', 'unknown', 'USER-DEFINED'):
f['type'] = "" # unsupported?
else:
raise RuntimeError("Data Type not supported: %s " % str(field))
try:
if field['column_default']:
if field['column_default']=="now()":
d = "request.now"
elif field['column_default']=="true":
d = "True"
elif field['column_default']=="false":
d = "False"
else:
d = repr(eval(field['column_default']))
f['default'] = str(d)
except (ValueError, SyntaxError):
pass
except Exception, e:
raise RuntimeError("Default unsupported '%s'" % field['column_default'])
if not field['is_nullable']:
f['notnull'] = "True"
comment = get_comment(conn, table, field)
if comment is not None:
f['comment'] = repr(comment)
return f
def is_unique(conn, table, field):
"Find unique columns (incomplete support)"
rows = query(conn, """
SELECT information_schema.constraint_column_usage.column_name
FROM information_schema.table_constraints
NATURAL JOIN information_schema.constraint_column_usage
WHERE information_schema.table_constraints.table_name=%s
AND information_schema.constraint_column_usage.column_name=%s
AND information_schema.table_constraints.constraint_type='UNIQUE'
;""", table, field['column_name'])
return rows and True or False
def get_comment(conn, table, field):
"Find the column comment (postgres specific)"
rows = query(conn, """
SELECT d.description AS comment
FROM pg_class c
JOIN pg_description d ON c.oid=d.objoid
JOIN pg_attribute a ON c.oid = a.attrelid
WHERE c.relname=%s AND a.attname=%s
AND a.attnum = d.objsubid
;""", table, field['column_name'])
return rows and rows[0]['comment'] or None
def primarykeys(conn, table):
"Find primary keys"
rows = query(conn, """
SELECT information_schema.constraint_column_usage.column_name
FROM information_schema.table_constraints
NATURAL JOIN information_schema.constraint_column_usage
WHERE information_schema.table_constraints.table_name=%s
AND information_schema.table_constraints.constraint_type='PRIMARY KEY'
;""", table)
return [row['column_name'] for row in rows]
def references(conn, table, field):
"Find a FK (fails if multiple)"
rows1 = query(conn, """
SELECT table_name, column_name, constraint_name,
update_rule, delete_rule, ordinal_position
FROM information_schema.key_column_usage
NATURAL JOIN information_schema.referential_constraints
NATURAL JOIN information_schema.table_constraints
WHERE information_schema.key_column_usage.table_name=%s
AND information_schema.key_column_usage.column_name=%s
AND information_schema.table_constraints.constraint_type='FOREIGN KEY'
;""", table, field)
if len(rows1)==1:
rows2 = query(conn, """
SELECT table_name, column_name, *
FROM information_schema.constraint_column_usage
WHERE constraint_name=%s
""", rows1[0]['constraint_name'])
row = None
if len(rows2)>1:
row = rows2[int(rows1[0]['ordinal_position'])-1]
keyed = True
if len(rows2)==1:
row = rows2[0]
keyed = False
if row:
if keyed: # THIS IS BAD, DON'T MIX "id" and primarykey!!!
ref = {'type': "'reference %s.%s'" % (row['table_name'],
row['column_name'])}
else:
ref = {'type': "'reference %s'" % (row['table_name'],)}
if rows1[0]['delete_rule']!="NO ACTION":
ref['ondelete'] = repr(rows1[0]['delete_rule'])
return ref
elif rows2:
raise RuntimeError("Unsupported foreign key reference: %s" %
str(rows2))
elif rows1:
raise RuntimeError("Unsupported referential constraint: %s" %
str(rows1))
def define_table(conn, table):
"Output single table definition"
fields = get_fields(conn, table)
pks = primarykeys(conn, table)
print "db.define_table('%s'," % (table, )
for field in fields:
fname = field['column_name']
fdef = define_field(conn, table, field, pks)
if fname not in pks and is_unique(conn, table, field):
fdef['unique'] = "True"
if fdef['type']=="'id'" and fname in pks:
pks.pop(pks.index(fname))
print " Field('%s', %s)," % (fname,
', '.join(["%s=%s" % (k, fdef[k]) for k in KWARGS
if k in fdef and fdef[k]]))
if pks:
print " primarykey=[%s]," % ", ".join(["'%s'" % pk for pk in pks])
print " migrate=migrate)"
print
def define_db(conn, db, host, port, user, passwd):
"Output database definition (model)"
dal = 'db = DAL("postgres://%s:%s@%s:%s/%s", pool_size=10)'
print dal % (user, passwd, host, port, db)
print
print "migrate = False"
print
for table in get_tables(conn):
define_table(conn, table)
if __name__ == "__main__":
if len(sys.argv) < 6:
print HELP
else:
# Parse arguments from command line:
db, host, port, user, passwd = sys.argv[1:6]
# Make the database connection (change driver if required)
import psycopg2
cnn = psycopg2.connect(database=db, host=host, port=port,
user=user, password=passwd,
)
# Start model code generation:
define_db(cnn, db, host, port, user, passwd)
| Python |
import sys
import re
def cleancss(text):
text=re.compile('\s+').sub(' ', text)
text=re.compile('\s*(?P<a>,|:)\s*').sub('\g<a> ', text)
text=re.compile('\s*;\s*').sub(';\n ', text)
text=re.compile('\s*\{\s*').sub(' {\n ', text)
text=re.compile('\s*\}\s*').sub('\n}\n\n', text)
return text
def cleanhtml(text):
text=text.lower()
r=re.compile('\<script.+?/script\>', re.DOTALL)
scripts=r.findall(text)
text=r.sub('<script />', text)
r=re.compile('\<style.+?/style\>', re.DOTALL)
styles=r.findall(text)
text=r.sub('<style />', text)
text=re.compile(
'<(?P<tag>(input|meta|link|hr|br|img|param))(?P<any>[^\>]*)\s*(?<!/)>')\
.sub('<\g<tag>\g<any> />', text)
text=text.replace('\n', ' ')
text=text.replace('>', '>\n')
text=text.replace('<', '\n<')
text=re.compile('\s*\n\s*').sub('\n', text)
lines=text.split('\n')
(indent, newlines)=(0, [])
for line in lines:
if line[:2]=='</': indent=indent-1
newlines.append(indent*' '+line)
if not line[:2]=='</' and line[-1:]=='>' and \
not line[-2:] in ['/>', '->']: indent=indent+1
text='\n'.join(newlines)
text=re.compile('\<div(?P<a>( .+)?)\>\s+\</div\>').sub('<div\g<a>></div>',text)
text=re.compile('\<a(?P<a>( .+)?)\>\s+(?P<b>[\w\s\(\)\/]+?)\s+\</a\>').sub('<a\g<a>>\g<b></a>',text)
text=re.compile('\<b(?P<a>( .+)?)\>\s+(?P<b>[\w\s\(\)\/]+?)\s+\</b\>').sub('<b\g<a>>\g<b></b>',text)
text=re.compile('\<i(?P<a>( .+)?)\>\s+(?P<b>[\w\s\(\)\/]+?)\s+\</i\>').sub('<i\g<a>>\g<b></i>',text)
text=re.compile('\<span(?P<a>( .+)?)\>\s+(?P<b>[\w\s\(\)\/]+?)\s+\</span\>').sub('<span\g<a>>\g<b></span>',text)
text=re.compile('\s+\<br(?P<a>.*?)\/\>').sub('<br\g<a>/>',text)
text=re.compile('\>(?P<a>\s+)(?P<b>[\.\,\:\;])').sub('>\g<b>\g<a>',text)
text=re.compile('\n\s*\n').sub('\n',text)
for script in scripts:
text=text.replace('<script />', script, 1)
for style in styles:
text=text.replace('<style />', cleancss(style), 1)
return text
def read_file(filename):
f = open(filename, 'r')
try:
return f.read()
finally:
f.close()
file=sys.argv[1]
if file[-4:]=='.css':
print cleancss(read_file(file))
if file[-5:]=='.html':
print cleanhtml(read_file(file))
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import re
filename = sys.argv[1]
datafile = open(filename, 'r')
try:
data = '\n'+datafile.read()
finally:
datafile.close()
SPACE = '\n ' if '-n' in sys.argv[1:] else ' '
data = re.compile('(?<!\:)//(?P<a>.*)').sub('/* \g<a> */',data)
data = re.compile('[ ]+').sub(' ', data)
data = re.compile('\s*{\s*').sub(' {'+SPACE, data)
data = re.compile('\s*;\s*').sub(';'+SPACE, data)
data = re.compile(',\s*').sub(', ', data)
data = re.compile('\s*\*/\s*').sub('*/'+SPACE, data)
data = re.compile('\s*}\s*').sub(SPACE+'}\n', data)
data = re.compile('\n\s*\n').sub('\n', data)
data = re.compile(';\s+/\*').sub('; /*',data)
data = re.compile('\*/\s+/\*').sub(' ',data)
data = re.compile('[ ]+\n').sub('\n', data)
data = re.compile('\n\s*/[\*]+(?P<a>.*?)[\*]+/',re.DOTALL).sub(
'\n/*\g<a>*/\n',data)
data = re.compile('[ \t]+(?P<a>\S.+?){').sub('\g<a>{',data)
data = data.replace('}','}\n')
print data
| Python |
'''
Create the web2py code needed to access your mysql legacy db.
To make this work all the legacy tables you want to access need to have an "id" field.
This plugin needs:
mysql
mysqldump
installed and globally available.
Under Windows you will probably need to add the mysql executable directory to the PATH variable,
you will also need to modify mysql to mysql.exe and mysqldump to mysqldump.exe below.
Just guessing here :)
Access your tables with:
legacy_db(legacy_db.mytable.id>0).select()
If the script crashes this is might be due to that fact that the data_type_map dictionary below is incomplete.
Please complete it, improve it and continue.
Created by Falko Krause, minor modifications by Massimo Di Pierro and Ron McOuat
'''
import subprocess
import re
import sys
data_type_map = dict(
varchar = 'string',
int = 'integer',
integer = 'integer',
tinyint = 'integer',
smallint = 'integer',
mediumint = 'integer',
bigint = 'integer',
float = 'double',
double = 'double',
char = 'string',
decimal = 'integer',
date = 'date',
#year = 'date',
time = 'time',
timestamp = 'datetime',
datetime = 'datetime',
binary = 'blob',
blob = 'blob',
tinyblob = 'blob',
mediumblob = 'blob',
longblob = 'blob',
text = 'text',
tinytext = 'text',
mediumtext = 'text',
longtext = 'text',
)
def mysql(database_name, username, password):
p = subprocess.Popen(['mysql',
'--user=%s' % username,
'--password=%s'% password,
'--execute=show tables;',
database_name],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
sql_showtables, stderr = p.communicate()
tables = [re.sub('\|\s+([^\|*])\s+.*', '\1', x) for x in sql_showtables.split()[1:]]
connection_string = "legacy_db = DAL('mysql://%s:%s@localhost/%s')"%(username, password, database_name)
legacy_db_table_web2py_code = []
for table_name in tables:
#get the sql create statement
p = subprocess.Popen(['mysqldump',
'--user=%s' % username,
'--password=%s' % password,
'--skip-add-drop-table',
'--no-data', database_name,
table_name], stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
sql_create_stmnt,stderr = p.communicate()
if 'CREATE' in sql_create_stmnt:#check if the table exists
#remove garbage lines from sql statement
sql_lines = sql_create_stmnt.split('\n')
sql_lines = [x for x in sql_lines if not(x.startswith('--') or x.startswith('/*') or x =='')]
#generate the web2py code from the create statement
web2py_table_code = ''
table_name = re.search('CREATE TABLE .(\S+). \(', sql_lines[0]).group(1)
fields = []
for line in sql_lines[1:-1]:
if re.search('KEY', line) or re.search('PRIMARY', line) or re.search(' ID', line) or line.startswith(')'):
continue
hit = re.search('(\S+)\s+(\S+)(,| )( .*)?', line)
if hit!=None:
name, d_type = hit.group(1), hit.group(2)
d_type = re.sub(r'(\w+)\(.*',r'\1',d_type)
name = re.sub('`','',name)
web2py_table_code += "\n Field('%s','%s'),"%(name,data_type_map[d_type])
web2py_table_code = "legacy_db.define_table('%s',%s\n migrate=False)"%(table_name,web2py_table_code)
legacy_db_table_web2py_code.append(web2py_table_code)
#----------------------------------------
#write the legacy db to file
legacy_db_web2py_code = connection_string+"\n\n"
legacy_db_web2py_code += "\n\n#--------\n".join(legacy_db_table_web2py_code)
return legacy_db_web2py_code
regex = re.compile('(.*?):(.*?)@(.*)')
if len(sys.argv)<2 or not regex.match(sys.argv[1]):
print 'USAGE:\n\n extract_mysql_models.py username:password@data_basename\n\n'
else:
m = regex.match(sys.argv[1])
print mysql(m.group(3),m.group(1),m.group(2))
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
autoroutes writes routes for you based on a simpler routing
configuration file called routes.conf. Example:
----- BEGIN routes.conf-------
127.0.0.1 /examples/default
domain1.com /app1/default
domain2.com /app2/default
domain3.com /app3/default
----- END ----------
It maps a domain (the left-hand side) to an app (one app per domain),
and shortens the URLs for the app by removing the listed path prefix. That means:
http://domain1.com/index is mapped to /app1/default/index
http://domain2.com/index is mapped to /app2/default/index
It preserves admin, appadmin, static files, favicon.ico and robots.txt:
http://domain1.com/favicon.ico /welcome/static/favicon.ico
http://domain1.com/robots.txt /welcome/static/robots.txt
http://domain1.com/admin/... /admin/...
http://domain1.com/appadmin/... /app1/appadmin/...
http://domain1.com/static/... /app1/static/...
and vice-versa.
To use, cp scripts/autoroutes.py routes.py
and either edit the config string below, or set config = "" and edit routes.conf
'''
config = '''
127.0.0.1 /examples/default
domain1.com /app1/default
domain2.com /app2/default
domain3.com /app3/defcon3
'''
if not config.strip():
try:
config_file = open('routes.conf','r')
try:
config = config_file.read()
finally:
config_file.close()
except:
config=''
def auto_in(apps):
routes = [
('/robots.txt','/welcome/static/robots.txt'),
('/favicon.ico','/welcome/static/favicon.ico'),
('/admin$anything','/admin$anything'),
]
for domain,path in [x.strip().split() for x in apps.split('\n') if x.strip() and not x.strip().startswith('#')]:
if not path.startswith('/'): path = '/'+path
if path.endswith('/'): path = path[:-1]
app = path.split('/')[1]
routes += [
('.*:https?://(.*\.)?%s:$method /' % domain,'%s' % path),
('.*:https?://(.*\.)?%s:$method /static/$anything' % domain,'/%s/static/$anything' % app),
('.*:https?://(.*\.)?%s:$method /appadmin/$anything' % domain,'/%s/appadmin/$anything' % app),
('.*:https?://(.*\.)?%s:$method /$anything' % domain,'%s/$anything' % path),
]
return routes
def auto_out(apps):
routes = []
for domain,path in [x.strip().split() for x in apps.split('\n') if x.strip() and not x.strip().startswith('#')]:
if not path.startswith('/'): path = '/'+path
if path.endswith('/'): path = path[:-1]
app = path.split('/')[1]
routes += [
('/%s/static/$anything' % app,'/static/$anything'),
('/%s/appadmin/$anything' % app, '/appadmin/$anything'),
('%s/$anything' % path, '/$anything'),
]
return routes
routes_in = auto_in(config)
routes_out = auto_out(config)
def __routes_doctest():
'''
Dummy function for doctesting autoroutes.py.
Use filter_url() to test incoming or outgoing routes;
filter_err() for error redirection.
filter_url() accepts overrides for method and remote host:
filter_url(url, method='get', remote='0.0.0.0', out=False)
filter_err() accepts overrides for application and ticket:
filter_err(status, application='app', ticket='tkt')
>>> filter_url('http://domain1.com/favicon.ico')
'http://domain1.com/welcome/static/favicon.ico'
>>> filter_url('https://domain2.com/robots.txt')
'https://domain2.com/welcome/static/robots.txt'
>>> filter_url('http://domain3.com/fcn')
'http://domain3.com/app3/defcon3/fcn'
>>> filter_url('http://127.0.0.1/fcn')
'http://127.0.0.1/examples/default/fcn'
>>> filter_url('HTTP://DOMAIN.COM/app/ctr/fcn')
'http://domain.com/app/ctr/fcn'
>>> filter_url('http://domain.com/app/ctr/fcn?query')
'http://domain.com/app/ctr/fcn?query'
>>> filter_url('http://otherdomain.com/fcn')
'http://otherdomain.com/fcn'
>>> regex_filter_out('/app/ctr/fcn')
'/app/ctr/fcn'
>>> regex_filter_out('/app1/ctr/fcn')
'/app1/ctr/fcn'
>>> filter_url('https://otherdomain.com/app1/default/fcn', out=True)
'/fcn'
>>> filter_url('http://otherdomain.com/app2/ctr/fcn', out=True)
'/app2/ctr/fcn'
>>> filter_url('http://domain1.com/app1/default/fcn?query', out=True)
'/fcn?query'
>>> filter_url('http://domain2.com/app3/defcon3/fcn#anchor', out=True)
'/fcn#anchor'
'''
pass
if __name__ == '__main__':
try:
import gluon.main
except ImportError:
import sys, os
os.chdir(os.path.dirname(os.path.dirname(__file__)))
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
import gluon.main
from gluon.rewrite import regex_select, load, filter_url, regex_filter_out
regex_select() # use base routing parameters
load(routes=__file__) # load this file
import doctest
doctest.testmod()
| Python |
#
# This files allows to delegate authentication for every URL within a domain
# to a web2py app within the same domain
# If you are logged in the app, you have access to the URL
# even if the URL is not a web2py URL
#
# in /etc/apache2/sites-available/default
#
# <VirtualHost *:80>
# WSGIDaemonProcess web2py user=www-data group=www-data
# WSGIProcessGroup web2py
# WSGIScriptAlias / /home/www-data/web2py/wsgihandler.py
#
# AliasMatch ^myapp/whatever/myfile /path/to/myfile
# <Directory /path/to/>
# WSGIAccessScript /path/to/web2py/scripts/access.wsgi
# </Directory>
# </VirtualHost>
#
# in yourapp/controllers/default.py
#
# def check_access():
# request_uri = request.vars.request_uri
# return 'true' if auth.is_logged_in() else 'false'
#
# start web2py as deamon
#
# nohup python web2py.py -a '' -p 8002
#
# now try visit:
#
# http://domain/myapp/whatever/myfile
#
# and you will have access ONLY if you are logged into myapp
#
URL_CHECK_ACCESS = 'http://127.0.0.1:8002/%(app)s/default/check_access'
def allow_access(environ,host):
import os
import urllib
import urllib2
import datetime
header = '%s @ %s ' % (datetime.datetime.now(),host) + '='*20
pprint = '\n'.join('%s:%s' % item for item in environ.items())
filename = os.path.join(os.path.dirname(__file__),'access.wsgi.log')
f = open(filename,'a')
try:
f.write('\n'+header+'\n'+pprint+'\n')
finally:
f.close()
app = environ['REQUEST_URI'].split('/')[1]
keys = [key for key in environ if key.startswith('HTTP_')]
headers = {}
for key in environ:
if key.startswith('HTTP_'):
headers[key[5:]] = environ[key] # this passes the cookies through!
try:
data = urllib.urlencode({'request_uri':environ['REQUEST_URI']})
request = urllib2.Request(URL_CHECK_ACCESS % dict(app=app),data,headers)
response = urllib2.urlopen(request).read().strip().lower()
if response.startswith('true'): return True
except: pass
return False
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.