repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
kencochrane/django-defender
defender/connection.py
get_redis_connection
def get_redis_connection(): """ Get the redis connection if not using mock """ if config.MOCK_REDIS: # pragma: no cover import mockredis return mockredis.mock_strict_redis_client() # pragma: no cover elif config.DEFENDER_REDIS_NAME: # pragma: no cover try: cache = caches[config.DEFENDER_REDIS_NAME] except InvalidCacheBackendError: raise KeyError(INVALID_CACHE_ERROR_MSG.format( config.DEFENDER_REDIS_NAME)) # every redis backend implement it own way to get the low level client try: # redis_cache.RedisCache case (django-redis-cache package) return cache.get_master_client() except AttributeError: # django_redis.cache.RedisCache case (django-redis package) return cache.client.get_client(True) else: # pragma: no cover redis_config = parse_redis_url(config.DEFENDER_REDIS_URL) return redis.StrictRedis( host=redis_config.get('HOST'), port=redis_config.get('PORT'), db=redis_config.get('DB'), password=redis_config.get('PASSWORD'), ssl=redis_config.get('SSL'))
python
def get_redis_connection(): """ Get the redis connection if not using mock """ if config.MOCK_REDIS: # pragma: no cover import mockredis return mockredis.mock_strict_redis_client() # pragma: no cover elif config.DEFENDER_REDIS_NAME: # pragma: no cover try: cache = caches[config.DEFENDER_REDIS_NAME] except InvalidCacheBackendError: raise KeyError(INVALID_CACHE_ERROR_MSG.format( config.DEFENDER_REDIS_NAME)) # every redis backend implement it own way to get the low level client try: # redis_cache.RedisCache case (django-redis-cache package) return cache.get_master_client() except AttributeError: # django_redis.cache.RedisCache case (django-redis package) return cache.client.get_client(True) else: # pragma: no cover redis_config = parse_redis_url(config.DEFENDER_REDIS_URL) return redis.StrictRedis( host=redis_config.get('HOST'), port=redis_config.get('PORT'), db=redis_config.get('DB'), password=redis_config.get('PASSWORD'), ssl=redis_config.get('SSL'))
[ "def", "get_redis_connection", "(", ")", ":", "if", "config", ".", "MOCK_REDIS", ":", "# pragma: no cover", "import", "mockredis", "return", "mockredis", ".", "mock_strict_redis_client", "(", ")", "# pragma: no cover", "elif", "config", ".", "DEFENDER_REDIS_NAME", ":", "# pragma: no cover", "try", ":", "cache", "=", "caches", "[", "config", ".", "DEFENDER_REDIS_NAME", "]", "except", "InvalidCacheBackendError", ":", "raise", "KeyError", "(", "INVALID_CACHE_ERROR_MSG", ".", "format", "(", "config", ".", "DEFENDER_REDIS_NAME", ")", ")", "# every redis backend implement it own way to get the low level client", "try", ":", "# redis_cache.RedisCache case (django-redis-cache package)", "return", "cache", ".", "get_master_client", "(", ")", "except", "AttributeError", ":", "# django_redis.cache.RedisCache case (django-redis package)", "return", "cache", ".", "client", ".", "get_client", "(", "True", ")", "else", ":", "# pragma: no cover", "redis_config", "=", "parse_redis_url", "(", "config", ".", "DEFENDER_REDIS_URL", ")", "return", "redis", ".", "StrictRedis", "(", "host", "=", "redis_config", ".", "get", "(", "'HOST'", ")", ",", "port", "=", "redis_config", ".", "get", "(", "'PORT'", ")", ",", "db", "=", "redis_config", ".", "get", "(", "'DB'", ")", ",", "password", "=", "redis_config", ".", "get", "(", "'PASSWORD'", ")", ",", "ssl", "=", "redis_config", ".", "get", "(", "'SSL'", ")", ")" ]
Get the redis connection if not using mock
[ "Get", "the", "redis", "connection", "if", "not", "using", "mock" ]
e3e547dbb83235e0d564a6d64652c7df00412ff2
https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/connection.py#L19-L44
train
kencochrane/django-defender
defender/connection.py
parse_redis_url
def parse_redis_url(url): """Parses a redis URL.""" # create config with some sane defaults redis_config = { "DB": 0, "PASSWORD": None, "HOST": "localhost", "PORT": 6379, "SSL": False } if not url: return redis_config url = urlparse.urlparse(url) # Remove query strings. path = url.path[1:] path = path.split('?', 2)[0] if path: redis_config.update({"DB": int(path)}) if url.password: redis_config.update({"PASSWORD": url.password}) if url.hostname: redis_config.update({"HOST": url.hostname}) if url.port: redis_config.update({"PORT": int(url.port)}) if url.scheme in ['https', 'rediss']: redis_config.update({"SSL": True}) return redis_config
python
def parse_redis_url(url): """Parses a redis URL.""" # create config with some sane defaults redis_config = { "DB": 0, "PASSWORD": None, "HOST": "localhost", "PORT": 6379, "SSL": False } if not url: return redis_config url = urlparse.urlparse(url) # Remove query strings. path = url.path[1:] path = path.split('?', 2)[0] if path: redis_config.update({"DB": int(path)}) if url.password: redis_config.update({"PASSWORD": url.password}) if url.hostname: redis_config.update({"HOST": url.hostname}) if url.port: redis_config.update({"PORT": int(url.port)}) if url.scheme in ['https', 'rediss']: redis_config.update({"SSL": True}) return redis_config
[ "def", "parse_redis_url", "(", "url", ")", ":", "# create config with some sane defaults", "redis_config", "=", "{", "\"DB\"", ":", "0", ",", "\"PASSWORD\"", ":", "None", ",", "\"HOST\"", ":", "\"localhost\"", ",", "\"PORT\"", ":", "6379", ",", "\"SSL\"", ":", "False", "}", "if", "not", "url", ":", "return", "redis_config", "url", "=", "urlparse", ".", "urlparse", "(", "url", ")", "# Remove query strings.", "path", "=", "url", ".", "path", "[", "1", ":", "]", "path", "=", "path", ".", "split", "(", "'?'", ",", "2", ")", "[", "0", "]", "if", "path", ":", "redis_config", ".", "update", "(", "{", "\"DB\"", ":", "int", "(", "path", ")", "}", ")", "if", "url", ".", "password", ":", "redis_config", ".", "update", "(", "{", "\"PASSWORD\"", ":", "url", ".", "password", "}", ")", "if", "url", ".", "hostname", ":", "redis_config", ".", "update", "(", "{", "\"HOST\"", ":", "url", ".", "hostname", "}", ")", "if", "url", ".", "port", ":", "redis_config", ".", "update", "(", "{", "\"PORT\"", ":", "int", "(", "url", ".", "port", ")", "}", ")", "if", "url", ".", "scheme", "in", "[", "'https'", ",", "'rediss'", "]", ":", "redis_config", ".", "update", "(", "{", "\"SSL\"", ":", "True", "}", ")", "return", "redis_config" ]
Parses a redis URL.
[ "Parses", "a", "redis", "URL", "." ]
e3e547dbb83235e0d564a6d64652c7df00412ff2
https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/connection.py#L48-L79
train
kencochrane/django-defender
defender/management/commands/cleanup_django_defender.py
Command.handle
def handle(self, **options): """ Removes any entries in the AccessAttempt that are older than your DEFENDER_ACCESS_ATTEMPT_EXPIRATION config, default 24 HOURS. """ print("Starting clean up of django-defender table") now = timezone.now() cleanup_delta = timedelta(hours=config.ACCESS_ATTEMPT_EXPIRATION) min_attempt_time = now - cleanup_delta attempts_to_clean = AccessAttempt.objects.filter( attempt_time__lt=min_attempt_time, ) attempts_to_clean_count = attempts_to_clean.count() attempts_to_clean.delete() print( "Finished. Removed {0} AccessAttempt entries.".format( attempts_to_clean_count) )
python
def handle(self, **options): """ Removes any entries in the AccessAttempt that are older than your DEFENDER_ACCESS_ATTEMPT_EXPIRATION config, default 24 HOURS. """ print("Starting clean up of django-defender table") now = timezone.now() cleanup_delta = timedelta(hours=config.ACCESS_ATTEMPT_EXPIRATION) min_attempt_time = now - cleanup_delta attempts_to_clean = AccessAttempt.objects.filter( attempt_time__lt=min_attempt_time, ) attempts_to_clean_count = attempts_to_clean.count() attempts_to_clean.delete() print( "Finished. Removed {0} AccessAttempt entries.".format( attempts_to_clean_count) )
[ "def", "handle", "(", "self", ",", "*", "*", "options", ")", ":", "print", "(", "\"Starting clean up of django-defender table\"", ")", "now", "=", "timezone", ".", "now", "(", ")", "cleanup_delta", "=", "timedelta", "(", "hours", "=", "config", ".", "ACCESS_ATTEMPT_EXPIRATION", ")", "min_attempt_time", "=", "now", "-", "cleanup_delta", "attempts_to_clean", "=", "AccessAttempt", ".", "objects", ".", "filter", "(", "attempt_time__lt", "=", "min_attempt_time", ",", ")", "attempts_to_clean_count", "=", "attempts_to_clean", ".", "count", "(", ")", "attempts_to_clean", ".", "delete", "(", ")", "print", "(", "\"Finished. Removed {0} AccessAttempt entries.\"", ".", "format", "(", "attempts_to_clean_count", ")", ")" ]
Removes any entries in the AccessAttempt that are older than your DEFENDER_ACCESS_ATTEMPT_EXPIRATION config, default 24 HOURS.
[ "Removes", "any", "entries", "in", "the", "AccessAttempt", "that", "are", "older", "than", "your", "DEFENDER_ACCESS_ATTEMPT_EXPIRATION", "config", "default", "24", "HOURS", "." ]
e3e547dbb83235e0d564a6d64652c7df00412ff2
https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/management/commands/cleanup_django_defender.py#L15-L35
train
Cito/DBUtils
DBUtils/PooledDB.py
PooledDB.connection
def connection(self, shareable=True): """Get a steady, cached DB-API 2 connection from the pool. If shareable is set and the underlying DB-API 2 allows it, then the connection may be shared with other threads. """ if shareable and self._maxshared: self._lock.acquire() try: while (not self._shared_cache and self._maxconnections and self._connections >= self._maxconnections): self._wait_lock() if len(self._shared_cache) < self._maxshared: # shared cache is not full, get a dedicated connection try: # first try to get it from the idle cache con = self._idle_cache.pop(0) except IndexError: # else get a fresh connection con = self.steady_connection() else: con._ping_check() # check this connection con = SharedDBConnection(con) self._connections += 1 else: # shared cache full or no more connections allowed self._shared_cache.sort() # least shared connection first con = self._shared_cache.pop(0) # get it while con.con._transaction: # do not share connections which are in a transaction self._shared_cache.insert(0, con) self._wait_lock() self._shared_cache.sort() con = self._shared_cache.pop(0) con.con._ping_check() # check the underlying connection con.share() # increase share of this connection # put the connection (back) into the shared cache self._shared_cache.append(con) self._lock.notify() finally: self._lock.release() con = PooledSharedDBConnection(self, con) else: # try to get a dedicated connection self._lock.acquire() try: while (self._maxconnections and self._connections >= self._maxconnections): self._wait_lock() # connection limit not reached, get a dedicated connection try: # first try to get it from the idle cache con = self._idle_cache.pop(0) except IndexError: # else get a fresh connection con = self.steady_connection() else: con._ping_check() # check connection con = PooledDedicatedDBConnection(self, con) self._connections += 1 finally: self._lock.release() return con
python
def connection(self, shareable=True): """Get a steady, cached DB-API 2 connection from the pool. If shareable is set and the underlying DB-API 2 allows it, then the connection may be shared with other threads. """ if shareable and self._maxshared: self._lock.acquire() try: while (not self._shared_cache and self._maxconnections and self._connections >= self._maxconnections): self._wait_lock() if len(self._shared_cache) < self._maxshared: # shared cache is not full, get a dedicated connection try: # first try to get it from the idle cache con = self._idle_cache.pop(0) except IndexError: # else get a fresh connection con = self.steady_connection() else: con._ping_check() # check this connection con = SharedDBConnection(con) self._connections += 1 else: # shared cache full or no more connections allowed self._shared_cache.sort() # least shared connection first con = self._shared_cache.pop(0) # get it while con.con._transaction: # do not share connections which are in a transaction self._shared_cache.insert(0, con) self._wait_lock() self._shared_cache.sort() con = self._shared_cache.pop(0) con.con._ping_check() # check the underlying connection con.share() # increase share of this connection # put the connection (back) into the shared cache self._shared_cache.append(con) self._lock.notify() finally: self._lock.release() con = PooledSharedDBConnection(self, con) else: # try to get a dedicated connection self._lock.acquire() try: while (self._maxconnections and self._connections >= self._maxconnections): self._wait_lock() # connection limit not reached, get a dedicated connection try: # first try to get it from the idle cache con = self._idle_cache.pop(0) except IndexError: # else get a fresh connection con = self.steady_connection() else: con._ping_check() # check connection con = PooledDedicatedDBConnection(self, con) self._connections += 1 finally: self._lock.release() return con
[ "def", "connection", "(", "self", ",", "shareable", "=", "True", ")", ":", "if", "shareable", "and", "self", ".", "_maxshared", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "while", "(", "not", "self", ".", "_shared_cache", "and", "self", ".", "_maxconnections", "and", "self", ".", "_connections", ">=", "self", ".", "_maxconnections", ")", ":", "self", ".", "_wait_lock", "(", ")", "if", "len", "(", "self", ".", "_shared_cache", ")", "<", "self", ".", "_maxshared", ":", "# shared cache is not full, get a dedicated connection", "try", ":", "# first try to get it from the idle cache", "con", "=", "self", ".", "_idle_cache", ".", "pop", "(", "0", ")", "except", "IndexError", ":", "# else get a fresh connection", "con", "=", "self", ".", "steady_connection", "(", ")", "else", ":", "con", ".", "_ping_check", "(", ")", "# check this connection", "con", "=", "SharedDBConnection", "(", "con", ")", "self", ".", "_connections", "+=", "1", "else", ":", "# shared cache full or no more connections allowed", "self", ".", "_shared_cache", ".", "sort", "(", ")", "# least shared connection first", "con", "=", "self", ".", "_shared_cache", ".", "pop", "(", "0", ")", "# get it", "while", "con", ".", "con", ".", "_transaction", ":", "# do not share connections which are in a transaction", "self", ".", "_shared_cache", ".", "insert", "(", "0", ",", "con", ")", "self", ".", "_wait_lock", "(", ")", "self", ".", "_shared_cache", ".", "sort", "(", ")", "con", "=", "self", ".", "_shared_cache", ".", "pop", "(", "0", ")", "con", ".", "con", ".", "_ping_check", "(", ")", "# check the underlying connection", "con", ".", "share", "(", ")", "# increase share of this connection", "# put the connection (back) into the shared cache", "self", ".", "_shared_cache", ".", "append", "(", "con", ")", "self", ".", "_lock", ".", "notify", "(", ")", "finally", ":", "self", ".", "_lock", ".", "release", "(", ")", "con", "=", "PooledSharedDBConnection", "(", "self", ",", "con", ")", "else", ":", "# try to get a dedicated connection", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "while", "(", "self", ".", "_maxconnections", "and", "self", ".", "_connections", ">=", "self", ".", "_maxconnections", ")", ":", "self", ".", "_wait_lock", "(", ")", "# connection limit not reached, get a dedicated connection", "try", ":", "# first try to get it from the idle cache", "con", "=", "self", ".", "_idle_cache", ".", "pop", "(", "0", ")", "except", "IndexError", ":", "# else get a fresh connection", "con", "=", "self", ".", "steady_connection", "(", ")", "else", ":", "con", ".", "_ping_check", "(", ")", "# check connection", "con", "=", "PooledDedicatedDBConnection", "(", "self", ",", "con", ")", "self", ".", "_connections", "+=", "1", "finally", ":", "self", ".", "_lock", ".", "release", "(", ")", "return", "con" ]
Get a steady, cached DB-API 2 connection from the pool. If shareable is set and the underlying DB-API 2 allows it, then the connection may be shared with other threads.
[ "Get", "a", "steady", "cached", "DB", "-", "API", "2", "connection", "from", "the", "pool", "." ]
90e8825e038f08c82044b8e50831480175fa026a
https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PooledDB.py#L277-L334
train
Cito/DBUtils
DBUtils/PooledDB.py
PooledDB.unshare
def unshare(self, con): """Decrease the share of a connection in the shared cache.""" self._lock.acquire() try: con.unshare() shared = con.shared if not shared: # connection is idle, try: # so try to remove it self._shared_cache.remove(con) # from shared cache except ValueError: pass # pool has already been closed finally: self._lock.release() if not shared: # connection has become idle, self.cache(con.con)
python
def unshare(self, con): """Decrease the share of a connection in the shared cache.""" self._lock.acquire() try: con.unshare() shared = con.shared if not shared: # connection is idle, try: # so try to remove it self._shared_cache.remove(con) # from shared cache except ValueError: pass # pool has already been closed finally: self._lock.release() if not shared: # connection has become idle, self.cache(con.con)
[ "def", "unshare", "(", "self", ",", "con", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "con", ".", "unshare", "(", ")", "shared", "=", "con", ".", "shared", "if", "not", "shared", ":", "# connection is idle,", "try", ":", "# so try to remove it", "self", ".", "_shared_cache", ".", "remove", "(", "con", ")", "# from shared cache", "except", "ValueError", ":", "pass", "# pool has already been closed", "finally", ":", "self", ".", "_lock", ".", "release", "(", ")", "if", "not", "shared", ":", "# connection has become idle,", "self", ".", "cache", "(", "con", ".", "con", ")" ]
Decrease the share of a connection in the shared cache.
[ "Decrease", "the", "share", "of", "a", "connection", "in", "the", "shared", "cache", "." ]
90e8825e038f08c82044b8e50831480175fa026a
https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PooledDB.py#L340-L354
train
Cito/DBUtils
DBUtils/PooledDB.py
PooledSharedDBConnection.close
def close(self): """Close the pooled shared connection.""" # Instead of actually closing the connection, # unshare it and/or return it to the pool. if self._con: self._pool.unshare(self._shared_con) self._shared_con = self._con = None
python
def close(self): """Close the pooled shared connection.""" # Instead of actually closing the connection, # unshare it and/or return it to the pool. if self._con: self._pool.unshare(self._shared_con) self._shared_con = self._con = None
[ "def", "close", "(", "self", ")", ":", "# Instead of actually closing the connection,", "# unshare it and/or return it to the pool.", "if", "self", ".", "_con", ":", "self", ".", "_pool", ".", "unshare", "(", "self", ".", "_shared_con", ")", "self", ".", "_shared_con", "=", "self", ".", "_con", "=", "None" ]
Close the pooled shared connection.
[ "Close", "the", "pooled", "shared", "connection", "." ]
90e8825e038f08c82044b8e50831480175fa026a
https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PooledDB.py#L516-L522
train
Cito/DBUtils
DBUtils/PersistentDB.py
PersistentDB.steady_connection
def steady_connection(self): """Get a steady, non-persistent DB-API 2 connection.""" return connect( self._creator, self._maxusage, self._setsession, self._failures, self._ping, self._closeable, *self._args, **self._kwargs)
python
def steady_connection(self): """Get a steady, non-persistent DB-API 2 connection.""" return connect( self._creator, self._maxusage, self._setsession, self._failures, self._ping, self._closeable, *self._args, **self._kwargs)
[ "def", "steady_connection", "(", "self", ")", ":", "return", "connect", "(", "self", ".", "_creator", ",", "self", ".", "_maxusage", ",", "self", ".", "_setsession", ",", "self", ".", "_failures", ",", "self", ".", "_ping", ",", "self", ".", "_closeable", ",", "*", "self", ".", "_args", ",", "*", "*", "self", ".", "_kwargs", ")" ]
Get a steady, non-persistent DB-API 2 connection.
[ "Get", "a", "steady", "non", "-", "persistent", "DB", "-", "API", "2", "connection", "." ]
90e8825e038f08c82044b8e50831480175fa026a
https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PersistentDB.py#L201-L206
train
Cito/DBUtils
DBUtils/PersistentDB.py
PersistentDB.connection
def connection(self, shareable=False): """Get a steady, persistent DB-API 2 connection. The shareable parameter exists only for compatibility with the PooledDB connection method. In reality, persistent connections are of course never shared with other threads. """ try: con = self.thread.connection except AttributeError: con = self.steady_connection() if not con.threadsafety(): raise NotSupportedError("Database module is not thread-safe.") self.thread.connection = con con._ping_check() return con
python
def connection(self, shareable=False): """Get a steady, persistent DB-API 2 connection. The shareable parameter exists only for compatibility with the PooledDB connection method. In reality, persistent connections are of course never shared with other threads. """ try: con = self.thread.connection except AttributeError: con = self.steady_connection() if not con.threadsafety(): raise NotSupportedError("Database module is not thread-safe.") self.thread.connection = con con._ping_check() return con
[ "def", "connection", "(", "self", ",", "shareable", "=", "False", ")", ":", "try", ":", "con", "=", "self", ".", "thread", ".", "connection", "except", "AttributeError", ":", "con", "=", "self", ".", "steady_connection", "(", ")", "if", "not", "con", ".", "threadsafety", "(", ")", ":", "raise", "NotSupportedError", "(", "\"Database module is not thread-safe.\"", ")", "self", ".", "thread", ".", "connection", "=", "con", "con", ".", "_ping_check", "(", ")", "return", "con" ]
Get a steady, persistent DB-API 2 connection. The shareable parameter exists only for compatibility with the PooledDB connection method. In reality, persistent connections are of course never shared with other threads.
[ "Get", "a", "steady", "persistent", "DB", "-", "API", "2", "connection", "." ]
90e8825e038f08c82044b8e50831480175fa026a
https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PersistentDB.py#L208-L224
train
Cito/DBUtils
DBUtils/PersistentPg.py
PersistentPg.steady_connection
def steady_connection(self): """Get a steady, non-persistent PyGreSQL connection.""" return SteadyPgConnection( self._maxusage, self._setsession, self._closeable, *self._args, **self._kwargs)
python
def steady_connection(self): """Get a steady, non-persistent PyGreSQL connection.""" return SteadyPgConnection( self._maxusage, self._setsession, self._closeable, *self._args, **self._kwargs)
[ "def", "steady_connection", "(", "self", ")", ":", "return", "SteadyPgConnection", "(", "self", ".", "_maxusage", ",", "self", ".", "_setsession", ",", "self", ".", "_closeable", ",", "*", "self", ".", "_args", ",", "*", "*", "self", ".", "_kwargs", ")" ]
Get a steady, non-persistent PyGreSQL connection.
[ "Get", "a", "steady", "non", "-", "persistent", "PyGreSQL", "connection", "." ]
90e8825e038f08c82044b8e50831480175fa026a
https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PersistentPg.py#L160-L164
train
Cito/DBUtils
DBUtils/PersistentPg.py
PersistentPg.connection
def connection(self): """Get a steady, persistent PyGreSQL connection.""" try: con = self.thread.connection except AttributeError: con = self.steady_connection() self.thread.connection = con return con
python
def connection(self): """Get a steady, persistent PyGreSQL connection.""" try: con = self.thread.connection except AttributeError: con = self.steady_connection() self.thread.connection = con return con
[ "def", "connection", "(", "self", ")", ":", "try", ":", "con", "=", "self", ".", "thread", ".", "connection", "except", "AttributeError", ":", "con", "=", "self", ".", "steady_connection", "(", ")", "self", ".", "thread", ".", "connection", "=", "con", "return", "con" ]
Get a steady, persistent PyGreSQL connection.
[ "Get", "a", "steady", "persistent", "PyGreSQL", "connection", "." ]
90e8825e038f08c82044b8e50831480175fa026a
https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PersistentPg.py#L166-L173
train
Cito/DBUtils
setversion.py
versionString
def versionString(version): """Create version string. For a sequence containing version information such as (2, 0, 0, 'pre'), this returns a printable string such as '2.0pre'. The micro version number is only excluded from the string if it is zero. """ ver = list(map(str, version)) numbers, rest = ver[:2 if ver[2] == '0' else 3], ver[3:] return '.'.join(numbers) + '-'.join(rest)
python
def versionString(version): """Create version string. For a sequence containing version information such as (2, 0, 0, 'pre'), this returns a printable string such as '2.0pre'. The micro version number is only excluded from the string if it is zero. """ ver = list(map(str, version)) numbers, rest = ver[:2 if ver[2] == '0' else 3], ver[3:] return '.'.join(numbers) + '-'.join(rest)
[ "def", "versionString", "(", "version", ")", ":", "ver", "=", "list", "(", "map", "(", "str", ",", "version", ")", ")", "numbers", ",", "rest", "=", "ver", "[", ":", "2", "if", "ver", "[", "2", "]", "==", "'0'", "else", "3", "]", ",", "ver", "[", "3", ":", "]", "return", "'.'", ".", "join", "(", "numbers", ")", "+", "'-'", ".", "join", "(", "rest", ")" ]
Create version string. For a sequence containing version information such as (2, 0, 0, 'pre'), this returns a printable string such as '2.0pre'. The micro version number is only excluded from the string if it is zero.
[ "Create", "version", "string", "." ]
90e8825e038f08c82044b8e50831480175fa026a
https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/setversion.py#L37-L47
train
Cito/DBUtils
DBUtils/PooledPg.py
PooledPg.steady_connection
def steady_connection(self): """Get a steady, unpooled PostgreSQL connection.""" return SteadyPgConnection(self._maxusage, self._setsession, True, *self._args, **self._kwargs)
python
def steady_connection(self): """Get a steady, unpooled PostgreSQL connection.""" return SteadyPgConnection(self._maxusage, self._setsession, True, *self._args, **self._kwargs)
[ "def", "steady_connection", "(", "self", ")", ":", "return", "SteadyPgConnection", "(", "self", ".", "_maxusage", ",", "self", ".", "_setsession", ",", "True", ",", "*", "self", ".", "_args", ",", "*", "*", "self", ".", "_kwargs", ")" ]
Get a steady, unpooled PostgreSQL connection.
[ "Get", "a", "steady", "unpooled", "PostgreSQL", "connection", "." ]
90e8825e038f08c82044b8e50831480175fa026a
https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PooledPg.py#L200-L203
train
Cito/DBUtils
DBUtils/PooledPg.py
PooledPg.connection
def connection(self): """Get a steady, cached PostgreSQL connection from the pool.""" if self._connections: if not self._connections.acquire(self._blocking): raise TooManyConnections try: con = self._cache.get(0) except Empty: con = self.steady_connection() return PooledPgConnection(self, con)
python
def connection(self): """Get a steady, cached PostgreSQL connection from the pool.""" if self._connections: if not self._connections.acquire(self._blocking): raise TooManyConnections try: con = self._cache.get(0) except Empty: con = self.steady_connection() return PooledPgConnection(self, con)
[ "def", "connection", "(", "self", ")", ":", "if", "self", ".", "_connections", ":", "if", "not", "self", ".", "_connections", ".", "acquire", "(", "self", ".", "_blocking", ")", ":", "raise", "TooManyConnections", "try", ":", "con", "=", "self", ".", "_cache", ".", "get", "(", "0", ")", "except", "Empty", ":", "con", "=", "self", ".", "steady_connection", "(", ")", "return", "PooledPgConnection", "(", "self", ",", "con", ")" ]
Get a steady, cached PostgreSQL connection from the pool.
[ "Get", "a", "steady", "cached", "PostgreSQL", "connection", "from", "the", "pool", "." ]
90e8825e038f08c82044b8e50831480175fa026a
https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PooledPg.py#L205-L214
train
Cito/DBUtils
DBUtils/PooledPg.py
PooledPg.cache
def cache(self, con): """Put a connection back into the pool cache.""" try: if self._reset == 2: con.reset() # reset the connection completely else: if self._reset or con._transaction: try: con.rollback() # rollback a possible transaction except Exception: pass self._cache.put(con, 0) # and then put it back into the cache except Full: con.close() if self._connections: self._connections.release()
python
def cache(self, con): """Put a connection back into the pool cache.""" try: if self._reset == 2: con.reset() # reset the connection completely else: if self._reset or con._transaction: try: con.rollback() # rollback a possible transaction except Exception: pass self._cache.put(con, 0) # and then put it back into the cache except Full: con.close() if self._connections: self._connections.release()
[ "def", "cache", "(", "self", ",", "con", ")", ":", "try", ":", "if", "self", ".", "_reset", "==", "2", ":", "con", ".", "reset", "(", ")", "# reset the connection completely", "else", ":", "if", "self", ".", "_reset", "or", "con", ".", "_transaction", ":", "try", ":", "con", ".", "rollback", "(", ")", "# rollback a possible transaction", "except", "Exception", ":", "pass", "self", ".", "_cache", ".", "put", "(", "con", ",", "0", ")", "# and then put it back into the cache", "except", "Full", ":", "con", ".", "close", "(", ")", "if", "self", ".", "_connections", ":", "self", ".", "_connections", ".", "release", "(", ")" ]
Put a connection back into the pool cache.
[ "Put", "a", "connection", "back", "into", "the", "pool", "cache", "." ]
90e8825e038f08c82044b8e50831480175fa026a
https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PooledPg.py#L216-L231
train
Cito/DBUtils
DBUtils/PooledPg.py
PooledPgConnection.reopen
def reopen(self): """Reopen the pooled connection.""" # If the connection is already back in the pool, # get another connection from the pool, # otherwise reopen the underlying connection. if self._con: self._con.reopen() else: self._con = self._pool.connection()
python
def reopen(self): """Reopen the pooled connection.""" # If the connection is already back in the pool, # get another connection from the pool, # otherwise reopen the underlying connection. if self._con: self._con.reopen() else: self._con = self._pool.connection()
[ "def", "reopen", "(", "self", ")", ":", "# If the connection is already back in the pool,", "# get another connection from the pool,", "# otherwise reopen the underlying connection.", "if", "self", ".", "_con", ":", "self", ".", "_con", ".", "reopen", "(", ")", "else", ":", "self", ".", "_con", "=", "self", ".", "_pool", ".", "connection", "(", ")" ]
Reopen the pooled connection.
[ "Reopen", "the", "pooled", "connection", "." ]
90e8825e038f08c82044b8e50831480175fa026a
https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PooledPg.py#L278-L286
train
Cito/DBUtils
DBUtils/SteadyPg.py
SteadyPgConnection.reopen
def reopen(self): """Reopen the tough connection. It will not complain if the connection cannot be reopened. """ try: self._con.reopen() except Exception: if self._transcation: self._transaction = False try: self._con.query('rollback') except Exception: pass else: self._transaction = False self._closed = False self._setsession() self._usage = 0
python
def reopen(self): """Reopen the tough connection. It will not complain if the connection cannot be reopened. """ try: self._con.reopen() except Exception: if self._transcation: self._transaction = False try: self._con.query('rollback') except Exception: pass else: self._transaction = False self._closed = False self._setsession() self._usage = 0
[ "def", "reopen", "(", "self", ")", ":", "try", ":", "self", ".", "_con", ".", "reopen", "(", ")", "except", "Exception", ":", "if", "self", ".", "_transcation", ":", "self", ".", "_transaction", "=", "False", "try", ":", "self", ".", "_con", ".", "query", "(", "'rollback'", ")", "except", "Exception", ":", "pass", "else", ":", "self", ".", "_transaction", "=", "False", "self", ".", "_closed", "=", "False", "self", ".", "_setsession", "(", ")", "self", ".", "_usage", "=", "0" ]
Reopen the tough connection. It will not complain if the connection cannot be reopened.
[ "Reopen", "the", "tough", "connection", "." ]
90e8825e038f08c82044b8e50831480175fa026a
https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyPg.py#L188-L207
train
Cito/DBUtils
DBUtils/SteadyPg.py
SteadyPgConnection.reset
def reset(self): """Reset the tough connection. If a reset is not possible, tries to reopen the connection. It will not complain if the connection is already closed. """ try: self._con.reset() self._transaction = False self._setsession() self._usage = 0 except Exception: try: self.reopen() except Exception: try: self.rollback() except Exception: pass
python
def reset(self): """Reset the tough connection. If a reset is not possible, tries to reopen the connection. It will not complain if the connection is already closed. """ try: self._con.reset() self._transaction = False self._setsession() self._usage = 0 except Exception: try: self.reopen() except Exception: try: self.rollback() except Exception: pass
[ "def", "reset", "(", "self", ")", ":", "try", ":", "self", ".", "_con", ".", "reset", "(", ")", "self", ".", "_transaction", "=", "False", "self", ".", "_setsession", "(", ")", "self", ".", "_usage", "=", "0", "except", "Exception", ":", "try", ":", "self", ".", "reopen", "(", ")", "except", "Exception", ":", "try", ":", "self", ".", "rollback", "(", ")", "except", "Exception", ":", "pass" ]
Reset the tough connection. If a reset is not possible, tries to reopen the connection. It will not complain if the connection is already closed.
[ "Reset", "the", "tough", "connection", "." ]
90e8825e038f08c82044b8e50831480175fa026a
https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyPg.py#L209-L228
train
Cito/DBUtils
DBUtils/SteadyPg.py
SteadyPgConnection._get_tough_method
def _get_tough_method(self, method): """Return a "tough" version of a connection class method. The tough version checks whether the connection is bad (lost) and automatically and transparently tries to reset the connection if this is the case (for instance, the database has been restarted). """ def tough_method(*args, **kwargs): transaction = self._transaction if not transaction: try: # check whether connection status is bad if not self._con.db.status: raise AttributeError if self._maxusage: # or connection used too often if self._usage >= self._maxusage: raise AttributeError except Exception: self.reset() # then reset the connection try: result = method(*args, **kwargs) # try connection method except Exception: # error in query if transaction: # inside a transaction self._transaction = False raise # propagate the error elif self._con.db.status: # if it was not a connection problem raise # then propagate the error else: # otherwise self.reset() # reset the connection result = method(*args, **kwargs) # and try one more time self._usage += 1 return result return tough_method
python
def _get_tough_method(self, method): """Return a "tough" version of a connection class method. The tough version checks whether the connection is bad (lost) and automatically and transparently tries to reset the connection if this is the case (for instance, the database has been restarted). """ def tough_method(*args, **kwargs): transaction = self._transaction if not transaction: try: # check whether connection status is bad if not self._con.db.status: raise AttributeError if self._maxusage: # or connection used too often if self._usage >= self._maxusage: raise AttributeError except Exception: self.reset() # then reset the connection try: result = method(*args, **kwargs) # try connection method except Exception: # error in query if transaction: # inside a transaction self._transaction = False raise # propagate the error elif self._con.db.status: # if it was not a connection problem raise # then propagate the error else: # otherwise self.reset() # reset the connection result = method(*args, **kwargs) # and try one more time self._usage += 1 return result return tough_method
[ "def", "_get_tough_method", "(", "self", ",", "method", ")", ":", "def", "tough_method", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "transaction", "=", "self", ".", "_transaction", "if", "not", "transaction", ":", "try", ":", "# check whether connection status is bad", "if", "not", "self", ".", "_con", ".", "db", ".", "status", ":", "raise", "AttributeError", "if", "self", ".", "_maxusage", ":", "# or connection used too often", "if", "self", ".", "_usage", ">=", "self", ".", "_maxusage", ":", "raise", "AttributeError", "except", "Exception", ":", "self", ".", "reset", "(", ")", "# then reset the connection", "try", ":", "result", "=", "method", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# try connection method", "except", "Exception", ":", "# error in query", "if", "transaction", ":", "# inside a transaction", "self", ".", "_transaction", "=", "False", "raise", "# propagate the error", "elif", "self", ".", "_con", ".", "db", ".", "status", ":", "# if it was not a connection problem", "raise", "# then propagate the error", "else", ":", "# otherwise", "self", ".", "reset", "(", ")", "# reset the connection", "result", "=", "method", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# and try one more time", "self", ".", "_usage", "+=", "1", "return", "result", "return", "tough_method" ]
Return a "tough" version of a connection class method. The tough version checks whether the connection is bad (lost) and automatically and transparently tries to reset the connection if this is the case (for instance, the database has been restarted).
[ "Return", "a", "tough", "version", "of", "a", "connection", "class", "method", "." ]
90e8825e038f08c82044b8e50831480175fa026a
https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyPg.py#L283-L315
train
Cito/DBUtils
DBUtils/SteadyDB.py
connect
def connect( creator, maxusage=None, setsession=None, failures=None, ping=1, closeable=True, *args, **kwargs): """A tough version of the connection constructor of a DB-API 2 module. creator: either an arbitrary function returning new DB-API 2 compliant connection objects or a DB-API 2 compliant database module maxusage: maximum usage limit for the underlying DB-API 2 connection (number of database operations, 0 or None means unlimited usage) callproc(), execute() and executemany() count as one operation. When the limit is reached, the connection is automatically reset. setsession: an optional list of SQL commands that may serve to prepare the session, e.g. ["set datestyle to german", "set time zone mez"] failures: an optional exception class or a tuple of exception classes for which the failover mechanism shall be applied, if the default (OperationalError, InternalError) is not adequate ping: determines when the connection should be checked with ping() (0 = None = never, 1 = default = when _ping_check() is called, 2 = whenever a cursor is created, 4 = when a query is executed, 7 = always, and all other bit combinations of these values) closeable: if this is set to false, then closing the connection will be silently ignored, but by default the connection can be closed args, kwargs: the parameters that shall be passed to the creator function or the connection constructor of the DB-API 2 module """ return SteadyDBConnection( creator, maxusage, setsession, failures, ping, closeable, *args, **kwargs)
python
def connect( creator, maxusage=None, setsession=None, failures=None, ping=1, closeable=True, *args, **kwargs): """A tough version of the connection constructor of a DB-API 2 module. creator: either an arbitrary function returning new DB-API 2 compliant connection objects or a DB-API 2 compliant database module maxusage: maximum usage limit for the underlying DB-API 2 connection (number of database operations, 0 or None means unlimited usage) callproc(), execute() and executemany() count as one operation. When the limit is reached, the connection is automatically reset. setsession: an optional list of SQL commands that may serve to prepare the session, e.g. ["set datestyle to german", "set time zone mez"] failures: an optional exception class or a tuple of exception classes for which the failover mechanism shall be applied, if the default (OperationalError, InternalError) is not adequate ping: determines when the connection should be checked with ping() (0 = None = never, 1 = default = when _ping_check() is called, 2 = whenever a cursor is created, 4 = when a query is executed, 7 = always, and all other bit combinations of these values) closeable: if this is set to false, then closing the connection will be silently ignored, but by default the connection can be closed args, kwargs: the parameters that shall be passed to the creator function or the connection constructor of the DB-API 2 module """ return SteadyDBConnection( creator, maxusage, setsession, failures, ping, closeable, *args, **kwargs)
[ "def", "connect", "(", "creator", ",", "maxusage", "=", "None", ",", "setsession", "=", "None", ",", "failures", "=", "None", ",", "ping", "=", "1", ",", "closeable", "=", "True", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "SteadyDBConnection", "(", "creator", ",", "maxusage", ",", "setsession", ",", "failures", ",", "ping", ",", "closeable", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
A tough version of the connection constructor of a DB-API 2 module. creator: either an arbitrary function returning new DB-API 2 compliant connection objects or a DB-API 2 compliant database module maxusage: maximum usage limit for the underlying DB-API 2 connection (number of database operations, 0 or None means unlimited usage) callproc(), execute() and executemany() count as one operation. When the limit is reached, the connection is automatically reset. setsession: an optional list of SQL commands that may serve to prepare the session, e.g. ["set datestyle to german", "set time zone mez"] failures: an optional exception class or a tuple of exception classes for which the failover mechanism shall be applied, if the default (OperationalError, InternalError) is not adequate ping: determines when the connection should be checked with ping() (0 = None = never, 1 = default = when _ping_check() is called, 2 = whenever a cursor is created, 4 = when a query is executed, 7 = always, and all other bit combinations of these values) closeable: if this is set to false, then closing the connection will be silently ignored, but by default the connection can be closed args, kwargs: the parameters that shall be passed to the creator function or the connection constructor of the DB-API 2 module
[ "A", "tough", "version", "of", "the", "connection", "constructor", "of", "a", "DB", "-", "API", "2", "module", "." ]
90e8825e038f08c82044b8e50831480175fa026a
https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyDB.py#L111-L139
train
Cito/DBUtils
DBUtils/SteadyDB.py
SteadyDBConnection._create
def _create(self): """Create a new connection using the creator function.""" con = self._creator(*self._args, **self._kwargs) try: try: if self._dbapi.connect != self._creator: raise AttributeError except AttributeError: # try finding the DB-API 2 module via the connection itself try: mod = con.__module__ except AttributeError: mod = None while mod: try: self._dbapi = sys.modules[mod] if not callable(self._dbapi.connect): raise AttributeError except (AttributeError, KeyError): pass else: break i = mod.rfind('.') if i < 0: mod = None else: mod = mod[:i] else: try: mod = con.OperationalError.__module__ except AttributeError: mod = None while mod: try: self._dbapi = sys.modules[mod] if not callable(self._dbapi.connect): raise AttributeError except (AttributeError, KeyError): pass else: break i = mod.rfind('.') if i < 0: mod = None else: mod = mod[:i] else: self._dbapi = None if self._threadsafety is None: try: self._threadsafety = self._dbapi.threadsafety except AttributeError: try: self._threadsafety = con.threadsafety except AttributeError: pass if self._failures is None: try: self._failures = ( self._dbapi.OperationalError, self._dbapi.InternalError) except AttributeError: try: self._failures = ( self._creator.OperationalError, self._creator.InternalError) except AttributeError: try: self._failures = ( con.OperationalError, con.InternalError) except AttributeError: raise AttributeError( "Could not determine failure exceptions" " (please set failures or creator.dbapi).") if isinstance(self._failures, tuple): self._failure = self._failures[0] else: self._failure = self._failures self._setsession(con) except Exception as error: # the database module could not be determined # or the session could not be prepared try: # close the connection first con.close() except Exception: pass raise error # re-raise the original error again return con
python
def _create(self): """Create a new connection using the creator function.""" con = self._creator(*self._args, **self._kwargs) try: try: if self._dbapi.connect != self._creator: raise AttributeError except AttributeError: # try finding the DB-API 2 module via the connection itself try: mod = con.__module__ except AttributeError: mod = None while mod: try: self._dbapi = sys.modules[mod] if not callable(self._dbapi.connect): raise AttributeError except (AttributeError, KeyError): pass else: break i = mod.rfind('.') if i < 0: mod = None else: mod = mod[:i] else: try: mod = con.OperationalError.__module__ except AttributeError: mod = None while mod: try: self._dbapi = sys.modules[mod] if not callable(self._dbapi.connect): raise AttributeError except (AttributeError, KeyError): pass else: break i = mod.rfind('.') if i < 0: mod = None else: mod = mod[:i] else: self._dbapi = None if self._threadsafety is None: try: self._threadsafety = self._dbapi.threadsafety except AttributeError: try: self._threadsafety = con.threadsafety except AttributeError: pass if self._failures is None: try: self._failures = ( self._dbapi.OperationalError, self._dbapi.InternalError) except AttributeError: try: self._failures = ( self._creator.OperationalError, self._creator.InternalError) except AttributeError: try: self._failures = ( con.OperationalError, con.InternalError) except AttributeError: raise AttributeError( "Could not determine failure exceptions" " (please set failures or creator.dbapi).") if isinstance(self._failures, tuple): self._failure = self._failures[0] else: self._failure = self._failures self._setsession(con) except Exception as error: # the database module could not be determined # or the session could not be prepared try: # close the connection first con.close() except Exception: pass raise error # re-raise the original error again return con
[ "def", "_create", "(", "self", ")", ":", "con", "=", "self", ".", "_creator", "(", "*", "self", ".", "_args", ",", "*", "*", "self", ".", "_kwargs", ")", "try", ":", "try", ":", "if", "self", ".", "_dbapi", ".", "connect", "!=", "self", ".", "_creator", ":", "raise", "AttributeError", "except", "AttributeError", ":", "# try finding the DB-API 2 module via the connection itself", "try", ":", "mod", "=", "con", ".", "__module__", "except", "AttributeError", ":", "mod", "=", "None", "while", "mod", ":", "try", ":", "self", ".", "_dbapi", "=", "sys", ".", "modules", "[", "mod", "]", "if", "not", "callable", "(", "self", ".", "_dbapi", ".", "connect", ")", ":", "raise", "AttributeError", "except", "(", "AttributeError", ",", "KeyError", ")", ":", "pass", "else", ":", "break", "i", "=", "mod", ".", "rfind", "(", "'.'", ")", "if", "i", "<", "0", ":", "mod", "=", "None", "else", ":", "mod", "=", "mod", "[", ":", "i", "]", "else", ":", "try", ":", "mod", "=", "con", ".", "OperationalError", ".", "__module__", "except", "AttributeError", ":", "mod", "=", "None", "while", "mod", ":", "try", ":", "self", ".", "_dbapi", "=", "sys", ".", "modules", "[", "mod", "]", "if", "not", "callable", "(", "self", ".", "_dbapi", ".", "connect", ")", ":", "raise", "AttributeError", "except", "(", "AttributeError", ",", "KeyError", ")", ":", "pass", "else", ":", "break", "i", "=", "mod", ".", "rfind", "(", "'.'", ")", "if", "i", "<", "0", ":", "mod", "=", "None", "else", ":", "mod", "=", "mod", "[", ":", "i", "]", "else", ":", "self", ".", "_dbapi", "=", "None", "if", "self", ".", "_threadsafety", "is", "None", ":", "try", ":", "self", ".", "_threadsafety", "=", "self", ".", "_dbapi", ".", "threadsafety", "except", "AttributeError", ":", "try", ":", "self", ".", "_threadsafety", "=", "con", ".", "threadsafety", "except", "AttributeError", ":", "pass", "if", "self", ".", "_failures", "is", "None", ":", "try", ":", "self", ".", "_failures", "=", "(", "self", ".", "_dbapi", ".", "OperationalError", ",", "self", ".", "_dbapi", ".", "InternalError", ")", "except", "AttributeError", ":", "try", ":", "self", ".", "_failures", "=", "(", "self", ".", "_creator", ".", "OperationalError", ",", "self", ".", "_creator", ".", "InternalError", ")", "except", "AttributeError", ":", "try", ":", "self", ".", "_failures", "=", "(", "con", ".", "OperationalError", ",", "con", ".", "InternalError", ")", "except", "AttributeError", ":", "raise", "AttributeError", "(", "\"Could not determine failure exceptions\"", "\" (please set failures or creator.dbapi).\"", ")", "if", "isinstance", "(", "self", ".", "_failures", ",", "tuple", ")", ":", "self", ".", "_failure", "=", "self", ".", "_failures", "[", "0", "]", "else", ":", "self", ".", "_failure", "=", "self", ".", "_failures", "self", ".", "_setsession", "(", "con", ")", "except", "Exception", "as", "error", ":", "# the database module could not be determined", "# or the session could not be prepared", "try", ":", "# close the connection first", "con", ".", "close", "(", ")", "except", "Exception", ":", "pass", "raise", "error", "# re-raise the original error again", "return", "con" ]
Create a new connection using the creator function.
[ "Create", "a", "new", "connection", "using", "the", "creator", "function", "." ]
90e8825e038f08c82044b8e50831480175fa026a
https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyDB.py#L209-L296
train
Cito/DBUtils
DBUtils/SteadyDB.py
SteadyDBConnection._store
def _store(self, con): """Store a database connection for subsequent use.""" self._con = con self._transaction = False self._closed = False self._usage = 0
python
def _store(self, con): """Store a database connection for subsequent use.""" self._con = con self._transaction = False self._closed = False self._usage = 0
[ "def", "_store", "(", "self", ",", "con", ")", ":", "self", ".", "_con", "=", "con", "self", ".", "_transaction", "=", "False", "self", ".", "_closed", "=", "False", "self", ".", "_usage", "=", "0" ]
Store a database connection for subsequent use.
[ "Store", "a", "database", "connection", "for", "subsequent", "use", "." ]
90e8825e038f08c82044b8e50831480175fa026a
https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyDB.py#L308-L313
train
Cito/DBUtils
DBUtils/SteadyDB.py
SteadyDBConnection._reset
def _reset(self, force=False): """Reset a tough connection. Rollback if forced or the connection was in a transaction. """ if not self._closed and (force or self._transaction): try: self.rollback() except Exception: pass
python
def _reset(self, force=False): """Reset a tough connection. Rollback if forced or the connection was in a transaction. """ if not self._closed and (force or self._transaction): try: self.rollback() except Exception: pass
[ "def", "_reset", "(", "self", ",", "force", "=", "False", ")", ":", "if", "not", "self", ".", "_closed", "and", "(", "force", "or", "self", ".", "_transaction", ")", ":", "try", ":", "self", ".", "rollback", "(", ")", "except", "Exception", ":", "pass" ]
Reset a tough connection. Rollback if forced or the connection was in a transaction.
[ "Reset", "a", "tough", "connection", "." ]
90e8825e038f08c82044b8e50831480175fa026a
https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyDB.py#L330-L340
train
Cito/DBUtils
DBUtils/SteadyDB.py
SteadyDBConnection.begin
def begin(self, *args, **kwargs): """Indicate the beginning of a transaction. During a transaction, connections won't be transparently replaced, and all errors will be raised to the application. If the underlying driver supports this method, it will be called with the given parameters (e.g. for distributed transactions). """ self._transaction = True try: begin = self._con.begin except AttributeError: pass else: begin(*args, **kwargs)
python
def begin(self, *args, **kwargs): """Indicate the beginning of a transaction. During a transaction, connections won't be transparently replaced, and all errors will be raised to the application. If the underlying driver supports this method, it will be called with the given parameters (e.g. for distributed transactions). """ self._transaction = True try: begin = self._con.begin except AttributeError: pass else: begin(*args, **kwargs)
[ "def", "begin", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_transaction", "=", "True", "try", ":", "begin", "=", "self", ".", "_con", ".", "begin", "except", "AttributeError", ":", "pass", "else", ":", "begin", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Indicate the beginning of a transaction. During a transaction, connections won't be transparently replaced, and all errors will be raised to the application. If the underlying driver supports this method, it will be called with the given parameters (e.g. for distributed transactions).
[ "Indicate", "the", "beginning", "of", "a", "transaction", "." ]
90e8825e038f08c82044b8e50831480175fa026a
https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyDB.py#L409-L425
train
Cito/DBUtils
DBUtils/SteadyDB.py
SteadyDBConnection.commit
def commit(self): """Commit any pending transaction.""" self._transaction = False try: self._con.commit() except self._failures as error: # cannot commit try: # try to reopen the connection con = self._create() except Exception: pass else: self._close() self._store(con) raise error
python
def commit(self): """Commit any pending transaction.""" self._transaction = False try: self._con.commit() except self._failures as error: # cannot commit try: # try to reopen the connection con = self._create() except Exception: pass else: self._close() self._store(con) raise error
[ "def", "commit", "(", "self", ")", ":", "self", ".", "_transaction", "=", "False", "try", ":", "self", ".", "_con", ".", "commit", "(", ")", "except", "self", ".", "_failures", "as", "error", ":", "# cannot commit", "try", ":", "# try to reopen the connection", "con", "=", "self", ".", "_create", "(", ")", "except", "Exception", ":", "pass", "else", ":", "self", ".", "_close", "(", ")", "self", ".", "_store", "(", "con", ")", "raise", "error" ]
Commit any pending transaction.
[ "Commit", "any", "pending", "transaction", "." ]
90e8825e038f08c82044b8e50831480175fa026a
https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyDB.py#L427-L440
train
Cito/DBUtils
DBUtils/SteadyDB.py
SteadyDBConnection.cancel
def cancel(self): """Cancel a long-running transaction. If the underlying driver supports this method, it will be called. """ self._transaction = False try: cancel = self._con.cancel except AttributeError: pass else: cancel()
python
def cancel(self): """Cancel a long-running transaction. If the underlying driver supports this method, it will be called. """ self._transaction = False try: cancel = self._con.cancel except AttributeError: pass else: cancel()
[ "def", "cancel", "(", "self", ")", ":", "self", ".", "_transaction", "=", "False", "try", ":", "cancel", "=", "self", ".", "_con", ".", "cancel", "except", "AttributeError", ":", "pass", "else", ":", "cancel", "(", ")" ]
Cancel a long-running transaction. If the underlying driver supports this method, it will be called.
[ "Cancel", "a", "long", "-", "running", "transaction", "." ]
90e8825e038f08c82044b8e50831480175fa026a
https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyDB.py#L457-L469
train
Cito/DBUtils
DBUtils/SteadyDB.py
SteadyDBCursor._setsizes
def _setsizes(self, cursor=None): """Set stored input and output sizes for cursor execution.""" if cursor is None: cursor = self._cursor if self._inputsizes: cursor.setinputsizes(self._inputsizes) for column, size in self._outputsizes.items(): if column is None: cursor.setoutputsize(size) else: cursor.setoutputsize(size, column)
python
def _setsizes(self, cursor=None): """Set stored input and output sizes for cursor execution.""" if cursor is None: cursor = self._cursor if self._inputsizes: cursor.setinputsizes(self._inputsizes) for column, size in self._outputsizes.items(): if column is None: cursor.setoutputsize(size) else: cursor.setoutputsize(size, column)
[ "def", "_setsizes", "(", "self", ",", "cursor", "=", "None", ")", ":", "if", "cursor", "is", "None", ":", "cursor", "=", "self", ".", "_cursor", "if", "self", ".", "_inputsizes", ":", "cursor", ".", "setinputsizes", "(", "self", ".", "_inputsizes", ")", "for", "column", ",", "size", "in", "self", ".", "_outputsizes", ".", "items", "(", ")", ":", "if", "column", "is", "None", ":", "cursor", ".", "setoutputsize", "(", "size", ")", "else", ":", "cursor", ".", "setoutputsize", "(", "size", ",", "column", ")" ]
Set stored input and output sizes for cursor execution.
[ "Set", "stored", "input", "and", "output", "sizes", "for", "cursor", "execution", "." ]
90e8825e038f08c82044b8e50831480175fa026a
https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyDB.py#L564-L574
train
Cito/DBUtils
DBUtils/SteadyDB.py
SteadyDBCursor.close
def close(self): """Close the tough cursor. It will not complain if you close it more than once. """ if not self._closed: try: self._cursor.close() except Exception: pass self._closed = True
python
def close(self): """Close the tough cursor. It will not complain if you close it more than once. """ if not self._closed: try: self._cursor.close() except Exception: pass self._closed = True
[ "def", "close", "(", "self", ")", ":", "if", "not", "self", ".", "_closed", ":", "try", ":", "self", ".", "_cursor", ".", "close", "(", ")", "except", "Exception", ":", "pass", "self", ".", "_closed", "=", "True" ]
Close the tough cursor. It will not complain if you close it more than once.
[ "Close", "the", "tough", "cursor", "." ]
90e8825e038f08c82044b8e50831480175fa026a
https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyDB.py#L576-L587
train
Cito/DBUtils
DBUtils/SteadyDB.py
SteadyDBCursor._get_tough_method
def _get_tough_method(self, name): """Return a "tough" version of the given cursor method.""" def tough_method(*args, **kwargs): execute = name.startswith('execute') con = self._con transaction = con._transaction if not transaction: con._ping_check(4) try: if con._maxusage: if con._usage >= con._maxusage: # the connection was used too often raise con._failure if execute: self._setsizes() method = getattr(self._cursor, name) result = method(*args, **kwargs) # try to execute if execute: self._clearsizes() except con._failures as error: # execution error if not transaction: try: cursor2 = con._cursor( *self._args, **self._kwargs) # open new cursor except Exception: pass else: try: # and try one more time to execute if execute: self._setsizes(cursor2) method = getattr(cursor2, name) result = method(*args, **kwargs) if execute: self._clearsizes() except Exception: pass else: self.close() self._cursor = cursor2 con._usage += 1 return result try: cursor2.close() except Exception: pass try: # try to reopen the connection con2 = con._create() except Exception: pass else: try: cursor2 = con2.cursor( *self._args, **self._kwargs) # open new cursor except Exception: pass else: if transaction: self.close() con._close() con._store(con2) self._cursor = cursor2 raise error # raise the original error again error2 = None try: # try one more time to execute if execute: self._setsizes(cursor2) method2 = getattr(cursor2, name) result = method2(*args, **kwargs) if execute: self._clearsizes() except error.__class__: # same execution error use2 = False error2 = error except Exception as error: # other execution errors use2 = True error2 = error else: use2 = True if use2: self.close() con._close() con._store(con2) self._cursor = cursor2 con._usage += 1 if error2: raise error2 # raise the other error return result try: cursor2.close() except Exception: pass try: con2.close() except Exception: pass if transaction: self._transaction = False raise error # re-raise the original error again else: con._usage += 1 return result return tough_method
python
def _get_tough_method(self, name): """Return a "tough" version of the given cursor method.""" def tough_method(*args, **kwargs): execute = name.startswith('execute') con = self._con transaction = con._transaction if not transaction: con._ping_check(4) try: if con._maxusage: if con._usage >= con._maxusage: # the connection was used too often raise con._failure if execute: self._setsizes() method = getattr(self._cursor, name) result = method(*args, **kwargs) # try to execute if execute: self._clearsizes() except con._failures as error: # execution error if not transaction: try: cursor2 = con._cursor( *self._args, **self._kwargs) # open new cursor except Exception: pass else: try: # and try one more time to execute if execute: self._setsizes(cursor2) method = getattr(cursor2, name) result = method(*args, **kwargs) if execute: self._clearsizes() except Exception: pass else: self.close() self._cursor = cursor2 con._usage += 1 return result try: cursor2.close() except Exception: pass try: # try to reopen the connection con2 = con._create() except Exception: pass else: try: cursor2 = con2.cursor( *self._args, **self._kwargs) # open new cursor except Exception: pass else: if transaction: self.close() con._close() con._store(con2) self._cursor = cursor2 raise error # raise the original error again error2 = None try: # try one more time to execute if execute: self._setsizes(cursor2) method2 = getattr(cursor2, name) result = method2(*args, **kwargs) if execute: self._clearsizes() except error.__class__: # same execution error use2 = False error2 = error except Exception as error: # other execution errors use2 = True error2 = error else: use2 = True if use2: self.close() con._close() con._store(con2) self._cursor = cursor2 con._usage += 1 if error2: raise error2 # raise the other error return result try: cursor2.close() except Exception: pass try: con2.close() except Exception: pass if transaction: self._transaction = False raise error # re-raise the original error again else: con._usage += 1 return result return tough_method
[ "def", "_get_tough_method", "(", "self", ",", "name", ")", ":", "def", "tough_method", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "execute", "=", "name", ".", "startswith", "(", "'execute'", ")", "con", "=", "self", ".", "_con", "transaction", "=", "con", ".", "_transaction", "if", "not", "transaction", ":", "con", ".", "_ping_check", "(", "4", ")", "try", ":", "if", "con", ".", "_maxusage", ":", "if", "con", ".", "_usage", ">=", "con", ".", "_maxusage", ":", "# the connection was used too often", "raise", "con", ".", "_failure", "if", "execute", ":", "self", ".", "_setsizes", "(", ")", "method", "=", "getattr", "(", "self", ".", "_cursor", ",", "name", ")", "result", "=", "method", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# try to execute", "if", "execute", ":", "self", ".", "_clearsizes", "(", ")", "except", "con", ".", "_failures", "as", "error", ":", "# execution error", "if", "not", "transaction", ":", "try", ":", "cursor2", "=", "con", ".", "_cursor", "(", "*", "self", ".", "_args", ",", "*", "*", "self", ".", "_kwargs", ")", "# open new cursor", "except", "Exception", ":", "pass", "else", ":", "try", ":", "# and try one more time to execute", "if", "execute", ":", "self", ".", "_setsizes", "(", "cursor2", ")", "method", "=", "getattr", "(", "cursor2", ",", "name", ")", "result", "=", "method", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "execute", ":", "self", ".", "_clearsizes", "(", ")", "except", "Exception", ":", "pass", "else", ":", "self", ".", "close", "(", ")", "self", ".", "_cursor", "=", "cursor2", "con", ".", "_usage", "+=", "1", "return", "result", "try", ":", "cursor2", ".", "close", "(", ")", "except", "Exception", ":", "pass", "try", ":", "# try to reopen the connection", "con2", "=", "con", ".", "_create", "(", ")", "except", "Exception", ":", "pass", "else", ":", "try", ":", "cursor2", "=", "con2", ".", "cursor", "(", "*", "self", ".", "_args", ",", "*", "*", "self", ".", "_kwargs", ")", "# open new cursor", "except", "Exception", ":", "pass", "else", ":", "if", "transaction", ":", "self", ".", "close", "(", ")", "con", ".", "_close", "(", ")", "con", ".", "_store", "(", "con2", ")", "self", ".", "_cursor", "=", "cursor2", "raise", "error", "# raise the original error again", "error2", "=", "None", "try", ":", "# try one more time to execute", "if", "execute", ":", "self", ".", "_setsizes", "(", "cursor2", ")", "method2", "=", "getattr", "(", "cursor2", ",", "name", ")", "result", "=", "method2", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "execute", ":", "self", ".", "_clearsizes", "(", ")", "except", "error", ".", "__class__", ":", "# same execution error", "use2", "=", "False", "error2", "=", "error", "except", "Exception", "as", "error", ":", "# other execution errors", "use2", "=", "True", "error2", "=", "error", "else", ":", "use2", "=", "True", "if", "use2", ":", "self", ".", "close", "(", ")", "con", ".", "_close", "(", ")", "con", ".", "_store", "(", "con2", ")", "self", ".", "_cursor", "=", "cursor2", "con", ".", "_usage", "+=", "1", "if", "error2", ":", "raise", "error2", "# raise the other error", "return", "result", "try", ":", "cursor2", ".", "close", "(", ")", "except", "Exception", ":", "pass", "try", ":", "con2", ".", "close", "(", ")", "except", "Exception", ":", "pass", "if", "transaction", ":", "self", ".", "_transaction", "=", "False", "raise", "error", "# re-raise the original error again", "else", ":", "con", ".", "_usage", "+=", "1", "return", "result", "return", "tough_method" ]
Return a "tough" version of the given cursor method.
[ "Return", "a", "tough", "version", "of", "the", "given", "cursor", "method", "." ]
90e8825e038f08c82044b8e50831480175fa026a
https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyDB.py#L589-L690
train
mcs07/ChemDataExtractor
chemdataextractor/cli/tokenize.py
train_punkt
def train_punkt(ctx, input, output, abbr, colloc): """Train Punkt sentence splitter using sentences in input.""" click.echo('chemdataextractor.tokenize.train_punkt') import pickle from nltk.tokenize.punkt import PunktSentenceTokenizer, PunktTrainer punkt = PunktTrainer() # Set these to true to include collocations more leniently, then increase MIN_COLLOC_FREQ to restrict again # punkt.INCLUDE_ALL_COLLOCS = False # punkt.INCLUDE_ABBREV_COLLOCS = False # punkt.MIN_COLLOC_FREQ = 1 # Don't train on titles. They may contain abbreviations, but basically never have actual sentence boundaries. for fin in input: click.echo('Training on %s' % fin.name) sentences = fin.read() #.replace('.\n', '. \n\n') punkt.train(sentences, finalize=False, verbose=True) punkt.finalize_training(verbose=True) if abbr: abbreviations = abbr.read().strip().split('\n') click.echo('Manually adding abbreviations: %s' % abbreviations) punkt._params.abbrev_types.update(abbreviations) if colloc: collocations = [tuple(l.split('. ', 1)) for l in colloc.read().strip().split('\n')] click.echo('Manually adding collocs: %s' % collocations) punkt._params.collocations.update(collocations) model = PunktSentenceTokenizer(punkt.get_params()) pickle.dump(model, output, protocol=pickle.HIGHEST_PROTOCOL)
python
def train_punkt(ctx, input, output, abbr, colloc): """Train Punkt sentence splitter using sentences in input.""" click.echo('chemdataextractor.tokenize.train_punkt') import pickle from nltk.tokenize.punkt import PunktSentenceTokenizer, PunktTrainer punkt = PunktTrainer() # Set these to true to include collocations more leniently, then increase MIN_COLLOC_FREQ to restrict again # punkt.INCLUDE_ALL_COLLOCS = False # punkt.INCLUDE_ABBREV_COLLOCS = False # punkt.MIN_COLLOC_FREQ = 1 # Don't train on titles. They may contain abbreviations, but basically never have actual sentence boundaries. for fin in input: click.echo('Training on %s' % fin.name) sentences = fin.read() #.replace('.\n', '. \n\n') punkt.train(sentences, finalize=False, verbose=True) punkt.finalize_training(verbose=True) if abbr: abbreviations = abbr.read().strip().split('\n') click.echo('Manually adding abbreviations: %s' % abbreviations) punkt._params.abbrev_types.update(abbreviations) if colloc: collocations = [tuple(l.split('. ', 1)) for l in colloc.read().strip().split('\n')] click.echo('Manually adding collocs: %s' % collocations) punkt._params.collocations.update(collocations) model = PunktSentenceTokenizer(punkt.get_params()) pickle.dump(model, output, protocol=pickle.HIGHEST_PROTOCOL)
[ "def", "train_punkt", "(", "ctx", ",", "input", ",", "output", ",", "abbr", ",", "colloc", ")", ":", "click", ".", "echo", "(", "'chemdataextractor.tokenize.train_punkt'", ")", "import", "pickle", "from", "nltk", ".", "tokenize", ".", "punkt", "import", "PunktSentenceTokenizer", ",", "PunktTrainer", "punkt", "=", "PunktTrainer", "(", ")", "# Set these to true to include collocations more leniently, then increase MIN_COLLOC_FREQ to restrict again", "# punkt.INCLUDE_ALL_COLLOCS = False", "# punkt.INCLUDE_ABBREV_COLLOCS = False", "# punkt.MIN_COLLOC_FREQ = 1", "# Don't train on titles. They may contain abbreviations, but basically never have actual sentence boundaries.", "for", "fin", "in", "input", ":", "click", ".", "echo", "(", "'Training on %s'", "%", "fin", ".", "name", ")", "sentences", "=", "fin", ".", "read", "(", ")", "#.replace('.\\n', '. \\n\\n')", "punkt", ".", "train", "(", "sentences", ",", "finalize", "=", "False", ",", "verbose", "=", "True", ")", "punkt", ".", "finalize_training", "(", "verbose", "=", "True", ")", "if", "abbr", ":", "abbreviations", "=", "abbr", ".", "read", "(", ")", ".", "strip", "(", ")", ".", "split", "(", "'\\n'", ")", "click", ".", "echo", "(", "'Manually adding abbreviations: %s'", "%", "abbreviations", ")", "punkt", ".", "_params", ".", "abbrev_types", ".", "update", "(", "abbreviations", ")", "if", "colloc", ":", "collocations", "=", "[", "tuple", "(", "l", ".", "split", "(", "'. '", ",", "1", ")", ")", "for", "l", "in", "colloc", ".", "read", "(", ")", ".", "strip", "(", ")", ".", "split", "(", "'\\n'", ")", "]", "click", ".", "echo", "(", "'Manually adding collocs: %s'", "%", "collocations", ")", "punkt", ".", "_params", ".", "collocations", ".", "update", "(", "collocations", ")", "model", "=", "PunktSentenceTokenizer", "(", "punkt", ".", "get_params", "(", ")", ")", "pickle", ".", "dump", "(", "model", ",", "output", ",", "protocol", "=", "pickle", ".", "HIGHEST_PROTOCOL", ")" ]
Train Punkt sentence splitter using sentences in input.
[ "Train", "Punkt", "sentence", "splitter", "using", "sentences", "in", "input", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/tokenize.py#L36-L61
train
mcs07/ChemDataExtractor
chemdataextractor/cli/tokenize.py
sentences
def sentences(ctx, input, output): """Read input document, and output sentences.""" log.info('chemdataextractor.read.elements') log.info('Reading %s' % input.name) doc = Document.from_file(input) for element in doc.elements: if isinstance(element, Text): for raw_sentence in element.raw_sentences: output.write(raw_sentence.strip()) output.write(u'\n')
python
def sentences(ctx, input, output): """Read input document, and output sentences.""" log.info('chemdataextractor.read.elements') log.info('Reading %s' % input.name) doc = Document.from_file(input) for element in doc.elements: if isinstance(element, Text): for raw_sentence in element.raw_sentences: output.write(raw_sentence.strip()) output.write(u'\n')
[ "def", "sentences", "(", "ctx", ",", "input", ",", "output", ")", ":", "log", ".", "info", "(", "'chemdataextractor.read.elements'", ")", "log", ".", "info", "(", "'Reading %s'", "%", "input", ".", "name", ")", "doc", "=", "Document", ".", "from_file", "(", "input", ")", "for", "element", "in", "doc", ".", "elements", ":", "if", "isinstance", "(", "element", ",", "Text", ")", ":", "for", "raw_sentence", "in", "element", ".", "raw_sentences", ":", "output", ".", "write", "(", "raw_sentence", ".", "strip", "(", ")", ")", "output", ".", "write", "(", "u'\\n'", ")" ]
Read input document, and output sentences.
[ "Read", "input", "document", "and", "output", "sentences", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/tokenize.py#L68-L77
train
mcs07/ChemDataExtractor
chemdataextractor/cli/tokenize.py
words
def words(ctx, input, output): """Read input document, and output words.""" log.info('chemdataextractor.read.elements') log.info('Reading %s' % input.name) doc = Document.from_file(input) for element in doc.elements: if isinstance(element, Text): for sentence in element.sentences: output.write(u' '.join(sentence.raw_tokens)) output.write(u'\n')
python
def words(ctx, input, output): """Read input document, and output words.""" log.info('chemdataextractor.read.elements') log.info('Reading %s' % input.name) doc = Document.from_file(input) for element in doc.elements: if isinstance(element, Text): for sentence in element.sentences: output.write(u' '.join(sentence.raw_tokens)) output.write(u'\n')
[ "def", "words", "(", "ctx", ",", "input", ",", "output", ")", ":", "log", ".", "info", "(", "'chemdataextractor.read.elements'", ")", "log", ".", "info", "(", "'Reading %s'", "%", "input", ".", "name", ")", "doc", "=", "Document", ".", "from_file", "(", "input", ")", "for", "element", "in", "doc", ".", "elements", ":", "if", "isinstance", "(", "element", ",", "Text", ")", ":", "for", "sentence", "in", "element", ".", "sentences", ":", "output", ".", "write", "(", "u' '", ".", "join", "(", "sentence", ".", "raw_tokens", ")", ")", "output", ".", "write", "(", "u'\\n'", ")" ]
Read input document, and output words.
[ "Read", "input", "document", "and", "output", "words", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/tokenize.py#L84-L93
train
mcs07/ChemDataExtractor
chemdataextractor/nlp/cem.py
CemTagger._in_stoplist
def _in_stoplist(self, entity): """Return True if the entity is in the stoplist.""" start = 0 end = len(entity) # Adjust boundaries to exclude disallowed prefixes/suffixes for prefix in IGNORE_PREFIX: if entity.startswith(prefix): # print('%s removing %s' % (currenttext, prefix)) start += len(prefix) break for suffix in IGNORE_SUFFIX: if entity.endswith(suffix): # print('%s removing %s' % (currenttext, suffix)) end -= len(suffix) break # Return True if entity has been reduced to nothing by adjusting boundaries if start >= end: return True # Return True if adjusted entity is in the literal stoplist entity = entity[start:end] if entity in STOPLIST: return True # log.debug('Entity: %s', entity) for stop_re in STOP_RES: if re.search(stop_re, entity): log.debug('Killed: %s', entity) return True
python
def _in_stoplist(self, entity): """Return True if the entity is in the stoplist.""" start = 0 end = len(entity) # Adjust boundaries to exclude disallowed prefixes/suffixes for prefix in IGNORE_PREFIX: if entity.startswith(prefix): # print('%s removing %s' % (currenttext, prefix)) start += len(prefix) break for suffix in IGNORE_SUFFIX: if entity.endswith(suffix): # print('%s removing %s' % (currenttext, suffix)) end -= len(suffix) break # Return True if entity has been reduced to nothing by adjusting boundaries if start >= end: return True # Return True if adjusted entity is in the literal stoplist entity = entity[start:end] if entity in STOPLIST: return True # log.debug('Entity: %s', entity) for stop_re in STOP_RES: if re.search(stop_re, entity): log.debug('Killed: %s', entity) return True
[ "def", "_in_stoplist", "(", "self", ",", "entity", ")", ":", "start", "=", "0", "end", "=", "len", "(", "entity", ")", "# Adjust boundaries to exclude disallowed prefixes/suffixes", "for", "prefix", "in", "IGNORE_PREFIX", ":", "if", "entity", ".", "startswith", "(", "prefix", ")", ":", "# print('%s removing %s' % (currenttext, prefix))", "start", "+=", "len", "(", "prefix", ")", "break", "for", "suffix", "in", "IGNORE_SUFFIX", ":", "if", "entity", ".", "endswith", "(", "suffix", ")", ":", "# print('%s removing %s' % (currenttext, suffix))", "end", "-=", "len", "(", "suffix", ")", "break", "# Return True if entity has been reduced to nothing by adjusting boundaries", "if", "start", ">=", "end", ":", "return", "True", "# Return True if adjusted entity is in the literal stoplist", "entity", "=", "entity", "[", "start", ":", "end", "]", "if", "entity", "in", "STOPLIST", ":", "return", "True", "# log.debug('Entity: %s', entity)", "for", "stop_re", "in", "STOP_RES", ":", "if", "re", ".", "search", "(", "stop_re", ",", "entity", ")", ":", "log", ".", "debug", "(", "'Killed: %s'", ",", "entity", ")", "return", "True" ]
Return True if the entity is in the stoplist.
[ "Return", "True", "if", "the", "entity", "is", "in", "the", "stoplist", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/cem.py#L518-L544
train
mcs07/ChemDataExtractor
chemdataextractor/cli/dict.py
_process_name
def _process_name(name): """Fix issues with Jochem names.""" # Unescape HTML entities name = unescape(name) # Remove bracketed stuff on the end name = NG_RE.sub('', name).strip() # Nomenclature groups name = END_RE.sub('', name).strip(', ') # Words name = RATIO_RE.sub('', name).strip(', ') # Ratios # Remove stuff off start name = START_RE.sub('', name).strip() # Remove balanced start and end brackets if none in between name = BRACKET_RE.sub('\g<1>', name) # Un-invert CAS style names comps = name.split(', ') if len(comps) == 2: if comps[1].endswith('-'): name = comps[0] name = '%s%s' % (comps[1], name) elif len(comps) > 2: name = comps[0] for i in range(1, len(comps)): if comps[i].endswith('-'): name = '%s%s' % (comps[i], name) else: name = '%s %s' % (name, comps[i]) return name
python
def _process_name(name): """Fix issues with Jochem names.""" # Unescape HTML entities name = unescape(name) # Remove bracketed stuff on the end name = NG_RE.sub('', name).strip() # Nomenclature groups name = END_RE.sub('', name).strip(', ') # Words name = RATIO_RE.sub('', name).strip(', ') # Ratios # Remove stuff off start name = START_RE.sub('', name).strip() # Remove balanced start and end brackets if none in between name = BRACKET_RE.sub('\g<1>', name) # Un-invert CAS style names comps = name.split(', ') if len(comps) == 2: if comps[1].endswith('-'): name = comps[0] name = '%s%s' % (comps[1], name) elif len(comps) > 2: name = comps[0] for i in range(1, len(comps)): if comps[i].endswith('-'): name = '%s%s' % (comps[i], name) else: name = '%s %s' % (name, comps[i]) return name
[ "def", "_process_name", "(", "name", ")", ":", "# Unescape HTML entities", "name", "=", "unescape", "(", "name", ")", "# Remove bracketed stuff on the end", "name", "=", "NG_RE", ".", "sub", "(", "''", ",", "name", ")", ".", "strip", "(", ")", "# Nomenclature groups", "name", "=", "END_RE", ".", "sub", "(", "''", ",", "name", ")", ".", "strip", "(", "', '", ")", "# Words", "name", "=", "RATIO_RE", ".", "sub", "(", "''", ",", "name", ")", ".", "strip", "(", "', '", ")", "# Ratios", "# Remove stuff off start", "name", "=", "START_RE", ".", "sub", "(", "''", ",", "name", ")", ".", "strip", "(", ")", "# Remove balanced start and end brackets if none in between", "name", "=", "BRACKET_RE", ".", "sub", "(", "'\\g<1>'", ",", "name", ")", "# Un-invert CAS style names", "comps", "=", "name", ".", "split", "(", "', '", ")", "if", "len", "(", "comps", ")", "==", "2", ":", "if", "comps", "[", "1", "]", ".", "endswith", "(", "'-'", ")", ":", "name", "=", "comps", "[", "0", "]", "name", "=", "'%s%s'", "%", "(", "comps", "[", "1", "]", ",", "name", ")", "elif", "len", "(", "comps", ")", ">", "2", ":", "name", "=", "comps", "[", "0", "]", "for", "i", "in", "range", "(", "1", ",", "len", "(", "comps", ")", ")", ":", "if", "comps", "[", "i", "]", ".", "endswith", "(", "'-'", ")", ":", "name", "=", "'%s%s'", "%", "(", "comps", "[", "i", "]", ",", "name", ")", "else", ":", "name", "=", "'%s %s'", "%", "(", "name", ",", "comps", "[", "i", "]", ")", "return", "name" ]
Fix issues with Jochem names.
[ "Fix", "issues", "with", "Jochem", "names", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/dict.py#L124-L154
train
mcs07/ChemDataExtractor
chemdataextractor/cli/dict.py
_get_variants
def _get_variants(name): """Return variants of chemical name.""" names = [name] oldname = name # Map greek words to unicode characters if DOT_GREEK_RE.search(name): wordname = name while True: m = DOT_GREEK_RE.search(wordname) if m: wordname = wordname[:m.start(1)-1] + m.group(1) + wordname[m.end(1)+1:] else: break symbolname = name while True: m = DOT_GREEK_RE.search(symbolname) if m: symbolname = symbolname[:m.start(1)-1] + GREEK_WORDS[m.group(1)] + symbolname[m.end(1)+1:] else: break names = [wordname, symbolname] else: while True: m = GREEK_RE.search(name) if m: name = name[:m.start(2)] + GREEK_WORDS[m.group(2)] + name[m.end(2):] else: break while True: m = UNAMBIGUOUS_GREEK_RE.search(name) if m: name = name[:m.start(1)] + GREEK_WORDS[m.group(1)] + name[m.end(1):] else: break if not name == oldname: names.append(name) newnames = [] for name in names: # If last word \d+, add variants with hyphen and no space preceding if NUM_END_RE.search(name): newnames.append(NUM_END_RE.sub('-\g<1>', name)) newnames.append(NUM_END_RE.sub('\g<1>', name)) # If last word [A-Za-z]\d* add variants with hyphen preceding. if ALPHANUM_END_RE.search(name): newnames.append(ALPHANUM_END_RE.sub('-\g<1>', name)) names.extend(newnames) return names
python
def _get_variants(name): """Return variants of chemical name.""" names = [name] oldname = name # Map greek words to unicode characters if DOT_GREEK_RE.search(name): wordname = name while True: m = DOT_GREEK_RE.search(wordname) if m: wordname = wordname[:m.start(1)-1] + m.group(1) + wordname[m.end(1)+1:] else: break symbolname = name while True: m = DOT_GREEK_RE.search(symbolname) if m: symbolname = symbolname[:m.start(1)-1] + GREEK_WORDS[m.group(1)] + symbolname[m.end(1)+1:] else: break names = [wordname, symbolname] else: while True: m = GREEK_RE.search(name) if m: name = name[:m.start(2)] + GREEK_WORDS[m.group(2)] + name[m.end(2):] else: break while True: m = UNAMBIGUOUS_GREEK_RE.search(name) if m: name = name[:m.start(1)] + GREEK_WORDS[m.group(1)] + name[m.end(1):] else: break if not name == oldname: names.append(name) newnames = [] for name in names: # If last word \d+, add variants with hyphen and no space preceding if NUM_END_RE.search(name): newnames.append(NUM_END_RE.sub('-\g<1>', name)) newnames.append(NUM_END_RE.sub('\g<1>', name)) # If last word [A-Za-z]\d* add variants with hyphen preceding. if ALPHANUM_END_RE.search(name): newnames.append(ALPHANUM_END_RE.sub('-\g<1>', name)) names.extend(newnames) return names
[ "def", "_get_variants", "(", "name", ")", ":", "names", "=", "[", "name", "]", "oldname", "=", "name", "# Map greek words to unicode characters", "if", "DOT_GREEK_RE", ".", "search", "(", "name", ")", ":", "wordname", "=", "name", "while", "True", ":", "m", "=", "DOT_GREEK_RE", ".", "search", "(", "wordname", ")", "if", "m", ":", "wordname", "=", "wordname", "[", ":", "m", ".", "start", "(", "1", ")", "-", "1", "]", "+", "m", ".", "group", "(", "1", ")", "+", "wordname", "[", "m", ".", "end", "(", "1", ")", "+", "1", ":", "]", "else", ":", "break", "symbolname", "=", "name", "while", "True", ":", "m", "=", "DOT_GREEK_RE", ".", "search", "(", "symbolname", ")", "if", "m", ":", "symbolname", "=", "symbolname", "[", ":", "m", ".", "start", "(", "1", ")", "-", "1", "]", "+", "GREEK_WORDS", "[", "m", ".", "group", "(", "1", ")", "]", "+", "symbolname", "[", "m", ".", "end", "(", "1", ")", "+", "1", ":", "]", "else", ":", "break", "names", "=", "[", "wordname", ",", "symbolname", "]", "else", ":", "while", "True", ":", "m", "=", "GREEK_RE", ".", "search", "(", "name", ")", "if", "m", ":", "name", "=", "name", "[", ":", "m", ".", "start", "(", "2", ")", "]", "+", "GREEK_WORDS", "[", "m", ".", "group", "(", "2", ")", "]", "+", "name", "[", "m", ".", "end", "(", "2", ")", ":", "]", "else", ":", "break", "while", "True", ":", "m", "=", "UNAMBIGUOUS_GREEK_RE", ".", "search", "(", "name", ")", "if", "m", ":", "name", "=", "name", "[", ":", "m", ".", "start", "(", "1", ")", "]", "+", "GREEK_WORDS", "[", "m", ".", "group", "(", "1", ")", "]", "+", "name", "[", "m", ".", "end", "(", "1", ")", ":", "]", "else", ":", "break", "if", "not", "name", "==", "oldname", ":", "names", ".", "append", "(", "name", ")", "newnames", "=", "[", "]", "for", "name", "in", "names", ":", "# If last word \\d+, add variants with hyphen and no space preceding", "if", "NUM_END_RE", ".", "search", "(", "name", ")", ":", "newnames", ".", "append", "(", "NUM_END_RE", ".", "sub", "(", "'-\\g<1>'", ",", "name", ")", ")", "newnames", ".", "append", "(", "NUM_END_RE", ".", "sub", "(", "'\\g<1>'", ",", "name", ")", ")", "# If last word [A-Za-z]\\d* add variants with hyphen preceding.", "if", "ALPHANUM_END_RE", ".", "search", "(", "name", ")", ":", "newnames", ".", "append", "(", "ALPHANUM_END_RE", ".", "sub", "(", "'-\\g<1>'", ",", "name", ")", ")", "names", ".", "extend", "(", "newnames", ")", "return", "names" ]
Return variants of chemical name.
[ "Return", "variants", "of", "chemical", "name", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/dict.py#L206-L252
train
mcs07/ChemDataExtractor
chemdataextractor/cli/dict.py
prepare_jochem
def prepare_jochem(ctx, jochem, output, csoutput): """Process and filter jochem file to produce list of names for dictionary.""" click.echo('chemdataextractor.dict.prepare_jochem') for i, line in enumerate(jochem): print('JC%s' % i) if line.startswith('TM '): if line.endswith(' @match=ci\n'): for tokens in _make_tokens(line[3:-11]): output.write(' '.join(tokens)) output.write('\n') else: for tokens in _make_tokens(line[3:-1]): csoutput.write(' '.join(tokens)) csoutput.write('\n')
python
def prepare_jochem(ctx, jochem, output, csoutput): """Process and filter jochem file to produce list of names for dictionary.""" click.echo('chemdataextractor.dict.prepare_jochem') for i, line in enumerate(jochem): print('JC%s' % i) if line.startswith('TM '): if line.endswith(' @match=ci\n'): for tokens in _make_tokens(line[3:-11]): output.write(' '.join(tokens)) output.write('\n') else: for tokens in _make_tokens(line[3:-1]): csoutput.write(' '.join(tokens)) csoutput.write('\n')
[ "def", "prepare_jochem", "(", "ctx", ",", "jochem", ",", "output", ",", "csoutput", ")", ":", "click", ".", "echo", "(", "'chemdataextractor.dict.prepare_jochem'", ")", "for", "i", ",", "line", "in", "enumerate", "(", "jochem", ")", ":", "print", "(", "'JC%s'", "%", "i", ")", "if", "line", ".", "startswith", "(", "'TM '", ")", ":", "if", "line", ".", "endswith", "(", "'\t@match=ci\\n'", ")", ":", "for", "tokens", "in", "_make_tokens", "(", "line", "[", "3", ":", "-", "11", "]", ")", ":", "output", ".", "write", "(", "' '", ".", "join", "(", "tokens", ")", ")", "output", ".", "write", "(", "'\\n'", ")", "else", ":", "for", "tokens", "in", "_make_tokens", "(", "line", "[", "3", ":", "-", "1", "]", ")", ":", "csoutput", ".", "write", "(", "' '", ".", "join", "(", "tokens", ")", ")", "csoutput", ".", "write", "(", "'\\n'", ")" ]
Process and filter jochem file to produce list of names for dictionary.
[ "Process", "and", "filter", "jochem", "file", "to", "produce", "list", "of", "names", "for", "dictionary", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/dict.py#L277-L290
train
mcs07/ChemDataExtractor
chemdataextractor/cli/dict.py
prepare_include
def prepare_include(ctx, include, output): """Process and filter include file to produce list of names for dictionary.""" click.echo('chemdataextractor.dict.prepare_include') for i, line in enumerate(include): print('IN%s' % i) for tokens in _make_tokens(line.strip()): output.write(u' '.join(tokens)) output.write(u'\n')
python
def prepare_include(ctx, include, output): """Process and filter include file to produce list of names for dictionary.""" click.echo('chemdataextractor.dict.prepare_include') for i, line in enumerate(include): print('IN%s' % i) for tokens in _make_tokens(line.strip()): output.write(u' '.join(tokens)) output.write(u'\n')
[ "def", "prepare_include", "(", "ctx", ",", "include", ",", "output", ")", ":", "click", ".", "echo", "(", "'chemdataextractor.dict.prepare_include'", ")", "for", "i", ",", "line", "in", "enumerate", "(", "include", ")", ":", "print", "(", "'IN%s'", "%", "i", ")", "for", "tokens", "in", "_make_tokens", "(", "line", ".", "strip", "(", ")", ")", ":", "output", ".", "write", "(", "u' '", ".", "join", "(", "tokens", ")", ")", "output", ".", "write", "(", "u'\\n'", ")" ]
Process and filter include file to produce list of names for dictionary.
[ "Process", "and", "filter", "include", "file", "to", "produce", "list", "of", "names", "for", "dictionary", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/dict.py#L297-L304
train
mcs07/ChemDataExtractor
chemdataextractor/cli/dict.py
build
def build(ctx, inputs, output, cs): """Build chemical name dictionary.""" click.echo('chemdataextractor.dict.build') dt = DictionaryTagger(lexicon=ChemLexicon(), case_sensitive=cs) names = [] for input in inputs: for line in input: tokens = line.split() names.append(tokens) dt.build(words=names) dt.save(output)
python
def build(ctx, inputs, output, cs): """Build chemical name dictionary.""" click.echo('chemdataextractor.dict.build') dt = DictionaryTagger(lexicon=ChemLexicon(), case_sensitive=cs) names = [] for input in inputs: for line in input: tokens = line.split() names.append(tokens) dt.build(words=names) dt.save(output)
[ "def", "build", "(", "ctx", ",", "inputs", ",", "output", ",", "cs", ")", ":", "click", ".", "echo", "(", "'chemdataextractor.dict.build'", ")", "dt", "=", "DictionaryTagger", "(", "lexicon", "=", "ChemLexicon", "(", ")", ",", "case_sensitive", "=", "cs", ")", "names", "=", "[", "]", "for", "input", "in", "inputs", ":", "for", "line", "in", "input", ":", "tokens", "=", "line", ".", "split", "(", ")", "names", ".", "append", "(", "tokens", ")", "dt", ".", "build", "(", "words", "=", "names", ")", "dt", ".", "save", "(", "output", ")" ]
Build chemical name dictionary.
[ "Build", "chemical", "name", "dictionary", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/dict.py#L312-L322
train
mcs07/ChemDataExtractor
chemdataextractor/reader/rsc.py
RscHtmlReader._parse_table_footnotes
def _parse_table_footnotes(self, fns, refs, specials): """Override to account for awkward RSC table footnotes.""" footnotes = [] for fn in fns: footnote = self._parse_text(fn, refs=refs, specials=specials, element_cls=Footnote)[0] footnote += Footnote('', id=fn.getprevious().get('id')) footnotes.append(footnote) return footnotes
python
def _parse_table_footnotes(self, fns, refs, specials): """Override to account for awkward RSC table footnotes.""" footnotes = [] for fn in fns: footnote = self._parse_text(fn, refs=refs, specials=specials, element_cls=Footnote)[0] footnote += Footnote('', id=fn.getprevious().get('id')) footnotes.append(footnote) return footnotes
[ "def", "_parse_table_footnotes", "(", "self", ",", "fns", ",", "refs", ",", "specials", ")", ":", "footnotes", "=", "[", "]", "for", "fn", "in", "fns", ":", "footnote", "=", "self", ".", "_parse_text", "(", "fn", ",", "refs", "=", "refs", ",", "specials", "=", "specials", ",", "element_cls", "=", "Footnote", ")", "[", "0", "]", "footnote", "+=", "Footnote", "(", "''", ",", "id", "=", "fn", ".", "getprevious", "(", ")", ".", "get", "(", "'id'", ")", ")", "footnotes", ".", "append", "(", "footnote", ")", "return", "footnotes" ]
Override to account for awkward RSC table footnotes.
[ "Override", "to", "account", "for", "awkward", "RSC", "table", "footnotes", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/reader/rsc.py#L44-L51
train
mcs07/ChemDataExtractor
scripts/melting_points.py
extract
def extract(): """Extract melting points from patents.""" Paragraph.parsers = [CompoundParser(), ChemicalLabelParser(), MpParser()] Table.parsers = [] patents = [] for root, dirs, files in os.walk('../examples/mp/grants'): for filename in files: if not filename.endswith('.xml'): continue path = os.path.abspath(os.path.join(root, filename)) size = os.path.getsize(path) patents.append((path, filename, size)) patents = sorted(patents, key=lambda p: p[2]) for path, filename, size in patents: print(path) shutil.copyfile(path, '../examples/mp/used/%s' % filename) with open(path) as f: d = Document.from_file(f) if os.path.isfile('../examples/mp/results/%s.json' % filename): continue records = [r.serialize() for r in d.records if len(r.melting_points) == 1] with open('../examples/mp/results/%s.json' % filename, 'w') as fout: fout.write(json.dumps(records, ensure_ascii=False, indent=2).encode('utf8'))
python
def extract(): """Extract melting points from patents.""" Paragraph.parsers = [CompoundParser(), ChemicalLabelParser(), MpParser()] Table.parsers = [] patents = [] for root, dirs, files in os.walk('../examples/mp/grants'): for filename in files: if not filename.endswith('.xml'): continue path = os.path.abspath(os.path.join(root, filename)) size = os.path.getsize(path) patents.append((path, filename, size)) patents = sorted(patents, key=lambda p: p[2]) for path, filename, size in patents: print(path) shutil.copyfile(path, '../examples/mp/used/%s' % filename) with open(path) as f: d = Document.from_file(f) if os.path.isfile('../examples/mp/results/%s.json' % filename): continue records = [r.serialize() for r in d.records if len(r.melting_points) == 1] with open('../examples/mp/results/%s.json' % filename, 'w') as fout: fout.write(json.dumps(records, ensure_ascii=False, indent=2).encode('utf8'))
[ "def", "extract", "(", ")", ":", "Paragraph", ".", "parsers", "=", "[", "CompoundParser", "(", ")", ",", "ChemicalLabelParser", "(", ")", ",", "MpParser", "(", ")", "]", "Table", ".", "parsers", "=", "[", "]", "patents", "=", "[", "]", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "'../examples/mp/grants'", ")", ":", "for", "filename", "in", "files", ":", "if", "not", "filename", ".", "endswith", "(", "'.xml'", ")", ":", "continue", "path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "root", ",", "filename", ")", ")", "size", "=", "os", ".", "path", ".", "getsize", "(", "path", ")", "patents", ".", "append", "(", "(", "path", ",", "filename", ",", "size", ")", ")", "patents", "=", "sorted", "(", "patents", ",", "key", "=", "lambda", "p", ":", "p", "[", "2", "]", ")", "for", "path", ",", "filename", ",", "size", "in", "patents", ":", "print", "(", "path", ")", "shutil", ".", "copyfile", "(", "path", ",", "'../examples/mp/used/%s'", "%", "filename", ")", "with", "open", "(", "path", ")", "as", "f", ":", "d", "=", "Document", ".", "from_file", "(", "f", ")", "if", "os", ".", "path", ".", "isfile", "(", "'../examples/mp/results/%s.json'", "%", "filename", ")", ":", "continue", "records", "=", "[", "r", ".", "serialize", "(", ")", "for", "r", "in", "d", ".", "records", "if", "len", "(", "r", ".", "melting_points", ")", "==", "1", "]", "with", "open", "(", "'../examples/mp/results/%s.json'", "%", "filename", ",", "'w'", ")", "as", "fout", ":", "fout", ".", "write", "(", "json", ".", "dumps", "(", "records", ",", "ensure_ascii", "=", "False", ",", "indent", "=", "2", ")", ".", "encode", "(", "'utf8'", ")", ")" ]
Extract melting points from patents.
[ "Extract", "melting", "points", "from", "patents", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/scripts/melting_points.py#L40-L64
train
mcs07/ChemDataExtractor
scripts/melting_points.py
make_sdf
def make_sdf(): """Produce SDF of ChemDataExtractor and Tetko sample melting points.""" # import numpy as np # my_results_by_inchikey = defaultdict(list) # result_dir = '../examples/mp/standardized_results' # fout = open('../examples/mp/sdf/chemdataextractor-melting-points.sdf', 'w') # writer = Chem.SDWriter(fout) # for filename in os.listdir(result_dir): # if not filename.endswith('.json'): # continue # patent_id = filename[:-5] # with open('%s/%s' % (result_dir, filename)) as fin: # results = json.loads(fin.read().decode('utf8')) # for m in results: # m['patent_id'] = patent_id # mol = Chem.MolFromSmiles(m['smiles']) # mol.SetProp(b'_Name', m['name'].encode('utf-8')) # mol.SetProp(b'OriginalText', m['value'].encode('utf-8')) # mol.SetProp(b'Value', b'%s' % m['float_value']) # mol.SetProp(b'Patent', m['patent_id'].encode('utf-8')) # mol.SetProp(b'SMILES', Chem.MolToSmiles(mol, isomericSmiles=True)) # mol.SetProp(b'QuantityType', b'MeltingPoint') # mol.SetProp(b'StdInChIKey', Chem.InchiToInchiKey(Chem.MolToInchi(mol))) # if not mol: # print('WARNING: %s' % m) # return # AllChem.Compute2DCoords(mol) # writer.write(mol) # my_results_by_inchikey[m['inchikey']].append(m) # writer.close() # fout.close() # # fout = open('../examples/mp/sdf/chemdataextractor-melting-points-filtered.sdf', 'w') # writer = Chem.SDWriter(fout) # for inchikey, results in my_results_by_inchikey.items(): # if len(results) == 1: # m = results[0] # elif len(results) == 2: # sorted_results = sorted(results, key=lambda x: x['float_value']) # m = sorted_results[0] # else: # median = np.median([r['float_value'] for r in results]) # chosen = results[0] # for result in results: # if result['float_value'] - median < chosen['float_value'] < median: # m = result # mol = Chem.MolFromSmiles(m['smiles']) # mol.SetProp(b'_Name', m['name'].encode('utf-8')) # mol.SetProp(b'OriginalText', m['value'].encode('utf-8')) # mol.SetProp(b'Value', b'%s' % m['float_value']) # mol.SetProp(b'Patent', m['patent_id'].encode('utf-8')) # mol.SetProp(b'SMILES', Chem.MolToSmiles(mol, isomericSmiles=True)) # mol.SetProp(b'QuantityType', b'MeltingPoint') # mol.SetProp(b'StdInChIKey', Chem.InchiToInchiKey(Chem.MolToInchi(mol))) # if not mol: # print('WARNING: %s' % m) # return # AllChem.Compute2DCoords(mol) # writer.write(mol) with open('../examples/mp/sdf/chemdataextractor-melting-points.sdf', 'rb') as f_in, gzip.open('../examples/mp/sdf/chemdataextractor-melting-points.sdf.gz', 'wb') as f_out: shutil.copyfileobj(f_in, f_out) with open('../examples/mp/sdf/chemdataextractor-melting-points-filtered.sdf', 'rb') as f_in, gzip.open('../examples/mp/sdf/chemdataextractor-melting-points-filtered.sdf.gz', 'wb') as f_out: shutil.copyfileobj(f_in, f_out)
python
def make_sdf(): """Produce SDF of ChemDataExtractor and Tetko sample melting points.""" # import numpy as np # my_results_by_inchikey = defaultdict(list) # result_dir = '../examples/mp/standardized_results' # fout = open('../examples/mp/sdf/chemdataextractor-melting-points.sdf', 'w') # writer = Chem.SDWriter(fout) # for filename in os.listdir(result_dir): # if not filename.endswith('.json'): # continue # patent_id = filename[:-5] # with open('%s/%s' % (result_dir, filename)) as fin: # results = json.loads(fin.read().decode('utf8')) # for m in results: # m['patent_id'] = patent_id # mol = Chem.MolFromSmiles(m['smiles']) # mol.SetProp(b'_Name', m['name'].encode('utf-8')) # mol.SetProp(b'OriginalText', m['value'].encode('utf-8')) # mol.SetProp(b'Value', b'%s' % m['float_value']) # mol.SetProp(b'Patent', m['patent_id'].encode('utf-8')) # mol.SetProp(b'SMILES', Chem.MolToSmiles(mol, isomericSmiles=True)) # mol.SetProp(b'QuantityType', b'MeltingPoint') # mol.SetProp(b'StdInChIKey', Chem.InchiToInchiKey(Chem.MolToInchi(mol))) # if not mol: # print('WARNING: %s' % m) # return # AllChem.Compute2DCoords(mol) # writer.write(mol) # my_results_by_inchikey[m['inchikey']].append(m) # writer.close() # fout.close() # # fout = open('../examples/mp/sdf/chemdataextractor-melting-points-filtered.sdf', 'w') # writer = Chem.SDWriter(fout) # for inchikey, results in my_results_by_inchikey.items(): # if len(results) == 1: # m = results[0] # elif len(results) == 2: # sorted_results = sorted(results, key=lambda x: x['float_value']) # m = sorted_results[0] # else: # median = np.median([r['float_value'] for r in results]) # chosen = results[0] # for result in results: # if result['float_value'] - median < chosen['float_value'] < median: # m = result # mol = Chem.MolFromSmiles(m['smiles']) # mol.SetProp(b'_Name', m['name'].encode('utf-8')) # mol.SetProp(b'OriginalText', m['value'].encode('utf-8')) # mol.SetProp(b'Value', b'%s' % m['float_value']) # mol.SetProp(b'Patent', m['patent_id'].encode('utf-8')) # mol.SetProp(b'SMILES', Chem.MolToSmiles(mol, isomericSmiles=True)) # mol.SetProp(b'QuantityType', b'MeltingPoint') # mol.SetProp(b'StdInChIKey', Chem.InchiToInchiKey(Chem.MolToInchi(mol))) # if not mol: # print('WARNING: %s' % m) # return # AllChem.Compute2DCoords(mol) # writer.write(mol) with open('../examples/mp/sdf/chemdataextractor-melting-points.sdf', 'rb') as f_in, gzip.open('../examples/mp/sdf/chemdataextractor-melting-points.sdf.gz', 'wb') as f_out: shutil.copyfileobj(f_in, f_out) with open('../examples/mp/sdf/chemdataextractor-melting-points-filtered.sdf', 'rb') as f_in, gzip.open('../examples/mp/sdf/chemdataextractor-melting-points-filtered.sdf.gz', 'wb') as f_out: shutil.copyfileobj(f_in, f_out)
[ "def", "make_sdf", "(", ")", ":", "# import numpy as np", "# my_results_by_inchikey = defaultdict(list)", "# result_dir = '../examples/mp/standardized_results'", "# fout = open('../examples/mp/sdf/chemdataextractor-melting-points.sdf', 'w')", "# writer = Chem.SDWriter(fout)", "# for filename in os.listdir(result_dir):", "# if not filename.endswith('.json'):", "# continue", "# patent_id = filename[:-5]", "# with open('%s/%s' % (result_dir, filename)) as fin:", "# results = json.loads(fin.read().decode('utf8'))", "# for m in results:", "# m['patent_id'] = patent_id", "# mol = Chem.MolFromSmiles(m['smiles'])", "# mol.SetProp(b'_Name', m['name'].encode('utf-8'))", "# mol.SetProp(b'OriginalText', m['value'].encode('utf-8'))", "# mol.SetProp(b'Value', b'%s' % m['float_value'])", "# mol.SetProp(b'Patent', m['patent_id'].encode('utf-8'))", "# mol.SetProp(b'SMILES', Chem.MolToSmiles(mol, isomericSmiles=True))", "# mol.SetProp(b'QuantityType', b'MeltingPoint')", "# mol.SetProp(b'StdInChIKey', Chem.InchiToInchiKey(Chem.MolToInchi(mol)))", "# if not mol:", "# print('WARNING: %s' % m)", "# return", "# AllChem.Compute2DCoords(mol)", "# writer.write(mol)", "# my_results_by_inchikey[m['inchikey']].append(m)", "# writer.close()", "# fout.close()", "#", "# fout = open('../examples/mp/sdf/chemdataextractor-melting-points-filtered.sdf', 'w')", "# writer = Chem.SDWriter(fout)", "# for inchikey, results in my_results_by_inchikey.items():", "# if len(results) == 1:", "# m = results[0]", "# elif len(results) == 2:", "# sorted_results = sorted(results, key=lambda x: x['float_value'])", "# m = sorted_results[0]", "# else:", "# median = np.median([r['float_value'] for r in results])", "# chosen = results[0]", "# for result in results:", "# if result['float_value'] - median < chosen['float_value'] < median:", "# m = result", "# mol = Chem.MolFromSmiles(m['smiles'])", "# mol.SetProp(b'_Name', m['name'].encode('utf-8'))", "# mol.SetProp(b'OriginalText', m['value'].encode('utf-8'))", "# mol.SetProp(b'Value', b'%s' % m['float_value'])", "# mol.SetProp(b'Patent', m['patent_id'].encode('utf-8'))", "# mol.SetProp(b'SMILES', Chem.MolToSmiles(mol, isomericSmiles=True))", "# mol.SetProp(b'QuantityType', b'MeltingPoint')", "# mol.SetProp(b'StdInChIKey', Chem.InchiToInchiKey(Chem.MolToInchi(mol)))", "# if not mol:", "# print('WARNING: %s' % m)", "# return", "# AllChem.Compute2DCoords(mol)", "# writer.write(mol)", "with", "open", "(", "'../examples/mp/sdf/chemdataextractor-melting-points.sdf'", ",", "'rb'", ")", "as", "f_in", ",", "gzip", ".", "open", "(", "'../examples/mp/sdf/chemdataextractor-melting-points.sdf.gz'", ",", "'wb'", ")", "as", "f_out", ":", "shutil", ".", "copyfileobj", "(", "f_in", ",", "f_out", ")", "with", "open", "(", "'../examples/mp/sdf/chemdataextractor-melting-points-filtered.sdf'", ",", "'rb'", ")", "as", "f_in", ",", "gzip", ".", "open", "(", "'../examples/mp/sdf/chemdataextractor-melting-points-filtered.sdf.gz'", ",", "'wb'", ")", "as", "f_out", ":", "shutil", ".", "copyfileobj", "(", "f_in", ",", "f_out", ")" ]
Produce SDF of ChemDataExtractor and Tetko sample melting points.
[ "Produce", "SDF", "of", "ChemDataExtractor", "and", "Tetko", "sample", "melting", "points", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/scripts/melting_points.py#L555-L620
train
mcs07/ChemDataExtractor
chemdataextractor/cli/__init__.py
cli
def cli(ctx, verbose): """ChemDataExtractor command line interface.""" log.debug('ChemDataExtractor v%s' % __version__) logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO) logging.getLogger('requests').setLevel(logging.WARN) ctx.obj = {}
python
def cli(ctx, verbose): """ChemDataExtractor command line interface.""" log.debug('ChemDataExtractor v%s' % __version__) logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO) logging.getLogger('requests').setLevel(logging.WARN) ctx.obj = {}
[ "def", "cli", "(", "ctx", ",", "verbose", ")", ":", "log", ".", "debug", "(", "'ChemDataExtractor v%s'", "%", "__version__", ")", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "DEBUG", "if", "verbose", "else", "logging", ".", "INFO", ")", "logging", ".", "getLogger", "(", "'requests'", ")", ".", "setLevel", "(", "logging", ".", "WARN", ")", "ctx", ".", "obj", "=", "{", "}" ]
ChemDataExtractor command line interface.
[ "ChemDataExtractor", "command", "line", "interface", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/__init__.py#L34-L39
train
mcs07/ChemDataExtractor
chemdataextractor/cli/__init__.py
extract
def extract(ctx, input, output): """Run ChemDataExtractor on a document.""" log.info('chemdataextractor.extract') log.info('Reading %s' % input.name) doc = Document.from_file(input, fname=input.name) records = [record.serialize(primitive=True) for record in doc.records] jsonstring = json.dumps(records, indent=2, ensure_ascii=False) output.write(jsonstring)
python
def extract(ctx, input, output): """Run ChemDataExtractor on a document.""" log.info('chemdataextractor.extract') log.info('Reading %s' % input.name) doc = Document.from_file(input, fname=input.name) records = [record.serialize(primitive=True) for record in doc.records] jsonstring = json.dumps(records, indent=2, ensure_ascii=False) output.write(jsonstring)
[ "def", "extract", "(", "ctx", ",", "input", ",", "output", ")", ":", "log", ".", "info", "(", "'chemdataextractor.extract'", ")", "log", ".", "info", "(", "'Reading %s'", "%", "input", ".", "name", ")", "doc", "=", "Document", ".", "from_file", "(", "input", ",", "fname", "=", "input", ".", "name", ")", "records", "=", "[", "record", ".", "serialize", "(", "primitive", "=", "True", ")", "for", "record", "in", "doc", ".", "records", "]", "jsonstring", "=", "json", ".", "dumps", "(", "records", ",", "indent", "=", "2", ",", "ensure_ascii", "=", "False", ")", "output", ".", "write", "(", "jsonstring", ")" ]
Run ChemDataExtractor on a document.
[ "Run", "ChemDataExtractor", "on", "a", "document", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/__init__.py#L46-L53
train
mcs07/ChemDataExtractor
chemdataextractor/cli/__init__.py
read
def read(ctx, input, output): """Output processed document elements.""" log.info('chemdataextractor.read') log.info('Reading %s' % input.name) doc = Document.from_file(input) for element in doc.elements: output.write(u'%s : %s\n=====\n' % (element.__class__.__name__, six.text_type(element)))
python
def read(ctx, input, output): """Output processed document elements.""" log.info('chemdataextractor.read') log.info('Reading %s' % input.name) doc = Document.from_file(input) for element in doc.elements: output.write(u'%s : %s\n=====\n' % (element.__class__.__name__, six.text_type(element)))
[ "def", "read", "(", "ctx", ",", "input", ",", "output", ")", ":", "log", ".", "info", "(", "'chemdataextractor.read'", ")", "log", ".", "info", "(", "'Reading %s'", "%", "input", ".", "name", ")", "doc", "=", "Document", ".", "from_file", "(", "input", ")", "for", "element", "in", "doc", ".", "elements", ":", "output", ".", "write", "(", "u'%s : %s\\n=====\\n'", "%", "(", "element", ".", "__class__", ".", "__name__", ",", "six", ".", "text_type", "(", "element", ")", ")", ")" ]
Output processed document elements.
[ "Output", "processed", "document", "elements", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/__init__.py#L60-L66
train
mcs07/ChemDataExtractor
chemdataextractor/text/chem.py
extract_smiles
def extract_smiles(s): """Return a list of SMILES identifiers extracted from the string.""" # TODO: This still gets a lot of false positives. smiles = [] for t in s.split(): if len(t) > 2 and SMILES_RE.match(t) and not t.endswith('.') and bracket_level(t) == 0: smiles.append(t) return smiles
python
def extract_smiles(s): """Return a list of SMILES identifiers extracted from the string.""" # TODO: This still gets a lot of false positives. smiles = [] for t in s.split(): if len(t) > 2 and SMILES_RE.match(t) and not t.endswith('.') and bracket_level(t) == 0: smiles.append(t) return smiles
[ "def", "extract_smiles", "(", "s", ")", ":", "# TODO: This still gets a lot of false positives.", "smiles", "=", "[", "]", "for", "t", "in", "s", ".", "split", "(", ")", ":", "if", "len", "(", "t", ")", ">", "2", "and", "SMILES_RE", ".", "match", "(", "t", ")", "and", "not", "t", ".", "endswith", "(", "'.'", ")", "and", "bracket_level", "(", "t", ")", "==", "0", ":", "smiles", ".", "append", "(", "t", ")", "return", "smiles" ]
Return a list of SMILES identifiers extracted from the string.
[ "Return", "a", "list", "of", "SMILES", "identifiers", "extracted", "from", "the", "string", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/text/chem.py#L155-L162
train
mcs07/ChemDataExtractor
chemdataextractor/biblio/person.py
PersonName.could_be
def could_be(self, other): """Return True if the other PersonName is not explicitly inconsistent.""" # TODO: Some suffix and title differences should be allowed if type(other) is not type(self): return NotImplemented if self == other: return True for attr in ['title', 'firstname', 'middlename', 'nickname', 'prefix', 'lastname', 'suffix']: if attr not in self or attr not in other: continue puncmap = dict((ord(char), None) for char in string.punctuation) s = self[attr].lower().translate(puncmap) o = other[attr].lower().translate(puncmap) if s == o: continue if attr in {'firstname', 'middlename', 'lastname'}: if (({len(comp) for comp in s.split()} == {1} and [el[0] for el in o.split()] == s.split()) or ({len(comp) for comp in o.split()} == {1} and [el[0] for el in s.split()] == o.split())): continue return False return True
python
def could_be(self, other): """Return True if the other PersonName is not explicitly inconsistent.""" # TODO: Some suffix and title differences should be allowed if type(other) is not type(self): return NotImplemented if self == other: return True for attr in ['title', 'firstname', 'middlename', 'nickname', 'prefix', 'lastname', 'suffix']: if attr not in self or attr not in other: continue puncmap = dict((ord(char), None) for char in string.punctuation) s = self[attr].lower().translate(puncmap) o = other[attr].lower().translate(puncmap) if s == o: continue if attr in {'firstname', 'middlename', 'lastname'}: if (({len(comp) for comp in s.split()} == {1} and [el[0] for el in o.split()] == s.split()) or ({len(comp) for comp in o.split()} == {1} and [el[0] for el in s.split()] == o.split())): continue return False return True
[ "def", "could_be", "(", "self", ",", "other", ")", ":", "# TODO: Some suffix and title differences should be allowed", "if", "type", "(", "other", ")", "is", "not", "type", "(", "self", ")", ":", "return", "NotImplemented", "if", "self", "==", "other", ":", "return", "True", "for", "attr", "in", "[", "'title'", ",", "'firstname'", ",", "'middlename'", ",", "'nickname'", ",", "'prefix'", ",", "'lastname'", ",", "'suffix'", "]", ":", "if", "attr", "not", "in", "self", "or", "attr", "not", "in", "other", ":", "continue", "puncmap", "=", "dict", "(", "(", "ord", "(", "char", ")", ",", "None", ")", "for", "char", "in", "string", ".", "punctuation", ")", "s", "=", "self", "[", "attr", "]", ".", "lower", "(", ")", ".", "translate", "(", "puncmap", ")", "o", "=", "other", "[", "attr", "]", ".", "lower", "(", ")", ".", "translate", "(", "puncmap", ")", "if", "s", "==", "o", ":", "continue", "if", "attr", "in", "{", "'firstname'", ",", "'middlename'", ",", "'lastname'", "}", ":", "if", "(", "(", "{", "len", "(", "comp", ")", "for", "comp", "in", "s", ".", "split", "(", ")", "}", "==", "{", "1", "}", "and", "[", "el", "[", "0", "]", "for", "el", "in", "o", ".", "split", "(", ")", "]", "==", "s", ".", "split", "(", ")", ")", "or", "(", "{", "len", "(", "comp", ")", "for", "comp", "in", "o", ".", "split", "(", ")", "}", "==", "{", "1", "}", "and", "[", "el", "[", "0", "]", "for", "el", "in", "s", ".", "split", "(", ")", "]", "==", "o", ".", "split", "(", ")", ")", ")", ":", "continue", "return", "False", "return", "True" ]
Return True if the other PersonName is not explicitly inconsistent.
[ "Return", "True", "if", "the", "other", "PersonName", "is", "not", "explicitly", "inconsistent", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/person.py#L125-L145
train
mcs07/ChemDataExtractor
chemdataextractor/biblio/person.py
PersonName._is_suffix
def _is_suffix(self, t): """Return true if t is a suffix.""" return t not in NOT_SUFFIX and (t.replace('.', '') in SUFFIXES or t.replace('.', '') in SUFFIXES_LOWER)
python
def _is_suffix(self, t): """Return true if t is a suffix.""" return t not in NOT_SUFFIX and (t.replace('.', '') in SUFFIXES or t.replace('.', '') in SUFFIXES_LOWER)
[ "def", "_is_suffix", "(", "self", ",", "t", ")", ":", "return", "t", "not", "in", "NOT_SUFFIX", "and", "(", "t", ".", "replace", "(", "'.'", ",", "''", ")", "in", "SUFFIXES", "or", "t", ".", "replace", "(", "'.'", ",", "''", ")", "in", "SUFFIXES_LOWER", ")" ]
Return true if t is a suffix.
[ "Return", "true", "if", "t", "is", "a", "suffix", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/person.py#L170-L172
train
mcs07/ChemDataExtractor
chemdataextractor/biblio/person.py
PersonName._tokenize
def _tokenize(self, comps): """Split name on spaces, unless inside curly brackets or quotes.""" ps = [] for comp in comps: ps.extend([c.strip(' ,') for c in re.split(r'\s+(?=[^{}]*(?:\{|$))', comp)]) return [p for p in ps if p]
python
def _tokenize(self, comps): """Split name on spaces, unless inside curly brackets or quotes.""" ps = [] for comp in comps: ps.extend([c.strip(' ,') for c in re.split(r'\s+(?=[^{}]*(?:\{|$))', comp)]) return [p for p in ps if p]
[ "def", "_tokenize", "(", "self", ",", "comps", ")", ":", "ps", "=", "[", "]", "for", "comp", "in", "comps", ":", "ps", ".", "extend", "(", "[", "c", ".", "strip", "(", "' ,'", ")", "for", "c", "in", "re", ".", "split", "(", "r'\\s+(?=[^{}]*(?:\\{|$))'", ",", "comp", ")", "]", ")", "return", "[", "p", "for", "p", "in", "ps", "if", "p", "]" ]
Split name on spaces, unless inside curly brackets or quotes.
[ "Split", "name", "on", "spaces", "unless", "inside", "curly", "brackets", "or", "quotes", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/person.py#L174-L179
train
mcs07/ChemDataExtractor
chemdataextractor/biblio/person.py
PersonName._clean
def _clean(self, t, capitalize=None): """Convert to normalized unicode and strip trailing full stops.""" if self._from_bibtex: t = latex_to_unicode(t, capitalize=capitalize) t = ' '.join([el.rstrip('.') if el.count('.') == 1 else el for el in t.split()]) return t
python
def _clean(self, t, capitalize=None): """Convert to normalized unicode and strip trailing full stops.""" if self._from_bibtex: t = latex_to_unicode(t, capitalize=capitalize) t = ' '.join([el.rstrip('.') if el.count('.') == 1 else el for el in t.split()]) return t
[ "def", "_clean", "(", "self", ",", "t", ",", "capitalize", "=", "None", ")", ":", "if", "self", ".", "_from_bibtex", ":", "t", "=", "latex_to_unicode", "(", "t", ",", "capitalize", "=", "capitalize", ")", "t", "=", "' '", ".", "join", "(", "[", "el", ".", "rstrip", "(", "'.'", ")", "if", "el", ".", "count", "(", "'.'", ")", "==", "1", "else", "el", "for", "el", "in", "t", ".", "split", "(", ")", "]", ")", "return", "t" ]
Convert to normalized unicode and strip trailing full stops.
[ "Convert", "to", "normalized", "unicode", "and", "strip", "trailing", "full", "stops", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/person.py#L181-L186
train
mcs07/ChemDataExtractor
chemdataextractor/biblio/person.py
PersonName._strip
def _strip(self, tokens, criteria, prop, rev=False): """Strip off contiguous tokens from the start or end of the list that meet the criteria.""" num = len(tokens) res = [] for i, token in enumerate(reversed(tokens) if rev else tokens): if criteria(token) and num > i + 1: res.insert(0, tokens.pop()) if rev else res.append(tokens.pop(0)) else: break if res: self[prop] = self._clean(' '.join(res)) return tokens
python
def _strip(self, tokens, criteria, prop, rev=False): """Strip off contiguous tokens from the start or end of the list that meet the criteria.""" num = len(tokens) res = [] for i, token in enumerate(reversed(tokens) if rev else tokens): if criteria(token) and num > i + 1: res.insert(0, tokens.pop()) if rev else res.append(tokens.pop(0)) else: break if res: self[prop] = self._clean(' '.join(res)) return tokens
[ "def", "_strip", "(", "self", ",", "tokens", ",", "criteria", ",", "prop", ",", "rev", "=", "False", ")", ":", "num", "=", "len", "(", "tokens", ")", "res", "=", "[", "]", "for", "i", ",", "token", "in", "enumerate", "(", "reversed", "(", "tokens", ")", "if", "rev", "else", "tokens", ")", ":", "if", "criteria", "(", "token", ")", "and", "num", ">", "i", "+", "1", ":", "res", ".", "insert", "(", "0", ",", "tokens", ".", "pop", "(", ")", ")", "if", "rev", "else", "res", ".", "append", "(", "tokens", ".", "pop", "(", "0", ")", ")", "else", ":", "break", "if", "res", ":", "self", "[", "prop", "]", "=", "self", ".", "_clean", "(", "' '", ".", "join", "(", "res", ")", ")", "return", "tokens" ]
Strip off contiguous tokens from the start or end of the list that meet the criteria.
[ "Strip", "off", "contiguous", "tokens", "from", "the", "start", "or", "end", "of", "the", "list", "that", "meet", "the", "criteria", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/person.py#L188-L199
train
mcs07/ChemDataExtractor
chemdataextractor/reader/markup.py
LxmlReader._parse_text
def _parse_text(self, el, refs=None, specials=None, element_cls=Paragraph): """Like _parse_element but ensure a single element.""" if specials is None: specials = {} if refs is None: refs = {} elements = self._parse_element_r(el, specials=specials, refs=refs, element_cls=element_cls) # This occurs if the input element is self-closing... (some table td in NLM XML) if not elements: return [element_cls('')] element = elements[0] for next_element in elements[1:]: element += element_cls(' ') + next_element return [element]
python
def _parse_text(self, el, refs=None, specials=None, element_cls=Paragraph): """Like _parse_element but ensure a single element.""" if specials is None: specials = {} if refs is None: refs = {} elements = self._parse_element_r(el, specials=specials, refs=refs, element_cls=element_cls) # This occurs if the input element is self-closing... (some table td in NLM XML) if not elements: return [element_cls('')] element = elements[0] for next_element in elements[1:]: element += element_cls(' ') + next_element return [element]
[ "def", "_parse_text", "(", "self", ",", "el", ",", "refs", "=", "None", ",", "specials", "=", "None", ",", "element_cls", "=", "Paragraph", ")", ":", "if", "specials", "is", "None", ":", "specials", "=", "{", "}", "if", "refs", "is", "None", ":", "refs", "=", "{", "}", "elements", "=", "self", ".", "_parse_element_r", "(", "el", ",", "specials", "=", "specials", ",", "refs", "=", "refs", ",", "element_cls", "=", "element_cls", ")", "# This occurs if the input element is self-closing... (some table td in NLM XML)", "if", "not", "elements", ":", "return", "[", "element_cls", "(", "''", ")", "]", "element", "=", "elements", "[", "0", "]", "for", "next_element", "in", "elements", "[", "1", ":", "]", ":", "element", "+=", "element_cls", "(", "' '", ")", "+", "next_element", "return", "[", "element", "]" ]
Like _parse_element but ensure a single element.
[ "Like", "_parse_element", "but", "ensure", "a", "single", "element", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/reader/markup.py#L112-L125
train
mcs07/ChemDataExtractor
chemdataextractor/reader/markup.py
LxmlReader._parse_reference
def _parse_reference(self, el): """Return reference ID from href or text content.""" if '#' in el.get('href', ''): return [el.get('href').split('#', 1)[1]] elif 'rid' in el.attrib: return [el.attrib['rid']] elif 'idref' in el.attrib: return [el.attrib['idref']] else: return [''.join(el.itertext()).strip()]
python
def _parse_reference(self, el): """Return reference ID from href or text content.""" if '#' in el.get('href', ''): return [el.get('href').split('#', 1)[1]] elif 'rid' in el.attrib: return [el.attrib['rid']] elif 'idref' in el.attrib: return [el.attrib['idref']] else: return [''.join(el.itertext()).strip()]
[ "def", "_parse_reference", "(", "self", ",", "el", ")", ":", "if", "'#'", "in", "el", ".", "get", "(", "'href'", ",", "''", ")", ":", "return", "[", "el", ".", "get", "(", "'href'", ")", ".", "split", "(", "'#'", ",", "1", ")", "[", "1", "]", "]", "elif", "'rid'", "in", "el", ".", "attrib", ":", "return", "[", "el", ".", "attrib", "[", "'rid'", "]", "]", "elif", "'idref'", "in", "el", ".", "attrib", ":", "return", "[", "el", ".", "attrib", "[", "'idref'", "]", "]", "else", ":", "return", "[", "''", ".", "join", "(", "el", ".", "itertext", "(", ")", ")", ".", "strip", "(", ")", "]" ]
Return reference ID from href or text content.
[ "Return", "reference", "ID", "from", "href", "or", "text", "content", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/reader/markup.py#L163-L172
train
mcs07/ChemDataExtractor
chemdataextractor/reader/markup.py
LxmlReader._is_inline
def _is_inline(self, element): """Return True if an element is inline.""" if element.tag not in {etree.Comment, etree.ProcessingInstruction} and element.tag.lower() in self.inline_elements: return True return False
python
def _is_inline(self, element): """Return True if an element is inline.""" if element.tag not in {etree.Comment, etree.ProcessingInstruction} and element.tag.lower() in self.inline_elements: return True return False
[ "def", "_is_inline", "(", "self", ",", "element", ")", ":", "if", "element", ".", "tag", "not", "in", "{", "etree", ".", "Comment", ",", "etree", ".", "ProcessingInstruction", "}", "and", "element", ".", "tag", ".", "lower", "(", ")", "in", "self", ".", "inline_elements", ":", "return", "True", "return", "False" ]
Return True if an element is inline.
[ "Return", "True", "if", "an", "element", "is", "inline", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/reader/markup.py#L193-L197
train
mcs07/ChemDataExtractor
chemdataextractor/biblio/bibtex.py
BibtexParser._next_token
def _next_token(self, skipws=True): """Increment _token to the next token and return it.""" self._token = next(self._tokens).group(0) return self._next_token() if skipws and self._token.isspace() else self._token
python
def _next_token(self, skipws=True): """Increment _token to the next token and return it.""" self._token = next(self._tokens).group(0) return self._next_token() if skipws and self._token.isspace() else self._token
[ "def", "_next_token", "(", "self", ",", "skipws", "=", "True", ")", ":", "self", ".", "_token", "=", "next", "(", "self", ".", "_tokens", ")", ".", "group", "(", "0", ")", "return", "self", ".", "_next_token", "(", ")", "if", "skipws", "and", "self", ".", "_token", ".", "isspace", "(", ")", "else", "self", ".", "_token" ]
Increment _token to the next token and return it.
[ "Increment", "_token", "to", "the", "next", "token", "and", "return", "it", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/bibtex.py#L65-L68
train
mcs07/ChemDataExtractor
chemdataextractor/biblio/bibtex.py
BibtexParser._parse_entry
def _parse_entry(self): """Parse an entry.""" entry_type = self._next_token().lower() if entry_type == 'string': self._parse_string() elif entry_type not in ['comment', 'preamble']: self._parse_record(entry_type)
python
def _parse_entry(self): """Parse an entry.""" entry_type = self._next_token().lower() if entry_type == 'string': self._parse_string() elif entry_type not in ['comment', 'preamble']: self._parse_record(entry_type)
[ "def", "_parse_entry", "(", "self", ")", ":", "entry_type", "=", "self", ".", "_next_token", "(", ")", ".", "lower", "(", ")", "if", "entry_type", "==", "'string'", ":", "self", ".", "_parse_string", "(", ")", "elif", "entry_type", "not", "in", "[", "'comment'", ",", "'preamble'", "]", ":", "self", ".", "_parse_record", "(", "entry_type", ")" ]
Parse an entry.
[ "Parse", "an", "entry", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/bibtex.py#L80-L86
train
mcs07/ChemDataExtractor
chemdataextractor/biblio/bibtex.py
BibtexParser._parse_string
def _parse_string(self): """Parse a string entry and store the definition.""" if self._next_token() in ['{', '(']: field = self._parse_field() if field: self.definitions[field[0]] = field[1]
python
def _parse_string(self): """Parse a string entry and store the definition.""" if self._next_token() in ['{', '(']: field = self._parse_field() if field: self.definitions[field[0]] = field[1]
[ "def", "_parse_string", "(", "self", ")", ":", "if", "self", ".", "_next_token", "(", ")", "in", "[", "'{'", ",", "'('", "]", ":", "field", "=", "self", ".", "_parse_field", "(", ")", "if", "field", ":", "self", ".", "definitions", "[", "field", "[", "0", "]", "]", "=", "field", "[", "1", "]" ]
Parse a string entry and store the definition.
[ "Parse", "a", "string", "entry", "and", "store", "the", "definition", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/bibtex.py#L88-L93
train
mcs07/ChemDataExtractor
chemdataextractor/biblio/bibtex.py
BibtexParser._parse_record
def _parse_record(self, record_type): """Parse a record.""" if self._next_token() in ['{', '(']: key = self._next_token() self.records[key] = { u'id': key, u'type': record_type.lower() } if self._next_token() == ',': while True: field = self._parse_field() if field: k, v = field[0], field[1] if k in self.keynorms: k = self.keynorms[k] if k == 'pages': v = v.replace(' ', '').replace('--', '-') if k == 'author' or k == 'editor': v = self.parse_names(v) # Recapitalizing the title generally causes more problems than it solves # elif k == 'title': # v = latex_to_unicode(v, capitalize='title') else: v = latex_to_unicode(v) self.records[key][k] = v if self._token != ',': break
python
def _parse_record(self, record_type): """Parse a record.""" if self._next_token() in ['{', '(']: key = self._next_token() self.records[key] = { u'id': key, u'type': record_type.lower() } if self._next_token() == ',': while True: field = self._parse_field() if field: k, v = field[0], field[1] if k in self.keynorms: k = self.keynorms[k] if k == 'pages': v = v.replace(' ', '').replace('--', '-') if k == 'author' or k == 'editor': v = self.parse_names(v) # Recapitalizing the title generally causes more problems than it solves # elif k == 'title': # v = latex_to_unicode(v, capitalize='title') else: v = latex_to_unicode(v) self.records[key][k] = v if self._token != ',': break
[ "def", "_parse_record", "(", "self", ",", "record_type", ")", ":", "if", "self", ".", "_next_token", "(", ")", "in", "[", "'{'", ",", "'('", "]", ":", "key", "=", "self", ".", "_next_token", "(", ")", "self", ".", "records", "[", "key", "]", "=", "{", "u'id'", ":", "key", ",", "u'type'", ":", "record_type", ".", "lower", "(", ")", "}", "if", "self", ".", "_next_token", "(", ")", "==", "','", ":", "while", "True", ":", "field", "=", "self", ".", "_parse_field", "(", ")", "if", "field", ":", "k", ",", "v", "=", "field", "[", "0", "]", ",", "field", "[", "1", "]", "if", "k", "in", "self", ".", "keynorms", ":", "k", "=", "self", ".", "keynorms", "[", "k", "]", "if", "k", "==", "'pages'", ":", "v", "=", "v", ".", "replace", "(", "' '", ",", "''", ")", ".", "replace", "(", "'--'", ",", "'-'", ")", "if", "k", "==", "'author'", "or", "k", "==", "'editor'", ":", "v", "=", "self", ".", "parse_names", "(", "v", ")", "# Recapitalizing the title generally causes more problems than it solves", "# elif k == 'title':", "# v = latex_to_unicode(v, capitalize='title')", "else", ":", "v", "=", "latex_to_unicode", "(", "v", ")", "self", ".", "records", "[", "key", "]", "[", "k", "]", "=", "v", "if", "self", ".", "_token", "!=", "','", ":", "break" ]
Parse a record.
[ "Parse", "a", "record", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/bibtex.py#L95-L121
train
mcs07/ChemDataExtractor
chemdataextractor/biblio/bibtex.py
BibtexParser._parse_field
def _parse_field(self): """Parse a Field.""" name = self._next_token() if self._next_token() == '=': value = self._parse_value() return name, value
python
def _parse_field(self): """Parse a Field.""" name = self._next_token() if self._next_token() == '=': value = self._parse_value() return name, value
[ "def", "_parse_field", "(", "self", ")", ":", "name", "=", "self", ".", "_next_token", "(", ")", "if", "self", ".", "_next_token", "(", ")", "==", "'='", ":", "value", "=", "self", ".", "_parse_value", "(", ")", "return", "name", ",", "value" ]
Parse a Field.
[ "Parse", "a", "Field", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/bibtex.py#L123-L128
train
mcs07/ChemDataExtractor
chemdataextractor/biblio/bibtex.py
BibtexParser._parse_value
def _parse_value(self): """Parse a value. Digits, definitions, and the contents of double quotes or curly brackets.""" val = [] while True: t = self._next_token() if t == '"': brac_counter = 0 while True: t = self._next_token(skipws=False) if t == '{': brac_counter += 1 if t == '}': brac_counter -= 1 if t == '"' and brac_counter <= 0: break else: val.append(t) elif t == '{': brac_counter = 0 while True: t = self._next_token(skipws=False) if t == '{': brac_counter += 1 if t == '}': brac_counter -= 1 if brac_counter < 0: break else: val.append(t) elif re.match(r'\w', t): val.extend([self.definitions.get(t, t), ' ']) elif t.isdigit(): val.append([t, ' ']) elif t == '#': pass else: break value = ' '.join(''.join(val).split()) return value
python
def _parse_value(self): """Parse a value. Digits, definitions, and the contents of double quotes or curly brackets.""" val = [] while True: t = self._next_token() if t == '"': brac_counter = 0 while True: t = self._next_token(skipws=False) if t == '{': brac_counter += 1 if t == '}': brac_counter -= 1 if t == '"' and brac_counter <= 0: break else: val.append(t) elif t == '{': brac_counter = 0 while True: t = self._next_token(skipws=False) if t == '{': brac_counter += 1 if t == '}': brac_counter -= 1 if brac_counter < 0: break else: val.append(t) elif re.match(r'\w', t): val.extend([self.definitions.get(t, t), ' ']) elif t.isdigit(): val.append([t, ' ']) elif t == '#': pass else: break value = ' '.join(''.join(val).split()) return value
[ "def", "_parse_value", "(", "self", ")", ":", "val", "=", "[", "]", "while", "True", ":", "t", "=", "self", ".", "_next_token", "(", ")", "if", "t", "==", "'\"'", ":", "brac_counter", "=", "0", "while", "True", ":", "t", "=", "self", ".", "_next_token", "(", "skipws", "=", "False", ")", "if", "t", "==", "'{'", ":", "brac_counter", "+=", "1", "if", "t", "==", "'}'", ":", "brac_counter", "-=", "1", "if", "t", "==", "'\"'", "and", "brac_counter", "<=", "0", ":", "break", "else", ":", "val", ".", "append", "(", "t", ")", "elif", "t", "==", "'{'", ":", "brac_counter", "=", "0", "while", "True", ":", "t", "=", "self", ".", "_next_token", "(", "skipws", "=", "False", ")", "if", "t", "==", "'{'", ":", "brac_counter", "+=", "1", "if", "t", "==", "'}'", ":", "brac_counter", "-=", "1", "if", "brac_counter", "<", "0", ":", "break", "else", ":", "val", ".", "append", "(", "t", ")", "elif", "re", ".", "match", "(", "r'\\w'", ",", "t", ")", ":", "val", ".", "extend", "(", "[", "self", ".", "definitions", ".", "get", "(", "t", ",", "t", ")", ",", "' '", "]", ")", "elif", "t", ".", "isdigit", "(", ")", ":", "val", ".", "append", "(", "[", "t", ",", "' '", "]", ")", "elif", "t", "==", "'#'", ":", "pass", "else", ":", "break", "value", "=", "' '", ".", "join", "(", "''", ".", "join", "(", "val", ")", ".", "split", "(", ")", ")", "return", "value" ]
Parse a value. Digits, definitions, and the contents of double quotes or curly brackets.
[ "Parse", "a", "value", ".", "Digits", "definitions", "and", "the", "contents", "of", "double", "quotes", "or", "curly", "brackets", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/bibtex.py#L130-L169
train
mcs07/ChemDataExtractor
chemdataextractor/biblio/bibtex.py
BibtexParser.parse_names
def parse_names(cls, names): """Parse a string of names separated by "and" like in a BibTeX authors field.""" names = [latex_to_unicode(n) for n in re.split(r'\sand\s(?=[^{}]*(?:\{|$))', names) if n] return names
python
def parse_names(cls, names): """Parse a string of names separated by "and" like in a BibTeX authors field.""" names = [latex_to_unicode(n) for n in re.split(r'\sand\s(?=[^{}]*(?:\{|$))', names) if n] return names
[ "def", "parse_names", "(", "cls", ",", "names", ")", ":", "names", "=", "[", "latex_to_unicode", "(", "n", ")", "for", "n", "in", "re", ".", "split", "(", "r'\\sand\\s(?=[^{}]*(?:\\{|$))'", ",", "names", ")", "if", "n", "]", "return", "names" ]
Parse a string of names separated by "and" like in a BibTeX authors field.
[ "Parse", "a", "string", "of", "names", "separated", "by", "and", "like", "in", "a", "BibTeX", "authors", "field", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/bibtex.py#L172-L175
train
mcs07/ChemDataExtractor
chemdataextractor/biblio/bibtex.py
BibtexParser.metadata
def metadata(self): """Return metadata for the parsed collection of records.""" auto = {u'records': self.size} auto.update(self.meta) return auto
python
def metadata(self): """Return metadata for the parsed collection of records.""" auto = {u'records': self.size} auto.update(self.meta) return auto
[ "def", "metadata", "(", "self", ")", ":", "auto", "=", "{", "u'records'", ":", "self", ".", "size", "}", "auto", ".", "update", "(", "self", ".", "meta", ")", "return", "auto" ]
Return metadata for the parsed collection of records.
[ "Return", "metadata", "for", "the", "parsed", "collection", "of", "records", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/bibtex.py#L188-L192
train
mcs07/ChemDataExtractor
chemdataextractor/biblio/bibtex.py
BibtexParser.json
def json(self): """Return a list of records as a JSON string. Follows the BibJSON convention.""" return json.dumps(OrderedDict([('metadata', self.metadata), ('records', self.records.values())]))
python
def json(self): """Return a list of records as a JSON string. Follows the BibJSON convention.""" return json.dumps(OrderedDict([('metadata', self.metadata), ('records', self.records.values())]))
[ "def", "json", "(", "self", ")", ":", "return", "json", ".", "dumps", "(", "OrderedDict", "(", "[", "(", "'metadata'", ",", "self", ".", "metadata", ")", ",", "(", "'records'", ",", "self", ".", "records", ".", "values", "(", ")", ")", "]", ")", ")" ]
Return a list of records as a JSON string. Follows the BibJSON convention.
[ "Return", "a", "list", "of", "records", "as", "a", "JSON", "string", ".", "Follows", "the", "BibJSON", "convention", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/bibtex.py#L195-L197
train
mcs07/ChemDataExtractor
chemdataextractor/config.py
Config._flush
def _flush(self): """Save the contents of data to the file on disk. You should not need to call this manually.""" d = os.path.dirname(self.path) if not os.path.isdir(d): os.makedirs(d) with io.open(self.path, 'w', encoding='utf8') as f: yaml.safe_dump(self._data, f, default_flow_style=False, encoding=None)
python
def _flush(self): """Save the contents of data to the file on disk. You should not need to call this manually.""" d = os.path.dirname(self.path) if not os.path.isdir(d): os.makedirs(d) with io.open(self.path, 'w', encoding='utf8') as f: yaml.safe_dump(self._data, f, default_flow_style=False, encoding=None)
[ "def", "_flush", "(", "self", ")", ":", "d", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "path", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "d", ")", ":", "os", ".", "makedirs", "(", "d", ")", "with", "io", ".", "open", "(", "self", ".", "path", ",", "'w'", ",", "encoding", "=", "'utf8'", ")", "as", "f", ":", "yaml", ".", "safe_dump", "(", "self", ".", "_data", ",", "f", ",", "default_flow_style", "=", "False", ",", "encoding", "=", "None", ")" ]
Save the contents of data to the file on disk. You should not need to call this manually.
[ "Save", "the", "contents", "of", "data", "to", "the", "file", "on", "disk", ".", "You", "should", "not", "need", "to", "call", "this", "manually", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/config.py#L79-L85
train
mcs07/ChemDataExtractor
chemdataextractor/nlp/abbrev.py
AbbreviationDetector._is_allowed_abbr
def _is_allowed_abbr(self, tokens): """Return True if text is an allowed abbreviation.""" if len(tokens) <= 2: abbr_text = ''.join(tokens) if self.abbr_min <= len(abbr_text) <= self.abbr_max and bracket_level(abbr_text) == 0: if abbr_text[0].isalnum() and any(c.isalpha() for c in abbr_text): # Disallow property values if re.match('^\d+(\.\d+)?(g|m[lL]|cm)$', abbr_text): return False return True return False
python
def _is_allowed_abbr(self, tokens): """Return True if text is an allowed abbreviation.""" if len(tokens) <= 2: abbr_text = ''.join(tokens) if self.abbr_min <= len(abbr_text) <= self.abbr_max and bracket_level(abbr_text) == 0: if abbr_text[0].isalnum() and any(c.isalpha() for c in abbr_text): # Disallow property values if re.match('^\d+(\.\d+)?(g|m[lL]|cm)$', abbr_text): return False return True return False
[ "def", "_is_allowed_abbr", "(", "self", ",", "tokens", ")", ":", "if", "len", "(", "tokens", ")", "<=", "2", ":", "abbr_text", "=", "''", ".", "join", "(", "tokens", ")", "if", "self", ".", "abbr_min", "<=", "len", "(", "abbr_text", ")", "<=", "self", ".", "abbr_max", "and", "bracket_level", "(", "abbr_text", ")", "==", "0", ":", "if", "abbr_text", "[", "0", "]", ".", "isalnum", "(", ")", "and", "any", "(", "c", ".", "isalpha", "(", ")", "for", "c", "in", "abbr_text", ")", ":", "# Disallow property values", "if", "re", ".", "match", "(", "'^\\d+(\\.\\d+)?(g|m[lL]|cm)$'", ",", "abbr_text", ")", ":", "return", "False", "return", "True", "return", "False" ]
Return True if text is an allowed abbreviation.
[ "Return", "True", "if", "text", "is", "an", "allowed", "abbreviation", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/abbrev.py#L43-L53
train
mcs07/ChemDataExtractor
chemdataextractor/scrape/base.py
BaseScraper.name
def name(self): """A unique name for this scraper.""" return ''.join('_%s' % c if c.isupper() else c for c in self.__class__.__name__).strip('_').lower()
python
def name(self): """A unique name for this scraper.""" return ''.join('_%s' % c if c.isupper() else c for c in self.__class__.__name__).strip('_').lower()
[ "def", "name", "(", "self", ")", ":", "return", "''", ".", "join", "(", "'_%s'", "%", "c", "if", "c", ".", "isupper", "(", ")", "else", "c", "for", "c", "in", "self", ".", "__class__", ".", "__name__", ")", ".", "strip", "(", "'_'", ")", ".", "lower", "(", ")" ]
A unique name for this scraper.
[ "A", "unique", "name", "for", "this", "scraper", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/scrape/base.py#L41-L43
train
mcs07/ChemDataExtractor
chemdataextractor/scrape/base.py
BaseField._post_scrape
def _post_scrape(self, value, processor=None): """Apply processing to the scraped value.""" # Pass each value through the field's clean method value = [self.process(v) for v in value] # Filter None values value = [v for v in value if v is not None] # Pass each value through processors defined on the entity if processor: value = [processor(v) for v in value] value = [v for v in value if v is not None] # Take first unless all is specified if not self.all: value = value[0] if value else None log.debug('Scraped %s: %s from %s' % (self.name, value, self.selection)) return value
python
def _post_scrape(self, value, processor=None): """Apply processing to the scraped value.""" # Pass each value through the field's clean method value = [self.process(v) for v in value] # Filter None values value = [v for v in value if v is not None] # Pass each value through processors defined on the entity if processor: value = [processor(v) for v in value] value = [v for v in value if v is not None] # Take first unless all is specified if not self.all: value = value[0] if value else None log.debug('Scraped %s: %s from %s' % (self.name, value, self.selection)) return value
[ "def", "_post_scrape", "(", "self", ",", "value", ",", "processor", "=", "None", ")", ":", "# Pass each value through the field's clean method", "value", "=", "[", "self", ".", "process", "(", "v", ")", "for", "v", "in", "value", "]", "# Filter None values", "value", "=", "[", "v", "for", "v", "in", "value", "if", "v", "is", "not", "None", "]", "# Pass each value through processors defined on the entity", "if", "processor", ":", "value", "=", "[", "processor", "(", "v", ")", "for", "v", "in", "value", "]", "value", "=", "[", "v", "for", "v", "in", "value", "if", "v", "is", "not", "None", "]", "# Take first unless all is specified", "if", "not", "self", ".", "all", ":", "value", "=", "value", "[", "0", "]", "if", "value", "else", "None", "log", ".", "debug", "(", "'Scraped %s: %s from %s'", "%", "(", "self", ".", "name", ",", "value", ",", "self", ".", "selection", ")", ")", "return", "value" ]
Apply processing to the scraped value.
[ "Apply", "processing", "to", "the", "scraped", "value", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/scrape/base.py#L197-L211
train
mcs07/ChemDataExtractor
chemdataextractor/scrape/entity.py
Entity.scrape
def scrape(cls, selector, root, xpath=False): """Return EntityList for the given selector.""" log.debug('Called scrape classmethod with root: %s' % root) roots = selector.xpath(root) if xpath else selector.css(root) results = [cls(r) for r in roots] return EntityList(*results)
python
def scrape(cls, selector, root, xpath=False): """Return EntityList for the given selector.""" log.debug('Called scrape classmethod with root: %s' % root) roots = selector.xpath(root) if xpath else selector.css(root) results = [cls(r) for r in roots] return EntityList(*results)
[ "def", "scrape", "(", "cls", ",", "selector", ",", "root", ",", "xpath", "=", "False", ")", ":", "log", ".", "debug", "(", "'Called scrape classmethod with root: %s'", "%", "root", ")", "roots", "=", "selector", ".", "xpath", "(", "root", ")", "if", "xpath", "else", "selector", ".", "css", "(", "root", ")", "results", "=", "[", "cls", "(", "r", ")", "for", "r", "in", "roots", "]", "return", "EntityList", "(", "*", "results", ")" ]
Return EntityList for the given selector.
[ "Return", "EntityList", "for", "the", "given", "selector", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/scrape/entity.py#L95-L100
train
mcs07/ChemDataExtractor
chemdataextractor/scrape/entity.py
Entity.serialize
def serialize(self): """Convert Entity to python dictionary.""" # Serialize fields to a dict data = {} for field_name in self: value = self._values.get(field_name) field = self.fields.get(field_name) if value is not None: if field.all: value = [field.serialize(v) for v in value] else: value = field.serialize(value) # Skip empty fields unless field.null if not field.null and ((field.all and value == []) or (not field.all and value in {None, ''})): continue data[field.name] = value return data
python
def serialize(self): """Convert Entity to python dictionary.""" # Serialize fields to a dict data = {} for field_name in self: value = self._values.get(field_name) field = self.fields.get(field_name) if value is not None: if field.all: value = [field.serialize(v) for v in value] else: value = field.serialize(value) # Skip empty fields unless field.null if not field.null and ((field.all and value == []) or (not field.all and value in {None, ''})): continue data[field.name] = value return data
[ "def", "serialize", "(", "self", ")", ":", "# Serialize fields to a dict", "data", "=", "{", "}", "for", "field_name", "in", "self", ":", "value", "=", "self", ".", "_values", ".", "get", "(", "field_name", ")", "field", "=", "self", ".", "fields", ".", "get", "(", "field_name", ")", "if", "value", "is", "not", "None", ":", "if", "field", ".", "all", ":", "value", "=", "[", "field", ".", "serialize", "(", "v", ")", "for", "v", "in", "value", "]", "else", ":", "value", "=", "field", ".", "serialize", "(", "value", ")", "# Skip empty fields unless field.null", "if", "not", "field", ".", "null", "and", "(", "(", "field", ".", "all", "and", "value", "==", "[", "]", ")", "or", "(", "not", "field", ".", "all", "and", "value", "in", "{", "None", ",", "''", "}", ")", ")", ":", "continue", "data", "[", "field", ".", "name", "]", "=", "value", "return", "data" ]
Convert Entity to python dictionary.
[ "Convert", "Entity", "to", "python", "dictionary", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/scrape/entity.py#L102-L118
train
mcs07/ChemDataExtractor
chemdataextractor/scrape/entity.py
Entity.to_json
def to_json(self, *args, **kwargs): """Convert Entity to JSON.""" return json.dumps(self.serialize(), *args, **kwargs)
python
def to_json(self, *args, **kwargs): """Convert Entity to JSON.""" return json.dumps(self.serialize(), *args, **kwargs)
[ "def", "to_json", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "json", ".", "dumps", "(", "self", ".", "serialize", "(", ")", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Convert Entity to JSON.
[ "Convert", "Entity", "to", "JSON", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/scrape/entity.py#L120-L122
train
mcs07/ChemDataExtractor
chemdataextractor/doc/document.py
Document.from_file
def from_file(cls, f, fname=None, readers=None): """Create a Document from a file. Usage:: with open('paper.html', 'rb') as f: doc = Document.from_file(f) .. note:: Always open files in binary mode by using the 'rb' parameter. :param file|string f: A file-like object or path to a file. :param string fname: (Optional) The filename. Used to help determine file format. :param list[chemdataextractor.reader.base.BaseReader] readers: (Optional) List of readers to use. """ if isinstance(f, six.string_types): f = io.open(f, 'rb') if not fname and hasattr(f, 'name'): fname = f.name return cls.from_string(f.read(), fname=fname, readers=readers)
python
def from_file(cls, f, fname=None, readers=None): """Create a Document from a file. Usage:: with open('paper.html', 'rb') as f: doc = Document.from_file(f) .. note:: Always open files in binary mode by using the 'rb' parameter. :param file|string f: A file-like object or path to a file. :param string fname: (Optional) The filename. Used to help determine file format. :param list[chemdataextractor.reader.base.BaseReader] readers: (Optional) List of readers to use. """ if isinstance(f, six.string_types): f = io.open(f, 'rb') if not fname and hasattr(f, 'name'): fname = f.name return cls.from_string(f.read(), fname=fname, readers=readers)
[ "def", "from_file", "(", "cls", ",", "f", ",", "fname", "=", "None", ",", "readers", "=", "None", ")", ":", "if", "isinstance", "(", "f", ",", "six", ".", "string_types", ")", ":", "f", "=", "io", ".", "open", "(", "f", ",", "'rb'", ")", "if", "not", "fname", "and", "hasattr", "(", "f", ",", "'name'", ")", ":", "fname", "=", "f", ".", "name", "return", "cls", ".", "from_string", "(", "f", ".", "read", "(", ")", ",", "fname", "=", "fname", ",", "readers", "=", "readers", ")" ]
Create a Document from a file. Usage:: with open('paper.html', 'rb') as f: doc = Document.from_file(f) .. note:: Always open files in binary mode by using the 'rb' parameter. :param file|string f: A file-like object or path to a file. :param string fname: (Optional) The filename. Used to help determine file format. :param list[chemdataextractor.reader.base.BaseReader] readers: (Optional) List of readers to use.
[ "Create", "a", "Document", "from", "a", "file", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/doc/document.py#L87-L107
train
mcs07/ChemDataExtractor
chemdataextractor/doc/document.py
Document.from_string
def from_string(cls, fstring, fname=None, readers=None): """Create a Document from a byte string containing the contents of a file. Usage:: contents = open('paper.html', 'rb').read() doc = Document.from_string(contents) .. note:: This method expects a byte string, not a unicode string (in contrast to most methods in ChemDataExtractor). :param bytes fstring: A byte string containing the contents of a file. :param string fname: (Optional) The filename. Used to help determine file format. :param list[chemdataextractor.reader.base.BaseReader] readers: (Optional) List of readers to use. """ if readers is None: from ..reader import DEFAULT_READERS readers = DEFAULT_READERS if isinstance(fstring, six.text_type): raise ReaderError('from_string expects a byte string, not a unicode string') for reader in readers: # Skip reader if we don't think it can read file if not reader.detect(fstring, fname=fname): continue try: d = reader.readstring(fstring) log.debug('Parsed document with %s' % reader.__class__.__name__) return d except ReaderError: pass raise ReaderError('Unable to read document')
python
def from_string(cls, fstring, fname=None, readers=None): """Create a Document from a byte string containing the contents of a file. Usage:: contents = open('paper.html', 'rb').read() doc = Document.from_string(contents) .. note:: This method expects a byte string, not a unicode string (in contrast to most methods in ChemDataExtractor). :param bytes fstring: A byte string containing the contents of a file. :param string fname: (Optional) The filename. Used to help determine file format. :param list[chemdataextractor.reader.base.BaseReader] readers: (Optional) List of readers to use. """ if readers is None: from ..reader import DEFAULT_READERS readers = DEFAULT_READERS if isinstance(fstring, six.text_type): raise ReaderError('from_string expects a byte string, not a unicode string') for reader in readers: # Skip reader if we don't think it can read file if not reader.detect(fstring, fname=fname): continue try: d = reader.readstring(fstring) log.debug('Parsed document with %s' % reader.__class__.__name__) return d except ReaderError: pass raise ReaderError('Unable to read document')
[ "def", "from_string", "(", "cls", ",", "fstring", ",", "fname", "=", "None", ",", "readers", "=", "None", ")", ":", "if", "readers", "is", "None", ":", "from", ".", ".", "reader", "import", "DEFAULT_READERS", "readers", "=", "DEFAULT_READERS", "if", "isinstance", "(", "fstring", ",", "six", ".", "text_type", ")", ":", "raise", "ReaderError", "(", "'from_string expects a byte string, not a unicode string'", ")", "for", "reader", "in", "readers", ":", "# Skip reader if we don't think it can read file", "if", "not", "reader", ".", "detect", "(", "fstring", ",", "fname", "=", "fname", ")", ":", "continue", "try", ":", "d", "=", "reader", ".", "readstring", "(", "fstring", ")", "log", ".", "debug", "(", "'Parsed document with %s'", "%", "reader", ".", "__class__", ".", "__name__", ")", "return", "d", "except", "ReaderError", ":", "pass", "raise", "ReaderError", "(", "'Unable to read document'", ")" ]
Create a Document from a byte string containing the contents of a file. Usage:: contents = open('paper.html', 'rb').read() doc = Document.from_string(contents) .. note:: This method expects a byte string, not a unicode string (in contrast to most methods in ChemDataExtractor). :param bytes fstring: A byte string containing the contents of a file. :param string fname: (Optional) The filename. Used to help determine file format. :param list[chemdataextractor.reader.base.BaseReader] readers: (Optional) List of readers to use.
[ "Create", "a", "Document", "from", "a", "byte", "string", "containing", "the", "contents", "of", "a", "file", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/doc/document.py#L110-L143
train
mcs07/ChemDataExtractor
chemdataextractor/doc/document.py
Document.get_element_with_id
def get_element_with_id(self, id): """Return the element with the specified ID.""" # Should we maintain a hashmap of ids to make this more efficient? Probably overkill. # TODO: Elements can contain nested elements (captions, footnotes, table cells, etc.) return next((el for el in self.elements if el.id == id), None)
python
def get_element_with_id(self, id): """Return the element with the specified ID.""" # Should we maintain a hashmap of ids to make this more efficient? Probably overkill. # TODO: Elements can contain nested elements (captions, footnotes, table cells, etc.) return next((el for el in self.elements if el.id == id), None)
[ "def", "get_element_with_id", "(", "self", ",", "id", ")", ":", "# Should we maintain a hashmap of ids to make this more efficient? Probably overkill.", "# TODO: Elements can contain nested elements (captions, footnotes, table cells, etc.)", "return", "next", "(", "(", "el", "for", "el", "in", "self", ".", "elements", "if", "el", ".", "id", "==", "id", ")", ",", "None", ")" ]
Return the element with the specified ID.
[ "Return", "the", "element", "with", "the", "specified", "ID", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/doc/document.py#L300-L304
train
mcs07/ChemDataExtractor
chemdataextractor/doc/document.py
Document.serialize
def serialize(self): """Convert Document to python dictionary.""" # Serialize fields to a dict elements = [] for element in self.elements: elements.append(element.serialize()) data = {'type': 'document', 'elements': elements} return data
python
def serialize(self): """Convert Document to python dictionary.""" # Serialize fields to a dict elements = [] for element in self.elements: elements.append(element.serialize()) data = {'type': 'document', 'elements': elements} return data
[ "def", "serialize", "(", "self", ")", ":", "# Serialize fields to a dict", "elements", "=", "[", "]", "for", "element", "in", "self", ".", "elements", ":", "elements", ".", "append", "(", "element", ".", "serialize", "(", ")", ")", "data", "=", "{", "'type'", ":", "'document'", ",", "'elements'", ":", "elements", "}", "return", "data" ]
Convert Document to python dictionary.
[ "Convert", "Document", "to", "python", "dictionary", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/doc/document.py#L357-L364
train
mcs07/ChemDataExtractor
chemdataextractor/biblio/xmp.py
XmpParser.parse
def parse(self, xmp): """Run parser and return a dictionary of all the parsed metadata.""" tree = etree.fromstring(xmp) rdf_tree = tree.find(RDF_NS + 'RDF') meta = defaultdict(dict) for desc in rdf_tree.findall(RDF_NS + 'Description'): for el in desc.getchildren(): ns, tag = self._parse_tag(el) value = self._parse_value(el) meta[ns][tag] = value return dict(meta)
python
def parse(self, xmp): """Run parser and return a dictionary of all the parsed metadata.""" tree = etree.fromstring(xmp) rdf_tree = tree.find(RDF_NS + 'RDF') meta = defaultdict(dict) for desc in rdf_tree.findall(RDF_NS + 'Description'): for el in desc.getchildren(): ns, tag = self._parse_tag(el) value = self._parse_value(el) meta[ns][tag] = value return dict(meta)
[ "def", "parse", "(", "self", ",", "xmp", ")", ":", "tree", "=", "etree", ".", "fromstring", "(", "xmp", ")", "rdf_tree", "=", "tree", ".", "find", "(", "RDF_NS", "+", "'RDF'", ")", "meta", "=", "defaultdict", "(", "dict", ")", "for", "desc", "in", "rdf_tree", ".", "findall", "(", "RDF_NS", "+", "'Description'", ")", ":", "for", "el", "in", "desc", ".", "getchildren", "(", ")", ":", "ns", ",", "tag", "=", "self", ".", "_parse_tag", "(", "el", ")", "value", "=", "self", ".", "_parse_value", "(", "el", ")", "meta", "[", "ns", "]", "[", "tag", "]", "=", "value", "return", "dict", "(", "meta", ")" ]
Run parser and return a dictionary of all the parsed metadata.
[ "Run", "parser", "and", "return", "a", "dictionary", "of", "all", "the", "parsed", "metadata", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/xmp.py#L60-L70
train
mcs07/ChemDataExtractor
chemdataextractor/biblio/xmp.py
XmpParser._parse_tag
def _parse_tag(self, el): """Extract the namespace and tag from an element.""" ns = None tag = el.tag if tag[0] == '{': ns, tag = tag[1:].split('}', 1) if self.ns_map and ns in self.ns_map: ns = self.ns_map[ns] return ns, tag
python
def _parse_tag(self, el): """Extract the namespace and tag from an element.""" ns = None tag = el.tag if tag[0] == '{': ns, tag = tag[1:].split('}', 1) if self.ns_map and ns in self.ns_map: ns = self.ns_map[ns] return ns, tag
[ "def", "_parse_tag", "(", "self", ",", "el", ")", ":", "ns", "=", "None", "tag", "=", "el", ".", "tag", "if", "tag", "[", "0", "]", "==", "'{'", ":", "ns", ",", "tag", "=", "tag", "[", "1", ":", "]", ".", "split", "(", "'}'", ",", "1", ")", "if", "self", ".", "ns_map", "and", "ns", "in", "self", ".", "ns_map", ":", "ns", "=", "self", ".", "ns_map", "[", "ns", "]", "return", "ns", ",", "tag" ]
Extract the namespace and tag from an element.
[ "Extract", "the", "namespace", "and", "tag", "from", "an", "element", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/xmp.py#L72-L80
train
mcs07/ChemDataExtractor
chemdataextractor/biblio/xmp.py
XmpParser._parse_value
def _parse_value(self, el): """Extract the metadata value from an element.""" if el.find(RDF_NS + 'Bag') is not None: value = [] for li in el.findall(RDF_NS + 'Bag/' + RDF_NS + 'li'): value.append(li.text) elif el.find(RDF_NS + 'Seq') is not None: value = [] for li in el.findall(RDF_NS + 'Seq/' + RDF_NS + 'li'): value.append(li.text) elif el.find(RDF_NS + 'Alt') is not None: value = {} for li in el.findall(RDF_NS + 'Alt/' + RDF_NS + 'li'): value[li.get(XML_NS + 'lang')] = li.text else: value = el.text return value
python
def _parse_value(self, el): """Extract the metadata value from an element.""" if el.find(RDF_NS + 'Bag') is not None: value = [] for li in el.findall(RDF_NS + 'Bag/' + RDF_NS + 'li'): value.append(li.text) elif el.find(RDF_NS + 'Seq') is not None: value = [] for li in el.findall(RDF_NS + 'Seq/' + RDF_NS + 'li'): value.append(li.text) elif el.find(RDF_NS + 'Alt') is not None: value = {} for li in el.findall(RDF_NS + 'Alt/' + RDF_NS + 'li'): value[li.get(XML_NS + 'lang')] = li.text else: value = el.text return value
[ "def", "_parse_value", "(", "self", ",", "el", ")", ":", "if", "el", ".", "find", "(", "RDF_NS", "+", "'Bag'", ")", "is", "not", "None", ":", "value", "=", "[", "]", "for", "li", "in", "el", ".", "findall", "(", "RDF_NS", "+", "'Bag/'", "+", "RDF_NS", "+", "'li'", ")", ":", "value", ".", "append", "(", "li", ".", "text", ")", "elif", "el", ".", "find", "(", "RDF_NS", "+", "'Seq'", ")", "is", "not", "None", ":", "value", "=", "[", "]", "for", "li", "in", "el", ".", "findall", "(", "RDF_NS", "+", "'Seq/'", "+", "RDF_NS", "+", "'li'", ")", ":", "value", ".", "append", "(", "li", ".", "text", ")", "elif", "el", ".", "find", "(", "RDF_NS", "+", "'Alt'", ")", "is", "not", "None", ":", "value", "=", "{", "}", "for", "li", "in", "el", ".", "findall", "(", "RDF_NS", "+", "'Alt/'", "+", "RDF_NS", "+", "'li'", ")", ":", "value", "[", "li", ".", "get", "(", "XML_NS", "+", "'lang'", ")", "]", "=", "li", ".", "text", "else", ":", "value", "=", "el", ".", "text", "return", "value" ]
Extract the metadata value from an element.
[ "Extract", "the", "metadata", "value", "from", "an", "element", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/xmp.py#L82-L98
train
mcs07/ChemDataExtractor
chemdataextractor/scrape/pub/rsc.py
parse_rsc_html
def parse_rsc_html(htmlstring): """Messy RSC HTML needs this special parser to fix problems before creating selector.""" converted = UnicodeDammit(htmlstring) if not converted.unicode_markup: raise UnicodeDecodeError('Failed to detect encoding, tried [%s]') root = fromstring(htmlstring, parser=HTMLParser(recover=True, encoding=converted.original_encoding)) # Add p.otherpara tags around orphan text newp = None for child in root.get_element_by_id('wrapper'): if newp is not None: if child.tag in BLOCK_ELEMENTS or child.get('id', '').startswith('sect') or child.getnext() is None: child.addprevious(newp) newp = None else: newp.append(child) if newp is None and child.tag in BLOCK_ELEMENTS and child.tail and child.tail.strip(): newp = Element('p', **{'class': 'otherpara'}) newp.text = child.tail child.tail = '' return root
python
def parse_rsc_html(htmlstring): """Messy RSC HTML needs this special parser to fix problems before creating selector.""" converted = UnicodeDammit(htmlstring) if not converted.unicode_markup: raise UnicodeDecodeError('Failed to detect encoding, tried [%s]') root = fromstring(htmlstring, parser=HTMLParser(recover=True, encoding=converted.original_encoding)) # Add p.otherpara tags around orphan text newp = None for child in root.get_element_by_id('wrapper'): if newp is not None: if child.tag in BLOCK_ELEMENTS or child.get('id', '').startswith('sect') or child.getnext() is None: child.addprevious(newp) newp = None else: newp.append(child) if newp is None and child.tag in BLOCK_ELEMENTS and child.tail and child.tail.strip(): newp = Element('p', **{'class': 'otherpara'}) newp.text = child.tail child.tail = '' return root
[ "def", "parse_rsc_html", "(", "htmlstring", ")", ":", "converted", "=", "UnicodeDammit", "(", "htmlstring", ")", "if", "not", "converted", ".", "unicode_markup", ":", "raise", "UnicodeDecodeError", "(", "'Failed to detect encoding, tried [%s]'", ")", "root", "=", "fromstring", "(", "htmlstring", ",", "parser", "=", "HTMLParser", "(", "recover", "=", "True", ",", "encoding", "=", "converted", ".", "original_encoding", ")", ")", "# Add p.otherpara tags around orphan text", "newp", "=", "None", "for", "child", "in", "root", ".", "get_element_by_id", "(", "'wrapper'", ")", ":", "if", "newp", "is", "not", "None", ":", "if", "child", ".", "tag", "in", "BLOCK_ELEMENTS", "or", "child", ".", "get", "(", "'id'", ",", "''", ")", ".", "startswith", "(", "'sect'", ")", "or", "child", ".", "getnext", "(", ")", "is", "None", ":", "child", ".", "addprevious", "(", "newp", ")", "newp", "=", "None", "else", ":", "newp", ".", "append", "(", "child", ")", "if", "newp", "is", "None", "and", "child", ".", "tag", "in", "BLOCK_ELEMENTS", "and", "child", ".", "tail", "and", "child", ".", "tail", ".", "strip", "(", ")", ":", "newp", "=", "Element", "(", "'p'", ",", "*", "*", "{", "'class'", ":", "'otherpara'", "}", ")", "newp", ".", "text", "=", "child", ".", "tail", "child", ".", "tail", "=", "''", "return", "root" ]
Messy RSC HTML needs this special parser to fix problems before creating selector.
[ "Messy", "RSC", "HTML", "needs", "this", "special", "parser", "to", "fix", "problems", "before", "creating", "selector", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/scrape/pub/rsc.py#L242-L261
train
mcs07/ChemDataExtractor
chemdataextractor/scrape/pub/rsc.py
replace_rsc_img_chars
def replace_rsc_img_chars(document): """Replace image characters with unicode equivalents.""" image_re = re.compile('http://www.rsc.org/images/entities/(?:h[23]+_)?(?:[ib]+_)?char_([0-9a-f]{4})(?:_([0-9a-f]{4}))?\.gif') for img in document.xpath('.//img[starts-with(@src, "http://www.rsc.org/images/entities/")]'): m = image_re.match(img.get('src')) if m: u1, u2 = m.group(1), m.group(2) if not u2 and u1 in RSC_IMG_CHARS: rep = RSC_IMG_CHARS[u1] else: rep = ('\\u%s' % u1).encode('ascii').decode('unicode-escape') if u2: rep += ('\\u%s' % u2).encode('ascii').decode('unicode-escape') if img.tail is not None: rep += img.tail # Make sure we don't remove any tail text parent = img.getparent() if parent is not None: previous = img.getprevious() if previous is not None: previous.tail = (previous.tail or '') + rep else: parent.text = (parent.text or '') + rep parent.remove(img) return document
python
def replace_rsc_img_chars(document): """Replace image characters with unicode equivalents.""" image_re = re.compile('http://www.rsc.org/images/entities/(?:h[23]+_)?(?:[ib]+_)?char_([0-9a-f]{4})(?:_([0-9a-f]{4}))?\.gif') for img in document.xpath('.//img[starts-with(@src, "http://www.rsc.org/images/entities/")]'): m = image_re.match(img.get('src')) if m: u1, u2 = m.group(1), m.group(2) if not u2 and u1 in RSC_IMG_CHARS: rep = RSC_IMG_CHARS[u1] else: rep = ('\\u%s' % u1).encode('ascii').decode('unicode-escape') if u2: rep += ('\\u%s' % u2).encode('ascii').decode('unicode-escape') if img.tail is not None: rep += img.tail # Make sure we don't remove any tail text parent = img.getparent() if parent is not None: previous = img.getprevious() if previous is not None: previous.tail = (previous.tail or '') + rep else: parent.text = (parent.text or '') + rep parent.remove(img) return document
[ "def", "replace_rsc_img_chars", "(", "document", ")", ":", "image_re", "=", "re", ".", "compile", "(", "'http://www.rsc.org/images/entities/(?:h[23]+_)?(?:[ib]+_)?char_([0-9a-f]{4})(?:_([0-9a-f]{4}))?\\.gif'", ")", "for", "img", "in", "document", ".", "xpath", "(", "'.//img[starts-with(@src, \"http://www.rsc.org/images/entities/\")]'", ")", ":", "m", "=", "image_re", ".", "match", "(", "img", ".", "get", "(", "'src'", ")", ")", "if", "m", ":", "u1", ",", "u2", "=", "m", ".", "group", "(", "1", ")", ",", "m", ".", "group", "(", "2", ")", "if", "not", "u2", "and", "u1", "in", "RSC_IMG_CHARS", ":", "rep", "=", "RSC_IMG_CHARS", "[", "u1", "]", "else", ":", "rep", "=", "(", "'\\\\u%s'", "%", "u1", ")", ".", "encode", "(", "'ascii'", ")", ".", "decode", "(", "'unicode-escape'", ")", "if", "u2", ":", "rep", "+=", "(", "'\\\\u%s'", "%", "u2", ")", ".", "encode", "(", "'ascii'", ")", ".", "decode", "(", "'unicode-escape'", ")", "if", "img", ".", "tail", "is", "not", "None", ":", "rep", "+=", "img", ".", "tail", "# Make sure we don't remove any tail text", "parent", "=", "img", ".", "getparent", "(", ")", "if", "parent", "is", "not", "None", ":", "previous", "=", "img", ".", "getprevious", "(", ")", "if", "previous", "is", "not", "None", ":", "previous", ".", "tail", "=", "(", "previous", ".", "tail", "or", "''", ")", "+", "rep", "else", ":", "parent", ".", "text", "=", "(", "parent", ".", "text", "or", "''", ")", "+", "rep", "parent", ".", "remove", "(", "img", ")", "return", "document" ]
Replace image characters with unicode equivalents.
[ "Replace", "image", "characters", "with", "unicode", "equivalents", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/scrape/pub/rsc.py#L264-L287
train
mcs07/ChemDataExtractor
chemdataextractor/scrape/pub/rsc.py
space_references
def space_references(document): """Ensure a space around reference links, so there's a gap when they are removed.""" for ref in document.xpath('.//a/sup/span[@class="sup_ref"]'): a = ref.getparent().getparent() if a is not None: atail = a.tail or '' if not atail.startswith(')') and not atail.startswith(',') and not atail.startswith(' '): a.tail = ' ' + atail return document
python
def space_references(document): """Ensure a space around reference links, so there's a gap when they are removed.""" for ref in document.xpath('.//a/sup/span[@class="sup_ref"]'): a = ref.getparent().getparent() if a is not None: atail = a.tail or '' if not atail.startswith(')') and not atail.startswith(',') and not atail.startswith(' '): a.tail = ' ' + atail return document
[ "def", "space_references", "(", "document", ")", ":", "for", "ref", "in", "document", ".", "xpath", "(", "'.//a/sup/span[@class=\"sup_ref\"]'", ")", ":", "a", "=", "ref", ".", "getparent", "(", ")", ".", "getparent", "(", ")", "if", "a", "is", "not", "None", ":", "atail", "=", "a", ".", "tail", "or", "''", "if", "not", "atail", ".", "startswith", "(", "')'", ")", "and", "not", "atail", ".", "startswith", "(", "','", ")", "and", "not", "atail", ".", "startswith", "(", "' '", ")", ":", "a", ".", "tail", "=", "' '", "+", "atail", "return", "document" ]
Ensure a space around reference links, so there's a gap when they are removed.
[ "Ensure", "a", "space", "around", "reference", "links", "so", "there", "s", "a", "gap", "when", "they", "are", "removed", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/scrape/pub/rsc.py#L290-L298
train
mcs07/ChemDataExtractor
chemdataextractor/cli/cluster.py
load
def load(ctx, input, output): """Read clusters from file and save to model file.""" log.debug('chemdataextractor.cluster.load') import pickle click.echo('Reading %s' % input.name) clusters = {} for line in input.readlines(): cluster, word, freq = line.split() clusters[word] = cluster pickle.dump(clusters, output, protocol=pickle.HIGHEST_PROTOCOL)
python
def load(ctx, input, output): """Read clusters from file and save to model file.""" log.debug('chemdataextractor.cluster.load') import pickle click.echo('Reading %s' % input.name) clusters = {} for line in input.readlines(): cluster, word, freq = line.split() clusters[word] = cluster pickle.dump(clusters, output, protocol=pickle.HIGHEST_PROTOCOL)
[ "def", "load", "(", "ctx", ",", "input", ",", "output", ")", ":", "log", ".", "debug", "(", "'chemdataextractor.cluster.load'", ")", "import", "pickle", "click", ".", "echo", "(", "'Reading %s'", "%", "input", ".", "name", ")", "clusters", "=", "{", "}", "for", "line", "in", "input", ".", "readlines", "(", ")", ":", "cluster", ",", "word", ",", "freq", "=", "line", ".", "split", "(", ")", "clusters", "[", "word", "]", "=", "cluster", "pickle", ".", "dump", "(", "clusters", ",", "output", ",", "protocol", "=", "pickle", ".", "HIGHEST_PROTOCOL", ")" ]
Read clusters from file and save to model file.
[ "Read", "clusters", "from", "file", "and", "save", "to", "model", "file", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/cluster.py#L32-L41
train
mcs07/ChemDataExtractor
chemdataextractor/scrape/pub/nlm.py
space_labels
def space_labels(document): """Ensure space around bold compound labels.""" for label in document.xpath('.//bold'): # TODO: Make this more permissive to match chemical_label in parser if not label.text or not re.match('^\(L?\d\d?[a-z]?\):?$', label.text, re.I): continue parent = label.getparent() previous = label.getprevious() if previous is None: text = parent.text or '' if not text.endswith(' '): parent.text = text + ' ' else: text = previous.tail or '' if not text.endswith(' '): previous.tail = text + ' ' text = label.tail or '' if not text.endswith(' '): label.tail = text + ' ' return document
python
def space_labels(document): """Ensure space around bold compound labels.""" for label in document.xpath('.//bold'): # TODO: Make this more permissive to match chemical_label in parser if not label.text or not re.match('^\(L?\d\d?[a-z]?\):?$', label.text, re.I): continue parent = label.getparent() previous = label.getprevious() if previous is None: text = parent.text or '' if not text.endswith(' '): parent.text = text + ' ' else: text = previous.tail or '' if not text.endswith(' '): previous.tail = text + ' ' text = label.tail or '' if not text.endswith(' '): label.tail = text + ' ' return document
[ "def", "space_labels", "(", "document", ")", ":", "for", "label", "in", "document", ".", "xpath", "(", "'.//bold'", ")", ":", "# TODO: Make this more permissive to match chemical_label in parser", "if", "not", "label", ".", "text", "or", "not", "re", ".", "match", "(", "'^\\(L?\\d\\d?[a-z]?\\):?$'", ",", "label", ".", "text", ",", "re", ".", "I", ")", ":", "continue", "parent", "=", "label", ".", "getparent", "(", ")", "previous", "=", "label", ".", "getprevious", "(", ")", "if", "previous", "is", "None", ":", "text", "=", "parent", ".", "text", "or", "''", "if", "not", "text", ".", "endswith", "(", "' '", ")", ":", "parent", ".", "text", "=", "text", "+", "' '", "else", ":", "text", "=", "previous", ".", "tail", "or", "''", "if", "not", "text", ".", "endswith", "(", "' '", ")", ":", "previous", ".", "tail", "=", "text", "+", "' '", "text", "=", "label", ".", "tail", "or", "''", "if", "not", "text", ".", "endswith", "(", "' '", ")", ":", "label", ".", "tail", "=", "text", "+", "' '", "return", "document" ]
Ensure space around bold compound labels.
[ "Ensure", "space", "around", "bold", "compound", "labels", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/scrape/pub/nlm.py#L34-L53
train
mcs07/ChemDataExtractor
chemdataextractor/scrape/pub/nlm.py
tidy_nlm_references
def tidy_nlm_references(document): """Remove punctuation around references like brackets, commas, hyphens.""" def strip_preceding(text): stext = text.rstrip() if stext.endswith('[') or stext.endswith('('): #log.debug('%s -> %s' % (text, stext[:-1])) return stext[:-1] return text def strip_between(text): stext = text.strip() if stext in {',', '-', '\u2013', '\u2212'}: #log.debug('%s -> %s' % (text, '')) return '' return text def strip_following(text): stext = text.lstrip() if stext.startswith(']') or stext.startswith(')'): #log.debug('%s -> %s' % (text, stext[1:])) return stext[1:] return text for ref in document.xpath('.//xref[@ref-type="bibr"]'): parent = ref.getparent() previous = ref.getprevious() next = ref.getnext() if previous is None: parent.text = strip_preceding(parent.text or '') else: previous.tail = strip_preceding(previous.tail or '') if next is not None and next.tag == 'xref' and next.get('ref-type') == 'bibr': ref.tail = strip_between(ref.tail or '') ref.tail = strip_following(ref.tail or '') return document
python
def tidy_nlm_references(document): """Remove punctuation around references like brackets, commas, hyphens.""" def strip_preceding(text): stext = text.rstrip() if stext.endswith('[') or stext.endswith('('): #log.debug('%s -> %s' % (text, stext[:-1])) return stext[:-1] return text def strip_between(text): stext = text.strip() if stext in {',', '-', '\u2013', '\u2212'}: #log.debug('%s -> %s' % (text, '')) return '' return text def strip_following(text): stext = text.lstrip() if stext.startswith(']') or stext.startswith(')'): #log.debug('%s -> %s' % (text, stext[1:])) return stext[1:] return text for ref in document.xpath('.//xref[@ref-type="bibr"]'): parent = ref.getparent() previous = ref.getprevious() next = ref.getnext() if previous is None: parent.text = strip_preceding(parent.text or '') else: previous.tail = strip_preceding(previous.tail or '') if next is not None and next.tag == 'xref' and next.get('ref-type') == 'bibr': ref.tail = strip_between(ref.tail or '') ref.tail = strip_following(ref.tail or '') return document
[ "def", "tidy_nlm_references", "(", "document", ")", ":", "def", "strip_preceding", "(", "text", ")", ":", "stext", "=", "text", ".", "rstrip", "(", ")", "if", "stext", ".", "endswith", "(", "'['", ")", "or", "stext", ".", "endswith", "(", "'('", ")", ":", "#log.debug('%s -> %s' % (text, stext[:-1]))", "return", "stext", "[", ":", "-", "1", "]", "return", "text", "def", "strip_between", "(", "text", ")", ":", "stext", "=", "text", ".", "strip", "(", ")", "if", "stext", "in", "{", "','", ",", "'-'", ",", "'\\u2013'", ",", "'\\u2212'", "}", ":", "#log.debug('%s -> %s' % (text, ''))", "return", "''", "return", "text", "def", "strip_following", "(", "text", ")", ":", "stext", "=", "text", ".", "lstrip", "(", ")", "if", "stext", ".", "startswith", "(", "']'", ")", "or", "stext", ".", "startswith", "(", "')'", ")", ":", "#log.debug('%s -> %s' % (text, stext[1:]))", "return", "stext", "[", "1", ":", "]", "return", "text", "for", "ref", "in", "document", ".", "xpath", "(", "'.//xref[@ref-type=\"bibr\"]'", ")", ":", "parent", "=", "ref", ".", "getparent", "(", ")", "previous", "=", "ref", ".", "getprevious", "(", ")", "next", "=", "ref", ".", "getnext", "(", ")", "if", "previous", "is", "None", ":", "parent", ".", "text", "=", "strip_preceding", "(", "parent", ".", "text", "or", "''", ")", "else", ":", "previous", ".", "tail", "=", "strip_preceding", "(", "previous", ".", "tail", "or", "''", ")", "if", "next", "is", "not", "None", "and", "next", ".", "tag", "==", "'xref'", "and", "next", ".", "get", "(", "'ref-type'", ")", "==", "'bibr'", ":", "ref", ".", "tail", "=", "strip_between", "(", "ref", ".", "tail", "or", "''", ")", "ref", ".", "tail", "=", "strip_following", "(", "ref", ".", "tail", "or", "''", ")", "return", "document" ]
Remove punctuation around references like brackets, commas, hyphens.
[ "Remove", "punctuation", "around", "references", "like", "brackets", "commas", "hyphens", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/scrape/pub/nlm.py#L56-L91
train
mcs07/ChemDataExtractor
chemdataextractor/nlp/tokenize.py
regex_span_tokenize
def regex_span_tokenize(s, regex): """Return spans that identify tokens in s split using regex.""" left = 0 for m in re.finditer(regex, s, re.U): right, next = m.span() if right != 0: yield left, right left = next yield left, len(s)
python
def regex_span_tokenize(s, regex): """Return spans that identify tokens in s split using regex.""" left = 0 for m in re.finditer(regex, s, re.U): right, next = m.span() if right != 0: yield left, right left = next yield left, len(s)
[ "def", "regex_span_tokenize", "(", "s", ",", "regex", ")", ":", "left", "=", "0", "for", "m", "in", "re", ".", "finditer", "(", "regex", ",", "s", ",", "re", ".", "U", ")", ":", "right", ",", "next", "=", "m", ".", "span", "(", ")", "if", "right", "!=", "0", ":", "yield", "left", ",", "right", "left", "=", "next", "yield", "left", ",", "len", "(", "s", ")" ]
Return spans that identify tokens in s split using regex.
[ "Return", "spans", "that", "identify", "tokens", "in", "s", "split", "using", "regex", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tokenize.py#L70-L78
train
mcs07/ChemDataExtractor
chemdataextractor/nlp/tokenize.py
BaseTokenizer.tokenize
def tokenize(self, s): """Return a list of token strings from the given sentence. :param string s: The sentence string to tokenize. :rtype: iter(str) """ return [s[start:end] for start, end in self.span_tokenize(s)]
python
def tokenize(self, s): """Return a list of token strings from the given sentence. :param string s: The sentence string to tokenize. :rtype: iter(str) """ return [s[start:end] for start, end in self.span_tokenize(s)]
[ "def", "tokenize", "(", "self", ",", "s", ")", ":", "return", "[", "s", "[", "start", ":", "end", "]", "for", "start", ",", "end", "in", "self", ".", "span_tokenize", "(", "s", ")", "]" ]
Return a list of token strings from the given sentence. :param string s: The sentence string to tokenize. :rtype: iter(str)
[ "Return", "a", "list", "of", "token", "strings", "from", "the", "given", "sentence", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tokenize.py#L35-L41
train
mcs07/ChemDataExtractor
chemdataextractor/nlp/tokenize.py
SentenceTokenizer.span_tokenize
def span_tokenize(self, s): """Return a list of integer offsets that identify sentences in the given text. :param string s: The text to tokenize into sentences. :rtype: iter(tuple(int, int)) """ if self._tokenizer is None: self._tokenizer = load_model(self.model) # for debug in tokenizer.debug_decisions(s): # log.debug(format_debug_decision(debug)) return self._tokenizer.span_tokenize(s)
python
def span_tokenize(self, s): """Return a list of integer offsets that identify sentences in the given text. :param string s: The text to tokenize into sentences. :rtype: iter(tuple(int, int)) """ if self._tokenizer is None: self._tokenizer = load_model(self.model) # for debug in tokenizer.debug_decisions(s): # log.debug(format_debug_decision(debug)) return self._tokenizer.span_tokenize(s)
[ "def", "span_tokenize", "(", "self", ",", "s", ")", ":", "if", "self", ".", "_tokenizer", "is", "None", ":", "self", ".", "_tokenizer", "=", "load_model", "(", "self", ".", "model", ")", "# for debug in tokenizer.debug_decisions(s):", "# log.debug(format_debug_decision(debug))", "return", "self", ".", "_tokenizer", ".", "span_tokenize", "(", "s", ")" ]
Return a list of integer offsets that identify sentences in the given text. :param string s: The text to tokenize into sentences. :rtype: iter(tuple(int, int))
[ "Return", "a", "list", "of", "integer", "offsets", "that", "identify", "sentences", "in", "the", "given", "text", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tokenize.py#L91-L101
train
mcs07/ChemDataExtractor
chemdataextractor/nlp/tokenize.py
WordTokenizer._split_span
def _split_span(self, span, index, length=0): """Split a span into two or three separate spans at certain indices.""" offset = span[1] + index if index < 0 else span[0] + index # log.debug([(span[0], offset), (offset, offset + length), (offset + length, span[1])]) return [(span[0], offset), (offset, offset + length), (offset + length, span[1])]
python
def _split_span(self, span, index, length=0): """Split a span into two or three separate spans at certain indices.""" offset = span[1] + index if index < 0 else span[0] + index # log.debug([(span[0], offset), (offset, offset + length), (offset + length, span[1])]) return [(span[0], offset), (offset, offset + length), (offset + length, span[1])]
[ "def", "_split_span", "(", "self", ",", "span", ",", "index", ",", "length", "=", "0", ")", ":", "offset", "=", "span", "[", "1", "]", "+", "index", "if", "index", "<", "0", "else", "span", "[", "0", "]", "+", "index", "# log.debug([(span[0], offset), (offset, offset + length), (offset + length, span[1])])", "return", "[", "(", "span", "[", "0", "]", ",", "offset", ")", ",", "(", "offset", ",", "offset", "+", "length", ")", ",", "(", "offset", "+", "length", ",", "span", "[", "1", "]", ")", "]" ]
Split a span into two or three separate spans at certain indices.
[ "Split", "a", "span", "into", "two", "or", "three", "separate", "spans", "at", "certain", "indices", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tokenize.py#L247-L251
train
mcs07/ChemDataExtractor
chemdataextractor/nlp/tokenize.py
ChemWordTokenizer._closing_bracket_index
def _closing_bracket_index(self, text, bpair=('(', ')')): """Return the index of the closing bracket that matches the opening bracket at the start of the text.""" level = 1 for i, char in enumerate(text[1:]): if char == bpair[0]: level += 1 elif char == bpair[1]: level -= 1 if level == 0: return i + 1
python
def _closing_bracket_index(self, text, bpair=('(', ')')): """Return the index of the closing bracket that matches the opening bracket at the start of the text.""" level = 1 for i, char in enumerate(text[1:]): if char == bpair[0]: level += 1 elif char == bpair[1]: level -= 1 if level == 0: return i + 1
[ "def", "_closing_bracket_index", "(", "self", ",", "text", ",", "bpair", "=", "(", "'('", ",", "')'", ")", ")", ":", "level", "=", "1", "for", "i", ",", "char", "in", "enumerate", "(", "text", "[", "1", ":", "]", ")", ":", "if", "char", "==", "bpair", "[", "0", "]", ":", "level", "+=", "1", "elif", "char", "==", "bpair", "[", "1", "]", ":", "level", "-=", "1", "if", "level", "==", "0", ":", "return", "i", "+", "1" ]
Return the index of the closing bracket that matches the opening bracket at the start of the text.
[ "Return", "the", "index", "of", "the", "closing", "bracket", "that", "matches", "the", "opening", "bracket", "at", "the", "start", "of", "the", "text", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tokenize.py#L535-L544
train
mcs07/ChemDataExtractor
chemdataextractor/nlp/tokenize.py
ChemWordTokenizer._opening_bracket_index
def _opening_bracket_index(self, text, bpair=('(', ')')): """Return the index of the opening bracket that matches the closing bracket at the end of the text.""" level = 1 for i, char in enumerate(reversed(text[:-1])): if char == bpair[1]: level += 1 elif char == bpair[0]: level -= 1 if level == 0: return len(text) - i - 2
python
def _opening_bracket_index(self, text, bpair=('(', ')')): """Return the index of the opening bracket that matches the closing bracket at the end of the text.""" level = 1 for i, char in enumerate(reversed(text[:-1])): if char == bpair[1]: level += 1 elif char == bpair[0]: level -= 1 if level == 0: return len(text) - i - 2
[ "def", "_opening_bracket_index", "(", "self", ",", "text", ",", "bpair", "=", "(", "'('", ",", "')'", ")", ")", ":", "level", "=", "1", "for", "i", ",", "char", "in", "enumerate", "(", "reversed", "(", "text", "[", ":", "-", "1", "]", ")", ")", ":", "if", "char", "==", "bpair", "[", "1", "]", ":", "level", "+=", "1", "elif", "char", "==", "bpair", "[", "0", "]", ":", "level", "-=", "1", "if", "level", "==", "0", ":", "return", "len", "(", "text", ")", "-", "i", "-", "2" ]
Return the index of the opening bracket that matches the closing bracket at the end of the text.
[ "Return", "the", "index", "of", "the", "opening", "bracket", "that", "matches", "the", "closing", "bracket", "at", "the", "end", "of", "the", "text", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tokenize.py#L546-L555
train
mcs07/ChemDataExtractor
chemdataextractor/nlp/tokenize.py
ChemWordTokenizer._is_saccharide_arrow
def _is_saccharide_arrow(self, before, after): """Return True if the arrow is in a chemical name.""" if (before and after and before[-1].isdigit() and after[0].isdigit() and before.rstrip('0123456789').endswith('(') and after.lstrip('0123456789').startswith(')-')): return True else: return False
python
def _is_saccharide_arrow(self, before, after): """Return True if the arrow is in a chemical name.""" if (before and after and before[-1].isdigit() and after[0].isdigit() and before.rstrip('0123456789').endswith('(') and after.lstrip('0123456789').startswith(')-')): return True else: return False
[ "def", "_is_saccharide_arrow", "(", "self", ",", "before", ",", "after", ")", ":", "if", "(", "before", "and", "after", "and", "before", "[", "-", "1", "]", ".", "isdigit", "(", ")", "and", "after", "[", "0", "]", ".", "isdigit", "(", ")", "and", "before", ".", "rstrip", "(", "'0123456789'", ")", ".", "endswith", "(", "'('", ")", "and", "after", ".", "lstrip", "(", "'0123456789'", ")", ".", "startswith", "(", "')-'", ")", ")", ":", "return", "True", "else", ":", "return", "False" ]
Return True if the arrow is in a chemical name.
[ "Return", "True", "if", "the", "arrow", "is", "in", "a", "chemical", "name", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tokenize.py#L565-L571
train
mcs07/ChemDataExtractor
chemdataextractor/cli/evaluate.py
get_names
def get_names(cs): """Return list of every name.""" records = [] for c in cs: records.extend(c.get('names', [])) return records
python
def get_names(cs): """Return list of every name.""" records = [] for c in cs: records.extend(c.get('names', [])) return records
[ "def", "get_names", "(", "cs", ")", ":", "records", "=", "[", "]", "for", "c", "in", "cs", ":", "records", ".", "extend", "(", "c", ".", "get", "(", "'names'", ",", "[", "]", ")", ")", "return", "records" ]
Return list of every name.
[ "Return", "list", "of", "every", "name", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/evaluate.py#L75-L80
train
mcs07/ChemDataExtractor
chemdataextractor/cli/evaluate.py
get_labels
def get_labels(cs): """Return list of every label.""" records = [] for c in cs: records.extend(c.get('labels', [])) return records
python
def get_labels(cs): """Return list of every label.""" records = [] for c in cs: records.extend(c.get('labels', [])) return records
[ "def", "get_labels", "(", "cs", ")", ":", "records", "=", "[", "]", "for", "c", "in", "cs", ":", "records", ".", "extend", "(", "c", ".", "get", "(", "'labels'", ",", "[", "]", ")", ")", "return", "records" ]
Return list of every label.
[ "Return", "list", "of", "every", "label", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/evaluate.py#L83-L88
train
mcs07/ChemDataExtractor
chemdataextractor/cli/evaluate.py
get_ids
def get_ids(cs): """Return chemical identifier records.""" records = [] for c in cs: records.append({k: c[k] for k in c if k in {'names', 'labels'}}) return records
python
def get_ids(cs): """Return chemical identifier records.""" records = [] for c in cs: records.append({k: c[k] for k in c if k in {'names', 'labels'}}) return records
[ "def", "get_ids", "(", "cs", ")", ":", "records", "=", "[", "]", "for", "c", "in", "cs", ":", "records", ".", "append", "(", "{", "k", ":", "c", "[", "k", "]", "for", "k", "in", "c", "if", "k", "in", "{", "'names'", ",", "'labels'", "}", "}", ")", "return", "records" ]
Return chemical identifier records.
[ "Return", "chemical", "identifier", "records", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/evaluate.py#L91-L96
train
mcs07/ChemDataExtractor
chemdataextractor/utils.py
memoized_property
def memoized_property(fget): """Decorator to create memoized properties.""" attr_name = '_{}'.format(fget.__name__) @functools.wraps(fget) def fget_memoized(self): if not hasattr(self, attr_name): setattr(self, attr_name, fget(self)) return getattr(self, attr_name) return property(fget_memoized)
python
def memoized_property(fget): """Decorator to create memoized properties.""" attr_name = '_{}'.format(fget.__name__) @functools.wraps(fget) def fget_memoized(self): if not hasattr(self, attr_name): setattr(self, attr_name, fget(self)) return getattr(self, attr_name) return property(fget_memoized)
[ "def", "memoized_property", "(", "fget", ")", ":", "attr_name", "=", "'_{}'", ".", "format", "(", "fget", ".", "__name__", ")", "@", "functools", ".", "wraps", "(", "fget", ")", "def", "fget_memoized", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "attr_name", ")", ":", "setattr", "(", "self", ",", "attr_name", ",", "fget", "(", "self", ")", ")", "return", "getattr", "(", "self", ",", "attr_name", ")", "return", "property", "(", "fget_memoized", ")" ]
Decorator to create memoized properties.
[ "Decorator", "to", "create", "memoized", "properties", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/utils.py#L25-L34
train
mcs07/ChemDataExtractor
chemdataextractor/utils.py
memoize
def memoize(obj): """Decorator to create memoized functions, methods or classes.""" cache = obj.cache = {} @functools.wraps(obj) def memoizer(*args, **kwargs): if args not in cache: cache[args] = obj(*args, **kwargs) return cache[args] return memoizer
python
def memoize(obj): """Decorator to create memoized functions, methods or classes.""" cache = obj.cache = {} @functools.wraps(obj) def memoizer(*args, **kwargs): if args not in cache: cache[args] = obj(*args, **kwargs) return cache[args] return memoizer
[ "def", "memoize", "(", "obj", ")", ":", "cache", "=", "obj", ".", "cache", "=", "{", "}", "@", "functools", ".", "wraps", "(", "obj", ")", "def", "memoizer", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", "not", "in", "cache", ":", "cache", "[", "args", "]", "=", "obj", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "cache", "[", "args", "]", "return", "memoizer" ]
Decorator to create memoized functions, methods or classes.
[ "Decorator", "to", "create", "memoized", "functions", "methods", "or", "classes", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/utils.py#L37-L46
train
mcs07/ChemDataExtractor
chemdataextractor/nlp/tag.py
BaseTagger.evaluate
def evaluate(self, gold): """Evaluate the accuracy of this tagger using a gold standard corpus. :param list(list(tuple(str, str))) gold: The list of tagged sentences to score the tagger on. :returns: Tagger accuracy value. :rtype: float """ tagged_sents = self.tag_sents([w for (w, t) in sent] for sent in gold) gold_tokens = sum(gold, []) test_tokens = sum(tagged_sents, []) accuracy = float(sum(x == y for x, y in six.moves.zip(gold_tokens, test_tokens))) / len(test_tokens) return accuracy
python
def evaluate(self, gold): """Evaluate the accuracy of this tagger using a gold standard corpus. :param list(list(tuple(str, str))) gold: The list of tagged sentences to score the tagger on. :returns: Tagger accuracy value. :rtype: float """ tagged_sents = self.tag_sents([w for (w, t) in sent] for sent in gold) gold_tokens = sum(gold, []) test_tokens = sum(tagged_sents, []) accuracy = float(sum(x == y for x, y in six.moves.zip(gold_tokens, test_tokens))) / len(test_tokens) return accuracy
[ "def", "evaluate", "(", "self", ",", "gold", ")", ":", "tagged_sents", "=", "self", ".", "tag_sents", "(", "[", "w", "for", "(", "w", ",", "t", ")", "in", "sent", "]", "for", "sent", "in", "gold", ")", "gold_tokens", "=", "sum", "(", "gold", ",", "[", "]", ")", "test_tokens", "=", "sum", "(", "tagged_sents", ",", "[", "]", ")", "accuracy", "=", "float", "(", "sum", "(", "x", "==", "y", "for", "x", ",", "y", "in", "six", ".", "moves", ".", "zip", "(", "gold_tokens", ",", "test_tokens", ")", ")", ")", "/", "len", "(", "test_tokens", ")", "return", "accuracy" ]
Evaluate the accuracy of this tagger using a gold standard corpus. :param list(list(tuple(str, str))) gold: The list of tagged sentences to score the tagger on. :returns: Tagger accuracy value. :rtype: float
[ "Evaluate", "the", "accuracy", "of", "this", "tagger", "using", "a", "gold", "standard", "corpus", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tag.py#L51-L62
train
mcs07/ChemDataExtractor
chemdataextractor/nlp/tag.py
AveragedPerceptron.predict
def predict(self, features): """Dot-product the features and current weights and return the best label.""" scores = defaultdict(float) for feat in features: if feat not in self.weights: continue weights = self.weights[feat] for label, weight in weights.items(): scores[label] += weight # Do a secondary alphabetic sort, for stability return max(self.classes, key=lambda label: (scores[label], label))
python
def predict(self, features): """Dot-product the features and current weights and return the best label.""" scores = defaultdict(float) for feat in features: if feat not in self.weights: continue weights = self.weights[feat] for label, weight in weights.items(): scores[label] += weight # Do a secondary alphabetic sort, for stability return max(self.classes, key=lambda label: (scores[label], label))
[ "def", "predict", "(", "self", ",", "features", ")", ":", "scores", "=", "defaultdict", "(", "float", ")", "for", "feat", "in", "features", ":", "if", "feat", "not", "in", "self", ".", "weights", ":", "continue", "weights", "=", "self", ".", "weights", "[", "feat", "]", "for", "label", ",", "weight", "in", "weights", ".", "items", "(", ")", ":", "scores", "[", "label", "]", "+=", "weight", "# Do a secondary alphabetic sort, for stability", "return", "max", "(", "self", ".", "classes", ",", "key", "=", "lambda", "label", ":", "(", "scores", "[", "label", "]", ",", "label", ")", ")" ]
Dot-product the features and current weights and return the best label.
[ "Dot", "-", "product", "the", "features", "and", "current", "weights", "and", "return", "the", "best", "label", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tag.py#L141-L151
train
mcs07/ChemDataExtractor
chemdataextractor/nlp/tag.py
AveragedPerceptron.update
def update(self, truth, guess, features): """Update the feature weights.""" def upd_feat(c, f, w, v): param = (f, c) self._totals[param] += (self.i - self._tstamps[param]) * w self._tstamps[param] = self.i self.weights[f][c] = w + v self.i += 1 if truth == guess: return None for f in features: weights = self.weights.setdefault(f, {}) upd_feat(truth, f, weights.get(truth, 0.0), 1.0) upd_feat(guess, f, weights.get(guess, 0.0), -1.0) return None
python
def update(self, truth, guess, features): """Update the feature weights.""" def upd_feat(c, f, w, v): param = (f, c) self._totals[param] += (self.i - self._tstamps[param]) * w self._tstamps[param] = self.i self.weights[f][c] = w + v self.i += 1 if truth == guess: return None for f in features: weights = self.weights.setdefault(f, {}) upd_feat(truth, f, weights.get(truth, 0.0), 1.0) upd_feat(guess, f, weights.get(guess, 0.0), -1.0) return None
[ "def", "update", "(", "self", ",", "truth", ",", "guess", ",", "features", ")", ":", "def", "upd_feat", "(", "c", ",", "f", ",", "w", ",", "v", ")", ":", "param", "=", "(", "f", ",", "c", ")", "self", ".", "_totals", "[", "param", "]", "+=", "(", "self", ".", "i", "-", "self", ".", "_tstamps", "[", "param", "]", ")", "*", "w", "self", ".", "_tstamps", "[", "param", "]", "=", "self", ".", "i", "self", ".", "weights", "[", "f", "]", "[", "c", "]", "=", "w", "+", "v", "self", ".", "i", "+=", "1", "if", "truth", "==", "guess", ":", "return", "None", "for", "f", "in", "features", ":", "weights", "=", "self", ".", "weights", ".", "setdefault", "(", "f", ",", "{", "}", ")", "upd_feat", "(", "truth", ",", "f", ",", "weights", ".", "get", "(", "truth", ",", "0.0", ")", ",", "1.0", ")", "upd_feat", "(", "guess", ",", "f", ",", "weights", ".", "get", "(", "guess", ",", "0.0", ")", ",", "-", "1.0", ")", "return", "None" ]
Update the feature weights.
[ "Update", "the", "feature", "weights", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tag.py#L153-L168
train
mcs07/ChemDataExtractor
chemdataextractor/nlp/tag.py
AveragedPerceptron.average_weights
def average_weights(self): """Average weights from all iterations.""" for feat, weights in self.weights.items(): new_feat_weights = {} for clas, weight in weights.items(): param = (feat, clas) total = self._totals[param] total += (self.i - self._tstamps[param]) * weight averaged = round(total / float(self.i), 3) if averaged: new_feat_weights[clas] = averaged self.weights[feat] = new_feat_weights return None
python
def average_weights(self): """Average weights from all iterations.""" for feat, weights in self.weights.items(): new_feat_weights = {} for clas, weight in weights.items(): param = (feat, clas) total = self._totals[param] total += (self.i - self._tstamps[param]) * weight averaged = round(total / float(self.i), 3) if averaged: new_feat_weights[clas] = averaged self.weights[feat] = new_feat_weights return None
[ "def", "average_weights", "(", "self", ")", ":", "for", "feat", ",", "weights", "in", "self", ".", "weights", ".", "items", "(", ")", ":", "new_feat_weights", "=", "{", "}", "for", "clas", ",", "weight", "in", "weights", ".", "items", "(", ")", ":", "param", "=", "(", "feat", ",", "clas", ")", "total", "=", "self", ".", "_totals", "[", "param", "]", "total", "+=", "(", "self", ".", "i", "-", "self", ".", "_tstamps", "[", "param", "]", ")", "*", "weight", "averaged", "=", "round", "(", "total", "/", "float", "(", "self", ".", "i", ")", ",", "3", ")", "if", "averaged", ":", "new_feat_weights", "[", "clas", "]", "=", "averaged", "self", ".", "weights", "[", "feat", "]", "=", "new_feat_weights", "return", "None" ]
Average weights from all iterations.
[ "Average", "weights", "from", "all", "iterations", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tag.py#L170-L182
train
mcs07/ChemDataExtractor
chemdataextractor/nlp/tag.py
AveragedPerceptron.save
def save(self, path): """Save the pickled model weights.""" with io.open(path, 'wb') as fout: return pickle.dump(dict(self.weights), fout)
python
def save(self, path): """Save the pickled model weights.""" with io.open(path, 'wb') as fout: return pickle.dump(dict(self.weights), fout)
[ "def", "save", "(", "self", ",", "path", ")", ":", "with", "io", ".", "open", "(", "path", ",", "'wb'", ")", "as", "fout", ":", "return", "pickle", ".", "dump", "(", "dict", "(", "self", ".", "weights", ")", ",", "fout", ")" ]
Save the pickled model weights.
[ "Save", "the", "pickled", "model", "weights", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tag.py#L184-L187
train
mcs07/ChemDataExtractor
chemdataextractor/nlp/tag.py
AveragedPerceptron.load
def load(self, path): """Load the pickled model weights.""" with io.open(path, 'rb') as fin: self.weights = pickle.load(fin)
python
def load(self, path): """Load the pickled model weights.""" with io.open(path, 'rb') as fin: self.weights = pickle.load(fin)
[ "def", "load", "(", "self", ",", "path", ")", ":", "with", "io", ".", "open", "(", "path", ",", "'rb'", ")", "as", "fin", ":", "self", ".", "weights", "=", "pickle", ".", "load", "(", "fin", ")" ]
Load the pickled model weights.
[ "Load", "the", "pickled", "model", "weights", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tag.py#L189-L192
train
mcs07/ChemDataExtractor
chemdataextractor/nlp/tag.py
ApTagger.train
def train(self, sentences, nr_iter=5): """Train a model from sentences. :param sentences: A list of sentences, each of which is a list of (token, tag) tuples. :param nr_iter: Number of training iterations. """ self._make_tagdict(sentences) self.perceptron.classes = self.classes for iter_ in range(nr_iter): c = 0 n = 0 for sentence in sentences: prev, prev2 = self.START context = [t[0] for t in sentence] for i, (token, tag) in enumerate(sentence): guess = self.tagdict.get(token) if not guess: feats = self._get_features(i, context, prev, prev2) guess = self.perceptron.predict(feats) self.perceptron.update(tag, guess, feats) prev2 = prev prev = guess c += guess == tag n += 1 random.shuffle(sentences) log.debug('Iter %s: %s/%s=%s' % (iter_, c, n, (float(c) / n) * 100)) self.perceptron.average_weights()
python
def train(self, sentences, nr_iter=5): """Train a model from sentences. :param sentences: A list of sentences, each of which is a list of (token, tag) tuples. :param nr_iter: Number of training iterations. """ self._make_tagdict(sentences) self.perceptron.classes = self.classes for iter_ in range(nr_iter): c = 0 n = 0 for sentence in sentences: prev, prev2 = self.START context = [t[0] for t in sentence] for i, (token, tag) in enumerate(sentence): guess = self.tagdict.get(token) if not guess: feats = self._get_features(i, context, prev, prev2) guess = self.perceptron.predict(feats) self.perceptron.update(tag, guess, feats) prev2 = prev prev = guess c += guess == tag n += 1 random.shuffle(sentences) log.debug('Iter %s: %s/%s=%s' % (iter_, c, n, (float(c) / n) * 100)) self.perceptron.average_weights()
[ "def", "train", "(", "self", ",", "sentences", ",", "nr_iter", "=", "5", ")", ":", "self", ".", "_make_tagdict", "(", "sentences", ")", "self", ".", "perceptron", ".", "classes", "=", "self", ".", "classes", "for", "iter_", "in", "range", "(", "nr_iter", ")", ":", "c", "=", "0", "n", "=", "0", "for", "sentence", "in", "sentences", ":", "prev", ",", "prev2", "=", "self", ".", "START", "context", "=", "[", "t", "[", "0", "]", "for", "t", "in", "sentence", "]", "for", "i", ",", "(", "token", ",", "tag", ")", "in", "enumerate", "(", "sentence", ")", ":", "guess", "=", "self", ".", "tagdict", ".", "get", "(", "token", ")", "if", "not", "guess", ":", "feats", "=", "self", ".", "_get_features", "(", "i", ",", "context", ",", "prev", ",", "prev2", ")", "guess", "=", "self", ".", "perceptron", ".", "predict", "(", "feats", ")", "self", ".", "perceptron", ".", "update", "(", "tag", ",", "guess", ",", "feats", ")", "prev2", "=", "prev", "prev", "=", "guess", "c", "+=", "guess", "==", "tag", "n", "+=", "1", "random", ".", "shuffle", "(", "sentences", ")", "log", ".", "debug", "(", "'Iter %s: %s/%s=%s'", "%", "(", "iter_", ",", "c", ",", "n", ",", "(", "float", "(", "c", ")", "/", "n", ")", "*", "100", ")", ")", "self", ".", "perceptron", ".", "average_weights", "(", ")" ]
Train a model from sentences. :param sentences: A list of sentences, each of which is a list of (token, tag) tuples. :param nr_iter: Number of training iterations.
[ "Train", "a", "model", "from", "sentences", "." ]
349a3bea965f2073141d62043b89319222e46af1
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tag.py#L235-L261
train