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
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
istresearch/scrapy-cluster
utils/scutils/stats_collector.py
StatsCollector.get_hll_counter
def get_hll_counter(self, redis_conn=None, host='localhost', port=6379, key='hyperloglog_counter', cycle_time=5, start_time=None, window=SECONDS_1_HOUR, roll=True, keep_max=12): ''' Generate a new HyperLogLogCounter. Useful for approximating extremely large counts of unique items @param redis_conn: A premade redis connection (overrides host and port) @param host: the redis host @param port: the redis port @param key: the key for your stats collection @param cycle_time: how often to check for expiring counts @param start_time: the time to start valid collection @param window: how long to collect data for in seconds (if rolling) @param roll: Roll the window after it expires, to continue collecting on a new date based key. @keep_max: If rolling the static window, the max number of prior windows to keep ''' counter = HyperLogLogCounter(key=key, cycle_time=cycle_time, start_time=start_time, window=window, roll=roll, keep_max=keep_max) counter.setup(redis_conn=redis_conn, host=host, port=port) return counter
python
def get_hll_counter(self, redis_conn=None, host='localhost', port=6379, key='hyperloglog_counter', cycle_time=5, start_time=None, window=SECONDS_1_HOUR, roll=True, keep_max=12): ''' Generate a new HyperLogLogCounter. Useful for approximating extremely large counts of unique items @param redis_conn: A premade redis connection (overrides host and port) @param host: the redis host @param port: the redis port @param key: the key for your stats collection @param cycle_time: how often to check for expiring counts @param start_time: the time to start valid collection @param window: how long to collect data for in seconds (if rolling) @param roll: Roll the window after it expires, to continue collecting on a new date based key. @keep_max: If rolling the static window, the max number of prior windows to keep ''' counter = HyperLogLogCounter(key=key, cycle_time=cycle_time, start_time=start_time, window=window, roll=roll, keep_max=keep_max) counter.setup(redis_conn=redis_conn, host=host, port=port) return counter
[ "def", "get_hll_counter", "(", "self", ",", "redis_conn", "=", "None", ",", "host", "=", "'localhost'", ",", "port", "=", "6379", ",", "key", "=", "'hyperloglog_counter'", ",", "cycle_time", "=", "5", ",", "start_time", "=", "None", ",", "window", "=", "...
Generate a new HyperLogLogCounter. Useful for approximating extremely large counts of unique items @param redis_conn: A premade redis connection (overrides host and port) @param host: the redis host @param port: the redis port @param key: the key for your stats collection @param cycle_time: how often to check for expiring counts @param start_time: the time to start valid collection @param window: how long to collect data for in seconds (if rolling) @param roll: Roll the window after it expires, to continue collecting on a new date based key. @keep_max: If rolling the static window, the max number of prior windows to keep
[ "Generate", "a", "new", "HyperLogLogCounter", ".", "Useful", "for", "approximating", "extremely", "large", "counts", "of", "unique", "items" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/stats_collector.py#L143-L167
train
215,500
istresearch/scrapy-cluster
utils/scutils/stats_collector.py
AbstractCounter.setup
def setup(self, redis_conn=None, host='localhost', port=6379): ''' Set up the redis connection ''' if redis_conn is None: if host is not None and port is not None: self.redis_conn = redis.Redis(host=host, port=port) else: raise Exception("Please specify some form of connection " "to Redis") else: self.redis_conn = redis_conn self.redis_conn.info()
python
def setup(self, redis_conn=None, host='localhost', port=6379): ''' Set up the redis connection ''' if redis_conn is None: if host is not None and port is not None: self.redis_conn = redis.Redis(host=host, port=port) else: raise Exception("Please specify some form of connection " "to Redis") else: self.redis_conn = redis_conn self.redis_conn.info()
[ "def", "setup", "(", "self", ",", "redis_conn", "=", "None", ",", "host", "=", "'localhost'", ",", "port", "=", "6379", ")", ":", "if", "redis_conn", "is", "None", ":", "if", "host", "is", "not", "None", "and", "port", "is", "not", "None", ":", "se...
Set up the redis connection
[ "Set", "up", "the", "redis", "connection" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/stats_collector.py#L206-L219
train
215,501
istresearch/scrapy-cluster
utils/scutils/stats_collector.py
ThreadedCounter.setup
def setup(self, redis_conn=None, host='localhost', port=6379): ''' Set up the counting manager class @param redis_conn: A premade redis connection (overrides host and port) @param host: the redis host @param port: the redis port ''' AbstractCounter.setup(self, redis_conn=redis_conn, host=host, port=port) self._threaded_start()
python
def setup(self, redis_conn=None, host='localhost', port=6379): ''' Set up the counting manager class @param redis_conn: A premade redis connection (overrides host and port) @param host: the redis host @param port: the redis port ''' AbstractCounter.setup(self, redis_conn=redis_conn, host=host, port=port) self._threaded_start()
[ "def", "setup", "(", "self", ",", "redis_conn", "=", "None", ",", "host", "=", "'localhost'", ",", "port", "=", "6379", ")", ":", "AbstractCounter", ".", "setup", "(", "self", ",", "redis_conn", "=", "redis_conn", ",", "host", "=", "host", ",", "port",...
Set up the counting manager class @param redis_conn: A premade redis connection (overrides host and port) @param host: the redis host @param port: the redis port
[ "Set", "up", "the", "counting", "manager", "class" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/stats_collector.py#L300-L311
train
215,502
istresearch/scrapy-cluster
utils/scutils/stats_collector.py
ThreadedCounter._threaded_start
def _threaded_start(self): ''' Spawns a worker thread to do the expiration checks ''' self.active = True self.thread = Thread(target=self._main_loop) self.thread.setDaemon(True) self.thread.start()
python
def _threaded_start(self): ''' Spawns a worker thread to do the expiration checks ''' self.active = True self.thread = Thread(target=self._main_loop) self.thread.setDaemon(True) self.thread.start()
[ "def", "_threaded_start", "(", "self", ")", ":", "self", ".", "active", "=", "True", "self", ".", "thread", "=", "Thread", "(", "target", "=", "self", ".", "_main_loop", ")", "self", ".", "thread", ".", "setDaemon", "(", "True", ")", "self", ".", "th...
Spawns a worker thread to do the expiration checks
[ "Spawns", "a", "worker", "thread", "to", "do", "the", "expiration", "checks" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/stats_collector.py#L313-L320
train
215,503
istresearch/scrapy-cluster
utils/scutils/stats_collector.py
ThreadedCounter._main_loop
def _main_loop(self): ''' Main loop for the stats collector ''' while self.active: self.expire() if self.roll and self.is_expired(): self.start_time = self.start_time + self.window self._set_key() self.purge_old() time.sleep(self.cycle_time) self._clean_up()
python
def _main_loop(self): ''' Main loop for the stats collector ''' while self.active: self.expire() if self.roll and self.is_expired(): self.start_time = self.start_time + self.window self._set_key() self.purge_old() time.sleep(self.cycle_time) self._clean_up()
[ "def", "_main_loop", "(", "self", ")", ":", "while", "self", ".", "active", ":", "self", ".", "expire", "(", ")", "if", "self", ".", "roll", "and", "self", ".", "is_expired", "(", ")", ":", "self", ".", "start_time", "=", "self", ".", "start_time", ...
Main loop for the stats collector
[ "Main", "loop", "for", "the", "stats", "collector" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/stats_collector.py#L329-L340
train
215,504
istresearch/scrapy-cluster
utils/scutils/stats_collector.py
ThreadedCounter._set_key
def _set_key(self): ''' sets the final key to be used currently ''' if self.roll: self.date = time.strftime(self.date_format, time.gmtime(self.start_time)) self.final_key = '{}:{}'.format(self.key, self.date) else: self.final_key = self.key
python
def _set_key(self): ''' sets the final key to be used currently ''' if self.roll: self.date = time.strftime(self.date_format, time.gmtime(self.start_time)) self.final_key = '{}:{}'.format(self.key, self.date) else: self.final_key = self.key
[ "def", "_set_key", "(", "self", ")", ":", "if", "self", ".", "roll", ":", "self", ".", "date", "=", "time", ".", "strftime", "(", "self", ".", "date_format", ",", "time", ".", "gmtime", "(", "self", ".", "start_time", ")", ")", "self", ".", "final_...
sets the final key to be used currently
[ "sets", "the", "final", "key", "to", "be", "used", "currently" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/stats_collector.py#L348-L358
train
215,505
istresearch/scrapy-cluster
utils/scutils/stats_collector.py
ThreadedCounter.is_expired
def is_expired(self): ''' Returns true if the time is beyond the window ''' if self.window is not None: return (self._time() - self.start_time) >= self.window return False
python
def is_expired(self): ''' Returns true if the time is beyond the window ''' if self.window is not None: return (self._time() - self.start_time) >= self.window return False
[ "def", "is_expired", "(", "self", ")", ":", "if", "self", ".", "window", "is", "not", "None", ":", "return", "(", "self", ".", "_time", "(", ")", "-", "self", ".", "start_time", ")", ">=", "self", ".", "window", "return", "False" ]
Returns true if the time is beyond the window
[ "Returns", "true", "if", "the", "time", "is", "beyond", "the", "window" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/stats_collector.py#L360-L366
train
215,506
istresearch/scrapy-cluster
utils/scutils/stats_collector.py
ThreadedCounter.purge_old
def purge_old(self): ''' Removes keys that are beyond our keep_max limit ''' if self.keep_max is not None: keys = self.redis_conn.keys(self.get_key() + ':*') keys.sort(reverse=True) while len(keys) > self.keep_max: key = keys.pop() self.redis_conn.delete(key)
python
def purge_old(self): ''' Removes keys that are beyond our keep_max limit ''' if self.keep_max is not None: keys = self.redis_conn.keys(self.get_key() + ':*') keys.sort(reverse=True) while len(keys) > self.keep_max: key = keys.pop() self.redis_conn.delete(key)
[ "def", "purge_old", "(", "self", ")", ":", "if", "self", ".", "keep_max", "is", "not", "None", ":", "keys", "=", "self", ".", "redis_conn", ".", "keys", "(", "self", ".", "get_key", "(", ")", "+", "':*'", ")", "keys", ".", "sort", "(", "reverse", ...
Removes keys that are beyond our keep_max limit
[ "Removes", "keys", "that", "are", "beyond", "our", "keep_max", "limit" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/stats_collector.py#L368-L377
train
215,507
istresearch/scrapy-cluster
utils/scutils/redis_queue.py
Base._encode_item
def _encode_item(self, item): ''' Encode an item object @requires: The object be serializable ''' if self.encoding.__name__ == 'pickle': return self.encoding.dumps(item, protocol=-1) else: return self.encoding.dumps(item)
python
def _encode_item(self, item): ''' Encode an item object @requires: The object be serializable ''' if self.encoding.__name__ == 'pickle': return self.encoding.dumps(item, protocol=-1) else: return self.encoding.dumps(item)
[ "def", "_encode_item", "(", "self", ",", "item", ")", ":", "if", "self", ".", "encoding", ".", "__name__", "==", "'pickle'", ":", "return", "self", ".", "encoding", ".", "dumps", "(", "item", ",", "protocol", "=", "-", "1", ")", "else", ":", "return"...
Encode an item object @requires: The object be serializable
[ "Encode", "an", "item", "object" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/redis_queue.py#L35-L44
train
215,508
istresearch/scrapy-cluster
utils/scutils/zookeeper_watcher.py
ZookeeperWatcher.threaded_start
def threaded_start(self, no_init=False): ''' Spawns a worker thread to set up the zookeeper connection ''' thread = Thread(target=self.init_connections, kwargs={ 'no_init': no_init}) thread.setDaemon(True) thread.start() thread.join()
python
def threaded_start(self, no_init=False): ''' Spawns a worker thread to set up the zookeeper connection ''' thread = Thread(target=self.init_connections, kwargs={ 'no_init': no_init}) thread.setDaemon(True) thread.start() thread.join()
[ "def", "threaded_start", "(", "self", ",", "no_init", "=", "False", ")", ":", "thread", "=", "Thread", "(", "target", "=", "self", ".", "init_connections", ",", "kwargs", "=", "{", "'no_init'", ":", "no_init", "}", ")", "thread", ".", "setDaemon", "(", ...
Spawns a worker thread to set up the zookeeper connection
[ "Spawns", "a", "worker", "thread", "to", "set", "up", "the", "zookeeper", "connection" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/zookeeper_watcher.py#L77-L85
train
215,509
istresearch/scrapy-cluster
utils/scutils/zookeeper_watcher.py
ZookeeperWatcher.init_connections
def init_connections(self, no_init=False): ''' Sets up the initial Kazoo Client and watches ''' success = False self.set_valid(False) if not no_init: if self.zoo_client: self.zoo_client.remove_listener(self.state_listener) self.old_data = '' self.old_pointed = '' while not success: try: if self.zoo_client is None: self.zoo_client = KazooClient(hosts=self.hosts) self.zoo_client.start() else: # self.zoo_client.stop() self.zoo_client._connection.connection_stopped.set() self.zoo_client.close() self.zoo_client = KazooClient(hosts=self.hosts) self.zoo_client.start() except Exception as e: log.error("ZKWatcher Exception: " + e.message) sleep(1) continue self.setup() success = self.update_file(self.my_file) sleep(5) else: self.setup() self.update_file(self.my_file)
python
def init_connections(self, no_init=False): ''' Sets up the initial Kazoo Client and watches ''' success = False self.set_valid(False) if not no_init: if self.zoo_client: self.zoo_client.remove_listener(self.state_listener) self.old_data = '' self.old_pointed = '' while not success: try: if self.zoo_client is None: self.zoo_client = KazooClient(hosts=self.hosts) self.zoo_client.start() else: # self.zoo_client.stop() self.zoo_client._connection.connection_stopped.set() self.zoo_client.close() self.zoo_client = KazooClient(hosts=self.hosts) self.zoo_client.start() except Exception as e: log.error("ZKWatcher Exception: " + e.message) sleep(1) continue self.setup() success = self.update_file(self.my_file) sleep(5) else: self.setup() self.update_file(self.my_file)
[ "def", "init_connections", "(", "self", ",", "no_init", "=", "False", ")", ":", "success", "=", "False", "self", ".", "set_valid", "(", "False", ")", "if", "not", "no_init", ":", "if", "self", ".", "zoo_client", ":", "self", ".", "zoo_client", ".", "re...
Sets up the initial Kazoo Client and watches
[ "Sets", "up", "the", "initial", "Kazoo", "Client", "and", "watches" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/zookeeper_watcher.py#L87-L121
train
215,510
istresearch/scrapy-cluster
utils/scutils/zookeeper_watcher.py
ZookeeperWatcher.setup
def setup(self): ''' Ensures the path to the watched file exists and we have a state listener ''' self.zoo_client.add_listener(self.state_listener) if self.ensure: self.zoo_client.ensure_path(self.my_file)
python
def setup(self): ''' Ensures the path to the watched file exists and we have a state listener ''' self.zoo_client.add_listener(self.state_listener) if self.ensure: self.zoo_client.ensure_path(self.my_file)
[ "def", "setup", "(", "self", ")", ":", "self", ".", "zoo_client", ".", "add_listener", "(", "self", ".", "state_listener", ")", "if", "self", ".", "ensure", ":", "self", ".", "zoo_client", ".", "ensure_path", "(", "self", ".", "my_file", ")" ]
Ensures the path to the watched file exists and we have a state listener
[ "Ensures", "the", "path", "to", "the", "watched", "file", "exists", "and", "we", "have", "a", "state", "listener" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/zookeeper_watcher.py#L123-L131
train
215,511
istresearch/scrapy-cluster
utils/scutils/zookeeper_watcher.py
ZookeeperWatcher.state_listener
def state_listener(self, state): ''' Restarts the session if we get anything besides CONNECTED ''' if state == KazooState.SUSPENDED: self.set_valid(False) self.call_error(self.BAD_CONNECTION) elif state == KazooState.LOST and not self.do_not_restart: self.threaded_start() elif state == KazooState.CONNECTED: # This is going to throw a SUSPENDED kazoo error # which will cause the sessions to be wiped and re established. # Used b/c of massive connection pool issues self.zoo_client.stop()
python
def state_listener(self, state): ''' Restarts the session if we get anything besides CONNECTED ''' if state == KazooState.SUSPENDED: self.set_valid(False) self.call_error(self.BAD_CONNECTION) elif state == KazooState.LOST and not self.do_not_restart: self.threaded_start() elif state == KazooState.CONNECTED: # This is going to throw a SUSPENDED kazoo error # which will cause the sessions to be wiped and re established. # Used b/c of massive connection pool issues self.zoo_client.stop()
[ "def", "state_listener", "(", "self", ",", "state", ")", ":", "if", "state", "==", "KazooState", ".", "SUSPENDED", ":", "self", ".", "set_valid", "(", "False", ")", "self", ".", "call_error", "(", "self", ".", "BAD_CONNECTION", ")", "elif", "state", "=="...
Restarts the session if we get anything besides CONNECTED
[ "Restarts", "the", "session", "if", "we", "get", "anything", "besides", "CONNECTED" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/zookeeper_watcher.py#L133-L146
train
215,512
istresearch/scrapy-cluster
utils/scutils/zookeeper_watcher.py
ZookeeperWatcher.close
def close(self, kill_restart=True): ''' Use when you would like to close everything down @param kill_restart= Prevent kazoo restarting from occurring ''' self.do_not_restart = kill_restart self.zoo_client.stop() self.zoo_client.close()
python
def close(self, kill_restart=True): ''' Use when you would like to close everything down @param kill_restart= Prevent kazoo restarting from occurring ''' self.do_not_restart = kill_restart self.zoo_client.stop() self.zoo_client.close()
[ "def", "close", "(", "self", ",", "kill_restart", "=", "True", ")", ":", "self", ".", "do_not_restart", "=", "kill_restart", "self", ".", "zoo_client", ".", "stop", "(", ")", "self", ".", "zoo_client", ".", "close", "(", ")" ]
Use when you would like to close everything down @param kill_restart= Prevent kazoo restarting from occurring
[ "Use", "when", "you", "would", "like", "to", "close", "everything", "down" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/zookeeper_watcher.py#L166-L173
train
215,513
istresearch/scrapy-cluster
utils/scutils/zookeeper_watcher.py
ZookeeperWatcher.get_file_contents
def get_file_contents(self, pointer=False): ''' Gets any file contents you care about. Defaults to the main file @param pointer: The the contents of the file pointer, not the pointed at file @return: A string of the contents ''' if self.pointer: if pointer: return self.old_pointed else: return self.old_data else: return self.old_data
python
def get_file_contents(self, pointer=False): ''' Gets any file contents you care about. Defaults to the main file @param pointer: The the contents of the file pointer, not the pointed at file @return: A string of the contents ''' if self.pointer: if pointer: return self.old_pointed else: return self.old_data else: return self.old_data
[ "def", "get_file_contents", "(", "self", ",", "pointer", "=", "False", ")", ":", "if", "self", ".", "pointer", ":", "if", "pointer", ":", "return", "self", ".", "old_pointed", "else", ":", "return", "self", ".", "old_data", "else", ":", "return", "self",...
Gets any file contents you care about. Defaults to the main file @param pointer: The the contents of the file pointer, not the pointed at file @return: A string of the contents
[ "Gets", "any", "file", "contents", "you", "care", "about", ".", "Defaults", "to", "the", "main", "file" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/zookeeper_watcher.py#L175-L188
train
215,514
istresearch/scrapy-cluster
utils/scutils/zookeeper_watcher.py
ZookeeperWatcher.update_file
def update_file(self, path): ''' Updates the file watcher and calls the appropriate method for results @return: False if we need to keep trying the connection ''' try: # grab the file result, stat = self.zoo_client.get(path, watch=self.watch_file) except ZookeeperError: self.set_valid(False) self.call_error(self.INVALID_GET) return False if self.pointer: if result is not None and len(result) > 0: self.pointed_at_expired = False # file is a pointer, go update and watch other file self.point_path = result if self.compare_pointer(result): self.update_pointed() else: self.pointed_at_expired = True self.old_pointed = '' self.old_data = '' self.set_valid(False) self.call_error(self.INVALID_PATH) else: # file is not a pointer, return contents if self.compare_data(result): self.call_config(result) self.set_valid(True) return True
python
def update_file(self, path): ''' Updates the file watcher and calls the appropriate method for results @return: False if we need to keep trying the connection ''' try: # grab the file result, stat = self.zoo_client.get(path, watch=self.watch_file) except ZookeeperError: self.set_valid(False) self.call_error(self.INVALID_GET) return False if self.pointer: if result is not None and len(result) > 0: self.pointed_at_expired = False # file is a pointer, go update and watch other file self.point_path = result if self.compare_pointer(result): self.update_pointed() else: self.pointed_at_expired = True self.old_pointed = '' self.old_data = '' self.set_valid(False) self.call_error(self.INVALID_PATH) else: # file is not a pointer, return contents if self.compare_data(result): self.call_config(result) self.set_valid(True) return True
[ "def", "update_file", "(", "self", ",", "path", ")", ":", "try", ":", "# grab the file", "result", ",", "stat", "=", "self", ".", "zoo_client", ".", "get", "(", "path", ",", "watch", "=", "self", ".", "watch_file", ")", "except", "ZookeeperError", ":", ...
Updates the file watcher and calls the appropriate method for results @return: False if we need to keep trying the connection
[ "Updates", "the", "file", "watcher", "and", "calls", "the", "appropriate", "method", "for", "results" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/zookeeper_watcher.py#L197-L229
train
215,515
istresearch/scrapy-cluster
utils/scutils/zookeeper_watcher.py
ZookeeperWatcher.update_pointed
def update_pointed(self): ''' Grabs the latest file contents based on the pointer uri ''' # only grab file if our pointer is still good (not None) if not self.pointed_at_expired: try: conf_string, stat2 = self.zoo_client.get(self.point_path, watch=self.watch_pointed) except ZookeeperError: self.old_data = '' self.set_valid(False) self.pointed_at_expired = True self.call_error(self.INVALID_PATH) return if self.compare_data(conf_string): self.call_config(conf_string) self.set_valid(True)
python
def update_pointed(self): ''' Grabs the latest file contents based on the pointer uri ''' # only grab file if our pointer is still good (not None) if not self.pointed_at_expired: try: conf_string, stat2 = self.zoo_client.get(self.point_path, watch=self.watch_pointed) except ZookeeperError: self.old_data = '' self.set_valid(False) self.pointed_at_expired = True self.call_error(self.INVALID_PATH) return if self.compare_data(conf_string): self.call_config(conf_string) self.set_valid(True)
[ "def", "update_pointed", "(", "self", ")", ":", "# only grab file if our pointer is still good (not None)", "if", "not", "self", ".", "pointed_at_expired", ":", "try", ":", "conf_string", ",", "stat2", "=", "self", ".", "zoo_client", ".", "get", "(", "self", ".", ...
Grabs the latest file contents based on the pointer uri
[ "Grabs", "the", "latest", "file", "contents", "based", "on", "the", "pointer", "uri" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/zookeeper_watcher.py#L237-L255
train
215,516
istresearch/scrapy-cluster
utils/scutils/zookeeper_watcher.py
ZookeeperWatcher.set_valid
def set_valid(self, boolean): ''' Sets the state and calls the change if needed @param bool: The state (true or false) ''' old_state = self.is_valid() self.valid_file = boolean if old_state != self.valid_file: self.call_valid(self.valid_file)
python
def set_valid(self, boolean): ''' Sets the state and calls the change if needed @param bool: The state (true or false) ''' old_state = self.is_valid() self.valid_file = boolean if old_state != self.valid_file: self.call_valid(self.valid_file)
[ "def", "set_valid", "(", "self", ",", "boolean", ")", ":", "old_state", "=", "self", ".", "is_valid", "(", ")", "self", ".", "valid_file", "=", "boolean", "if", "old_state", "!=", "self", ".", "valid_file", ":", "self", ".", "call_valid", "(", "self", ...
Sets the state and calls the change if needed @param bool: The state (true or false)
[ "Sets", "the", "state", "and", "calls", "the", "change", "if", "needed" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/zookeeper_watcher.py#L257-L266
train
215,517
istresearch/scrapy-cluster
kafka-monitor/plugins/zookeeper_handler.py
ZookeeperHandler.setup
def setup(self, settings): ''' Setup redis and tldextract ''' self.extract = tldextract.TLDExtract() self.redis_conn = redis.Redis(host=settings['REDIS_HOST'], port=settings['REDIS_PORT'], db=settings.get('REDIS_DB')) try: self.redis_conn.info() self.logger.debug("Connected to Redis in ZookeeperHandler") except ConnectionError: self.logger.error("Failed to connect to Redis in ZookeeperHandler") # plugin is essential to functionality sys.exit(1)
python
def setup(self, settings): ''' Setup redis and tldextract ''' self.extract = tldextract.TLDExtract() self.redis_conn = redis.Redis(host=settings['REDIS_HOST'], port=settings['REDIS_PORT'], db=settings.get('REDIS_DB')) try: self.redis_conn.info() self.logger.debug("Connected to Redis in ZookeeperHandler") except ConnectionError: self.logger.error("Failed to connect to Redis in ZookeeperHandler") # plugin is essential to functionality sys.exit(1)
[ "def", "setup", "(", "self", ",", "settings", ")", ":", "self", ".", "extract", "=", "tldextract", ".", "TLDExtract", "(", ")", "self", ".", "redis_conn", "=", "redis", ".", "Redis", "(", "host", "=", "settings", "[", "'REDIS_HOST'", "]", ",", "port", ...
Setup redis and tldextract
[ "Setup", "redis", "and", "tldextract" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/kafka-monitor/plugins/zookeeper_handler.py#L14-L29
train
215,518
istresearch/scrapy-cluster
redis-monitor/plugins/base_monitor.py
BaseMonitor.get_log_dict
def get_log_dict(self, action, appid, spiderid=None, uuid=None, crawlid=None): ''' Returns a basic dictionary for logging @param action: the action taken by the redis monitor @param spiderid: the spider id @param appid: the application id @param uuid: a unique id of the request @param crawlid: a unique crawl id of the request ''' extras = {} extras['action'] = action extras['appid'] = appid if spiderid is not None: extras['spiderid'] = spiderid if uuid is not None: extras['uuid'] = uuid if crawlid is not None: extras['crawlid'] = crawlid return extras
python
def get_log_dict(self, action, appid, spiderid=None, uuid=None, crawlid=None): ''' Returns a basic dictionary for logging @param action: the action taken by the redis monitor @param spiderid: the spider id @param appid: the application id @param uuid: a unique id of the request @param crawlid: a unique crawl id of the request ''' extras = {} extras['action'] = action extras['appid'] = appid if spiderid is not None: extras['spiderid'] = spiderid if uuid is not None: extras['uuid'] = uuid if crawlid is not None: extras['crawlid'] = crawlid return extras
[ "def", "get_log_dict", "(", "self", ",", "action", ",", "appid", ",", "spiderid", "=", "None", ",", "uuid", "=", "None", ",", "crawlid", "=", "None", ")", ":", "extras", "=", "{", "}", "extras", "[", "'action'", "]", "=", "action", "extras", "[", "...
Returns a basic dictionary for logging @param action: the action taken by the redis monitor @param spiderid: the spider id @param appid: the application id @param uuid: a unique id of the request @param crawlid: a unique crawl id of the request
[ "Returns", "a", "basic", "dictionary", "for", "logging" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/plugins/base_monitor.py#L71-L91
train
215,519
istresearch/scrapy-cluster
redis-monitor/redis_monitor.py
RedisMonitor._load_plugins
def _load_plugins(self): ''' Sets up all plugins and defaults ''' plugins = self.settings['PLUGINS'] self.plugins_dict = {} for key in plugins: # skip loading the plugin if its value is None if plugins[key] is None: continue # valid plugin, import and setup self.logger.debug("Trying to load plugin {cls}" .format(cls=key)) the_class = self.import_class(key) instance = the_class() instance.redis_conn = self.redis_conn instance._set_logger(self.logger) if not self.unit_test: instance.setup(self.settings) the_regex = instance.regex mini = {} mini['instance'] = instance if the_regex is None: raise ImportError() # continue mini['regex'] = the_regex self.plugins_dict[plugins[key]] = mini self.plugins_dict = OrderedDict(sorted(list(self.plugins_dict.items()), key=lambda t: t[0]))
python
def _load_plugins(self): ''' Sets up all plugins and defaults ''' plugins = self.settings['PLUGINS'] self.plugins_dict = {} for key in plugins: # skip loading the plugin if its value is None if plugins[key] is None: continue # valid plugin, import and setup self.logger.debug("Trying to load plugin {cls}" .format(cls=key)) the_class = self.import_class(key) instance = the_class() instance.redis_conn = self.redis_conn instance._set_logger(self.logger) if not self.unit_test: instance.setup(self.settings) the_regex = instance.regex mini = {} mini['instance'] = instance if the_regex is None: raise ImportError() # continue mini['regex'] = the_regex self.plugins_dict[plugins[key]] = mini self.plugins_dict = OrderedDict(sorted(list(self.plugins_dict.items()), key=lambda t: t[0]))
[ "def", "_load_plugins", "(", "self", ")", ":", "plugins", "=", "self", ".", "settings", "[", "'PLUGINS'", "]", "self", ".", "plugins_dict", "=", "{", "}", "for", "key", "in", "plugins", ":", "# skip loading the plugin if its value is None", "if", "plugins", "[...
Sets up all plugins and defaults
[ "Sets", "up", "all", "plugins", "and", "defaults" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/redis_monitor.py#L87-L119
train
215,520
istresearch/scrapy-cluster
redis-monitor/redis_monitor.py
RedisMonitor._main_loop
def _main_loop(self): ''' The internal while true main loop for the redis monitor ''' self.logger.debug("Running main loop") old_time = 0 while True: for plugin_key in self.plugins_dict: obj = self.plugins_dict[plugin_key] self._process_plugin(obj) if self.settings['STATS_DUMP'] != 0: new_time = int(old_div(time.time(), self.settings['STATS_DUMP'])) # only log every X seconds if new_time != old_time: self._dump_stats() if self.settings['STATS_DUMP_CRAWL']: self._dump_crawl_stats() if self.settings['STATS_DUMP_QUEUE']: self._dump_queue_stats() old_time = new_time self._report_self() time.sleep(self.settings['SLEEP_TIME'])
python
def _main_loop(self): ''' The internal while true main loop for the redis monitor ''' self.logger.debug("Running main loop") old_time = 0 while True: for plugin_key in self.plugins_dict: obj = self.plugins_dict[plugin_key] self._process_plugin(obj) if self.settings['STATS_DUMP'] != 0: new_time = int(old_div(time.time(), self.settings['STATS_DUMP'])) # only log every X seconds if new_time != old_time: self._dump_stats() if self.settings['STATS_DUMP_CRAWL']: self._dump_crawl_stats() if self.settings['STATS_DUMP_QUEUE']: self._dump_queue_stats() old_time = new_time self._report_self() time.sleep(self.settings['SLEEP_TIME'])
[ "def", "_main_loop", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Running main loop\"", ")", "old_time", "=", "0", "while", "True", ":", "for", "plugin_key", "in", "self", ".", "plugins_dict", ":", "obj", "=", "self", ".", "plugins...
The internal while true main loop for the redis monitor
[ "The", "internal", "while", "true", "main", "loop", "for", "the", "redis", "monitor" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/redis_monitor.py#L127-L152
train
215,521
istresearch/scrapy-cluster
redis-monitor/redis_monitor.py
RedisMonitor._process_plugin
def _process_plugin(self, plugin): ''' Logic to handle each plugin that is active @param plugin: a plugin dict object ''' instance = plugin['instance'] regex = plugin['regex'] for key in self.redis_conn.scan_iter(match=regex): # acquire lock lock = self._create_lock_object(key) try: if lock.acquire(blocking=False): val = self.redis_conn.get(key) self._process_key_val(instance, key, val) except Exception: self.logger.error(traceback.format_exc()) self._increment_fail_stat('{k}:{v}'.format(k=key, v=val)) self._process_failures(key) # remove lock regardless of if exception or was handled ok if lock._held: self.logger.debug("releasing lock") lock.release()
python
def _process_plugin(self, plugin): ''' Logic to handle each plugin that is active @param plugin: a plugin dict object ''' instance = plugin['instance'] regex = plugin['regex'] for key in self.redis_conn.scan_iter(match=regex): # acquire lock lock = self._create_lock_object(key) try: if lock.acquire(blocking=False): val = self.redis_conn.get(key) self._process_key_val(instance, key, val) except Exception: self.logger.error(traceback.format_exc()) self._increment_fail_stat('{k}:{v}'.format(k=key, v=val)) self._process_failures(key) # remove lock regardless of if exception or was handled ok if lock._held: self.logger.debug("releasing lock") lock.release()
[ "def", "_process_plugin", "(", "self", ",", "plugin", ")", ":", "instance", "=", "plugin", "[", "'instance'", "]", "regex", "=", "plugin", "[", "'regex'", "]", "for", "key", "in", "self", ".", "redis_conn", ".", "scan_iter", "(", "match", "=", "regex", ...
Logic to handle each plugin that is active @param plugin: a plugin dict object
[ "Logic", "to", "handle", "each", "plugin", "that", "is", "active" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/redis_monitor.py#L154-L179
train
215,522
istresearch/scrapy-cluster
redis-monitor/redis_monitor.py
RedisMonitor._create_lock_object
def _create_lock_object(self, key): ''' Returns a lock object, split for testing ''' return redis_lock.Lock(self.redis_conn, key, expire=self.settings['REDIS_LOCK_EXPIRATION'], auto_renewal=True)
python
def _create_lock_object(self, key): ''' Returns a lock object, split for testing ''' return redis_lock.Lock(self.redis_conn, key, expire=self.settings['REDIS_LOCK_EXPIRATION'], auto_renewal=True)
[ "def", "_create_lock_object", "(", "self", ",", "key", ")", ":", "return", "redis_lock", ".", "Lock", "(", "self", ".", "redis_conn", ",", "key", ",", "expire", "=", "self", ".", "settings", "[", "'REDIS_LOCK_EXPIRATION'", "]", ",", "auto_renewal", "=", "T...
Returns a lock object, split for testing
[ "Returns", "a", "lock", "object", "split", "for", "testing" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/redis_monitor.py#L181-L187
train
215,523
istresearch/scrapy-cluster
redis-monitor/redis_monitor.py
RedisMonitor._process_failures
def _process_failures(self, key): ''' Handles the retrying of the failed key ''' if self.settings['RETRY_FAILURES']: self.logger.debug("going to retry failure") # get the current failure count failkey = self._get_fail_key(key) current = self.redis_conn.get(failkey) if current is None: current = 0 else: current = int(current) if current < self.settings['RETRY_FAILURES_MAX']: self.logger.debug("Incr fail key") current += 1 self.redis_conn.set(failkey, current) else: self.logger.error("Could not process action within" " failure limit") self.redis_conn.delete(failkey) self.redis_conn.delete(key)
python
def _process_failures(self, key): ''' Handles the retrying of the failed key ''' if self.settings['RETRY_FAILURES']: self.logger.debug("going to retry failure") # get the current failure count failkey = self._get_fail_key(key) current = self.redis_conn.get(failkey) if current is None: current = 0 else: current = int(current) if current < self.settings['RETRY_FAILURES_MAX']: self.logger.debug("Incr fail key") current += 1 self.redis_conn.set(failkey, current) else: self.logger.error("Could not process action within" " failure limit") self.redis_conn.delete(failkey) self.redis_conn.delete(key)
[ "def", "_process_failures", "(", "self", ",", "key", ")", ":", "if", "self", ".", "settings", "[", "'RETRY_FAILURES'", "]", ":", "self", ".", "logger", ".", "debug", "(", "\"going to retry failure\"", ")", "# get the current failure count", "failkey", "=", "self...
Handles the retrying of the failed key
[ "Handles", "the", "retrying", "of", "the", "failed", "key" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/redis_monitor.py#L195-L216
train
215,524
istresearch/scrapy-cluster
redis-monitor/redis_monitor.py
RedisMonitor._setup_stats
def _setup_stats(self): ''' Sets up the stats ''' # stats setup self.stats_dict = {} if self.settings['STATS_TOTAL']: self._setup_stats_total() if self.settings['STATS_PLUGINS']: self._setup_stats_plugins()
python
def _setup_stats(self): ''' Sets up the stats ''' # stats setup self.stats_dict = {} if self.settings['STATS_TOTAL']: self._setup_stats_total() if self.settings['STATS_PLUGINS']: self._setup_stats_plugins()
[ "def", "_setup_stats", "(", "self", ")", ":", "# stats setup", "self", ".", "stats_dict", "=", "{", "}", "if", "self", ".", "settings", "[", "'STATS_TOTAL'", "]", ":", "self", ".", "_setup_stats_total", "(", ")", "if", "self", ".", "settings", "[", "'STA...
Sets up the stats
[ "Sets", "up", "the", "stats" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/redis_monitor.py#L239-L250
train
215,525
istresearch/scrapy-cluster
redis-monitor/redis_monitor.py
RedisMonitor._setup_stats_plugins
def _setup_stats_plugins(self): ''' Sets up the plugin stats collectors ''' self.stats_dict['plugins'] = {} for key in self.plugins_dict: plugin_name = self.plugins_dict[key]['instance'].__class__.__name__ temp_key = 'stats:redis-monitor:{p}'.format(p=plugin_name) self.stats_dict['plugins'][plugin_name] = {} for item in self.settings['STATS_TIMES']: try: time = getattr(StatsCollector, item) self.stats_dict['plugins'][plugin_name][time] = StatsCollector \ .get_rolling_time_window( redis_conn=self.redis_conn, key='{k}:{t}'.format(k=temp_key, t=time), window=time, cycle_time=self.settings['STATS_CYCLE']) self.logger.debug("Set up {p} plugin Stats Collector '{i}'"\ .format(p=plugin_name, i=item)) except AttributeError as e: self.logger.warning("Unable to find Stats Time '{s}'"\ .format(s=item)) total = StatsCollector.get_hll_counter(redis_conn=self.redis_conn, key='{k}:lifetime'.format(k=temp_key), cycle_time=self.settings['STATS_CYCLE'], roll=False) self.logger.debug("Set up {p} plugin Stats Collector 'lifetime'"\ .format(p=plugin_name)) self.stats_dict['plugins'][plugin_name]['lifetime'] = total
python
def _setup_stats_plugins(self): ''' Sets up the plugin stats collectors ''' self.stats_dict['plugins'] = {} for key in self.plugins_dict: plugin_name = self.plugins_dict[key]['instance'].__class__.__name__ temp_key = 'stats:redis-monitor:{p}'.format(p=plugin_name) self.stats_dict['plugins'][plugin_name] = {} for item in self.settings['STATS_TIMES']: try: time = getattr(StatsCollector, item) self.stats_dict['plugins'][plugin_name][time] = StatsCollector \ .get_rolling_time_window( redis_conn=self.redis_conn, key='{k}:{t}'.format(k=temp_key, t=time), window=time, cycle_time=self.settings['STATS_CYCLE']) self.logger.debug("Set up {p} plugin Stats Collector '{i}'"\ .format(p=plugin_name, i=item)) except AttributeError as e: self.logger.warning("Unable to find Stats Time '{s}'"\ .format(s=item)) total = StatsCollector.get_hll_counter(redis_conn=self.redis_conn, key='{k}:lifetime'.format(k=temp_key), cycle_time=self.settings['STATS_CYCLE'], roll=False) self.logger.debug("Set up {p} plugin Stats Collector 'lifetime'"\ .format(p=plugin_name)) self.stats_dict['plugins'][plugin_name]['lifetime'] = total
[ "def", "_setup_stats_plugins", "(", "self", ")", ":", "self", ".", "stats_dict", "[", "'plugins'", "]", "=", "{", "}", "for", "key", "in", "self", ".", "plugins_dict", ":", "plugin_name", "=", "self", ".", "plugins_dict", "[", "key", "]", "[", "'instance...
Sets up the plugin stats collectors
[ "Sets", "up", "the", "plugin", "stats", "collectors" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/redis_monitor.py#L292-L322
train
215,526
istresearch/scrapy-cluster
redis-monitor/redis_monitor.py
RedisMonitor._dump_crawl_stats
def _dump_crawl_stats(self): ''' Dumps flattened crawling stats so the spiders do not have to ''' extras = {} spiders = {} spider_set = set() total_spider_count = 0 keys = self.redis_conn.keys('stats:crawler:*:*:*') for key in keys: # we only care about the spider elements = key.split(":") spider = elements[3] if spider not in spiders: spiders[spider] = 0 if len(elements) == 6: # got a time based stat response = elements[4] end = elements[5] final = '{s}_{r}_{e}'.format(s=spider, r=response, e=end) if end == 'lifetime': value = self.redis_conn.execute_command("PFCOUNT", key) else: value = self.redis_conn.zcard(key) extras[final] = value elif len(elements) == 5: # got a spider identifier spiders[spider] += 1 total_spider_count += 1 spider_set.add(spider) else: self.logger.warn("Unknown crawler stat key", {"key":key}) # simple counts extras['unique_spider_count'] = len(spider_set) extras['total_spider_count'] = total_spider_count for spider in spiders: extras['{k}_spider_count'.format(k=spider)] = spiders[spider] if not self.logger.json: self.logger.info('Crawler Stats Dump:\n{0}'.format( json.dumps(extras, indent=4, sort_keys=True))) else: self.logger.info('Crawler Stats Dump', extra=extras)
python
def _dump_crawl_stats(self): ''' Dumps flattened crawling stats so the spiders do not have to ''' extras = {} spiders = {} spider_set = set() total_spider_count = 0 keys = self.redis_conn.keys('stats:crawler:*:*:*') for key in keys: # we only care about the spider elements = key.split(":") spider = elements[3] if spider not in spiders: spiders[spider] = 0 if len(elements) == 6: # got a time based stat response = elements[4] end = elements[5] final = '{s}_{r}_{e}'.format(s=spider, r=response, e=end) if end == 'lifetime': value = self.redis_conn.execute_command("PFCOUNT", key) else: value = self.redis_conn.zcard(key) extras[final] = value elif len(elements) == 5: # got a spider identifier spiders[spider] += 1 total_spider_count += 1 spider_set.add(spider) else: self.logger.warn("Unknown crawler stat key", {"key":key}) # simple counts extras['unique_spider_count'] = len(spider_set) extras['total_spider_count'] = total_spider_count for spider in spiders: extras['{k}_spider_count'.format(k=spider)] = spiders[spider] if not self.logger.json: self.logger.info('Crawler Stats Dump:\n{0}'.format( json.dumps(extras, indent=4, sort_keys=True))) else: self.logger.info('Crawler Stats Dump', extra=extras)
[ "def", "_dump_crawl_stats", "(", "self", ")", ":", "extras", "=", "{", "}", "spiders", "=", "{", "}", "spider_set", "=", "set", "(", ")", "total_spider_count", "=", "0", "keys", "=", "self", ".", "redis_conn", ".", "keys", "(", "'stats:crawler:*:*:*'", "...
Dumps flattened crawling stats so the spiders do not have to
[ "Dumps", "flattened", "crawling", "stats", "so", "the", "spiders", "do", "not", "have", "to" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/redis_monitor.py#L398-L451
train
215,527
istresearch/scrapy-cluster
redis-monitor/redis_monitor.py
RedisMonitor._dump_queue_stats
def _dump_queue_stats(self): ''' Dumps basic info about the queue lengths for the spider types ''' extras = {} keys = self.redis_conn.keys('*:*:queue') total_backlog = 0 for key in keys: elements = key.split(":") spider = elements[0] domain = elements[1] spider = 'queue_' + spider if spider not in extras: extras[spider] = {} extras[spider]['spider_backlog'] = 0 extras[spider]['num_domains'] = 0 count = self.redis_conn.zcard(key) total_backlog += count extras[spider]['spider_backlog'] += count extras[spider]['num_domains'] += 1 extras['total_backlog'] = total_backlog if not self.logger.json: self.logger.info('Queue Stats Dump:\n{0}'.format( json.dumps(extras, indent=4, sort_keys=True))) else: self.logger.info('Queue Stats Dump', extra=extras)
python
def _dump_queue_stats(self): ''' Dumps basic info about the queue lengths for the spider types ''' extras = {} keys = self.redis_conn.keys('*:*:queue') total_backlog = 0 for key in keys: elements = key.split(":") spider = elements[0] domain = elements[1] spider = 'queue_' + spider if spider not in extras: extras[spider] = {} extras[spider]['spider_backlog'] = 0 extras[spider]['num_domains'] = 0 count = self.redis_conn.zcard(key) total_backlog += count extras[spider]['spider_backlog'] += count extras[spider]['num_domains'] += 1 extras['total_backlog'] = total_backlog if not self.logger.json: self.logger.info('Queue Stats Dump:\n{0}'.format( json.dumps(extras, indent=4, sort_keys=True))) else: self.logger.info('Queue Stats Dump', extra=extras)
[ "def", "_dump_queue_stats", "(", "self", ")", ":", "extras", "=", "{", "}", "keys", "=", "self", ".", "redis_conn", ".", "keys", "(", "'*:*:queue'", ")", "total_backlog", "=", "0", "for", "key", "in", "keys", ":", "elements", "=", "key", ".", "split", ...
Dumps basic info about the queue lengths for the spider types
[ "Dumps", "basic", "info", "about", "the", "queue", "lengths", "for", "the", "spider", "types" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/redis_monitor.py#L453-L482
train
215,528
istresearch/scrapy-cluster
redis-monitor/redis_monitor.py
RedisMonitor.close
def close(self): ''' Closes the Redis Monitor and plugins ''' for plugin_key in self.plugins_dict: obj = self.plugins_dict[plugin_key] instance = obj['instance'] instance.close()
python
def close(self): ''' Closes the Redis Monitor and plugins ''' for plugin_key in self.plugins_dict: obj = self.plugins_dict[plugin_key] instance = obj['instance'] instance.close()
[ "def", "close", "(", "self", ")", ":", "for", "plugin_key", "in", "self", ".", "plugins_dict", ":", "obj", "=", "self", ".", "plugins_dict", "[", "plugin_key", "]", "instance", "=", "obj", "[", "'instance'", "]", "instance", ".", "close", "(", ")" ]
Closes the Redis Monitor and plugins
[ "Closes", "the", "Redis", "Monitor", "and", "plugins" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/redis_monitor.py#L494-L501
train
215,529
istresearch/scrapy-cluster
redis-monitor/plugins/stats_monitor.py
StatsMonitor.get_all_stats
def get_all_stats(self): ''' Gather all stats objects ''' self.logger.debug("Gathering all stats") the_dict = {} the_dict['kafka-monitor'] = self.get_kafka_monitor_stats() the_dict['redis-monitor'] = self.get_redis_monitor_stats() the_dict['crawler'] = self.get_crawler_stats() the_dict['rest'] = self.get_rest_stats() return the_dict
python
def get_all_stats(self): ''' Gather all stats objects ''' self.logger.debug("Gathering all stats") the_dict = {} the_dict['kafka-monitor'] = self.get_kafka_monitor_stats() the_dict['redis-monitor'] = self.get_redis_monitor_stats() the_dict['crawler'] = self.get_crawler_stats() the_dict['rest'] = self.get_rest_stats() return the_dict
[ "def", "get_all_stats", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Gathering all stats\"", ")", "the_dict", "=", "{", "}", "the_dict", "[", "'kafka-monitor'", "]", "=", "self", ".", "get_kafka_monitor_stats", "(", ")", "the_dict", "[...
Gather all stats objects
[ "Gather", "all", "stats", "objects" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/plugins/stats_monitor.py#L69-L80
train
215,530
istresearch/scrapy-cluster
redis-monitor/plugins/stats_monitor.py
StatsMonitor._get_plugin_stats
def _get_plugin_stats(self, name): ''' Used for getting stats for Plugin based stuff, like Kafka Monitor and Redis Monitor @param name: the main class stats name @return: A formatted dict of stats ''' the_dict = {} keys = self.redis_conn.keys('stats:{n}:*'.format(n=name)) for key in keys: # break down key elements = key.split(":") main = elements[2] end = elements[3] if main == 'total' or main == 'fail': if main not in the_dict: the_dict[main] = {} the_dict[main][end] = self._get_key_value(key, end == 'lifetime') elif main == 'self': if 'nodes' not in the_dict: # main is self, end is machine, true_tail is uuid the_dict['nodes'] = {} true_tail = elements[4] if end not in the_dict['nodes']: the_dict['nodes'][end] = [] the_dict['nodes'][end].append(true_tail) else: if 'plugins' not in the_dict: the_dict['plugins'] = {} if main not in the_dict['plugins']: the_dict['plugins'][main] = {} the_dict['plugins'][main][end] = self._get_key_value(key, end == 'lifetime') return the_dict
python
def _get_plugin_stats(self, name): ''' Used for getting stats for Plugin based stuff, like Kafka Monitor and Redis Monitor @param name: the main class stats name @return: A formatted dict of stats ''' the_dict = {} keys = self.redis_conn.keys('stats:{n}:*'.format(n=name)) for key in keys: # break down key elements = key.split(":") main = elements[2] end = elements[3] if main == 'total' or main == 'fail': if main not in the_dict: the_dict[main] = {} the_dict[main][end] = self._get_key_value(key, end == 'lifetime') elif main == 'self': if 'nodes' not in the_dict: # main is self, end is machine, true_tail is uuid the_dict['nodes'] = {} true_tail = elements[4] if end not in the_dict['nodes']: the_dict['nodes'][end] = [] the_dict['nodes'][end].append(true_tail) else: if 'plugins' not in the_dict: the_dict['plugins'] = {} if main not in the_dict['plugins']: the_dict['plugins'][main] = {} the_dict['plugins'][main][end] = self._get_key_value(key, end == 'lifetime') return the_dict
[ "def", "_get_plugin_stats", "(", "self", ",", "name", ")", ":", "the_dict", "=", "{", "}", "keys", "=", "self", ".", "redis_conn", ".", "keys", "(", "'stats:{n}:*'", ".", "format", "(", "n", "=", "name", ")", ")", "for", "key", "in", "keys", ":", "...
Used for getting stats for Plugin based stuff, like Kafka Monitor and Redis Monitor @param name: the main class stats name @return: A formatted dict of stats
[ "Used", "for", "getting", "stats", "for", "Plugin", "based", "stuff", "like", "Kafka", "Monitor", "and", "Redis", "Monitor" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/plugins/stats_monitor.py#L109-L146
train
215,531
istresearch/scrapy-cluster
redis-monitor/plugins/stats_monitor.py
StatsMonitor._get_key_value
def _get_key_value(self, key, is_hll=False): ''' Returns the proper key value for the stats @param key: the redis key @param is_hll: the key is a HyperLogLog, else is a sorted set ''' if is_hll: # get hll value return self.redis_conn.execute_command("PFCOUNT", key) else: # get zcard value return self.redis_conn.zcard(key)
python
def _get_key_value(self, key, is_hll=False): ''' Returns the proper key value for the stats @param key: the redis key @param is_hll: the key is a HyperLogLog, else is a sorted set ''' if is_hll: # get hll value return self.redis_conn.execute_command("PFCOUNT", key) else: # get zcard value return self.redis_conn.zcard(key)
[ "def", "_get_key_value", "(", "self", ",", "key", ",", "is_hll", "=", "False", ")", ":", "if", "is_hll", ":", "# get hll value", "return", "self", ".", "redis_conn", ".", "execute_command", "(", "\"PFCOUNT\"", ",", "key", ")", "else", ":", "# get zcard value...
Returns the proper key value for the stats @param key: the redis key @param is_hll: the key is a HyperLogLog, else is a sorted set
[ "Returns", "the", "proper", "key", "value", "for", "the", "stats" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/plugins/stats_monitor.py#L148-L160
train
215,532
istresearch/scrapy-cluster
redis-monitor/plugins/stats_monitor.py
StatsMonitor.get_crawler_stats
def get_crawler_stats(self): ''' Gather crawler stats @return: A dict of stats ''' self.logger.debug("Gathering crawler stats") the_dict = {} the_dict['spiders'] = self.get_spider_stats()['spiders'] the_dict['machines'] = self.get_machine_stats()['machines'] the_dict['queue'] = self.get_queue_stats()['queues'] return the_dict
python
def get_crawler_stats(self): ''' Gather crawler stats @return: A dict of stats ''' self.logger.debug("Gathering crawler stats") the_dict = {} the_dict['spiders'] = self.get_spider_stats()['spiders'] the_dict['machines'] = self.get_machine_stats()['machines'] the_dict['queue'] = self.get_queue_stats()['queues'] return the_dict
[ "def", "get_crawler_stats", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Gathering crawler stats\"", ")", "the_dict", "=", "{", "}", "the_dict", "[", "'spiders'", "]", "=", "self", ".", "get_spider_stats", "(", ")", "[", "'spiders'", ...
Gather crawler stats @return: A dict of stats
[ "Gather", "crawler", "stats" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/plugins/stats_monitor.py#L246-L259
train
215,533
istresearch/scrapy-cluster
redis-monitor/plugins/stats_monitor.py
StatsMonitor.get_queue_stats
def get_queue_stats(self): ''' Gather queue stats @return: A dict of stats ''' self.logger.debug("Gathering queue based stats") the_dict = {} keys = self.redis_conn.keys('*:*:queue') total_backlog = 0 for key in keys: elements = key.split(":") spider = elements[0] domain = elements[1] spider = 'queue_' + spider if spider not in the_dict: the_dict[spider] = { 'spider_backlog': 0, 'num_domains': 0, 'domains': [] } count = self.redis_conn.zcard(key) total_backlog += count the_dict[spider]['spider_backlog'] += count the_dict[spider]['num_domains'] += 1 the_dict[spider]['domains'].append({'domain': domain, 'backlog': count}) the_dict['total_backlog'] = total_backlog ret_dict = { 'queues': the_dict } return ret_dict
python
def get_queue_stats(self): ''' Gather queue stats @return: A dict of stats ''' self.logger.debug("Gathering queue based stats") the_dict = {} keys = self.redis_conn.keys('*:*:queue') total_backlog = 0 for key in keys: elements = key.split(":") spider = elements[0] domain = elements[1] spider = 'queue_' + spider if spider not in the_dict: the_dict[spider] = { 'spider_backlog': 0, 'num_domains': 0, 'domains': [] } count = self.redis_conn.zcard(key) total_backlog += count the_dict[spider]['spider_backlog'] += count the_dict[spider]['num_domains'] += 1 the_dict[spider]['domains'].append({'domain': domain, 'backlog': count}) the_dict['total_backlog'] = total_backlog ret_dict = { 'queues': the_dict } return ret_dict
[ "def", "get_queue_stats", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Gathering queue based stats\"", ")", "the_dict", "=", "{", "}", "keys", "=", "self", ".", "redis_conn", ".", "keys", "(", "'*:*:queue'", ")", "total_backlog", "=", ...
Gather queue stats @return: A dict of stats
[ "Gather", "queue", "stats" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/plugins/stats_monitor.py#L261-L297
train
215,534
istresearch/scrapy-cluster
crawler/config/file_pusher.py
main
def main(): ''' A manual configuration file pusher for the crawlers. This will update Zookeeper with the contents of the file specified in the args. ''' import argparse from kazoo.client import KazooClient parser = argparse.ArgumentParser( description="Crawler config file pusher to Zookeeper") parser.add_argument('-f', '--file', action='store', required=True, help="The yaml file to use") parser.add_argument('-i', '--id', action='store', default="all", help="The crawler id to use in zookeeper") parser.add_argument('-p', '--path', action='store', default="/scrapy-cluster/crawler/", help="The zookeeper path to use") parser.add_argument('-w', '--wipe', action='store_const', const=True, help="Remove the current config") parser.add_argument('-z', '--zoo-keeper', action='store', required=True, help="The Zookeeper connection <host>:<port>") args = vars(parser.parse_args()) filename = args['file'] id = args['id'] wipe = args['wipe'] zoo = args['zoo_keeper'] path = args['path'] zk = KazooClient(hosts=zoo) zk.start() # ensure path exists zk.ensure_path(path) bytes = open(filename, 'rb').read() if zk.exists(path): # push the conf file if not zk.exists(path + id) and not wipe: print("creaing conf node") zk.create(path + id, bytes) elif not wipe: print("updating conf file") zk.set(path + id, bytes) if wipe: zk.set(path + id, None) zk.stop()
python
def main(): ''' A manual configuration file pusher for the crawlers. This will update Zookeeper with the contents of the file specified in the args. ''' import argparse from kazoo.client import KazooClient parser = argparse.ArgumentParser( description="Crawler config file pusher to Zookeeper") parser.add_argument('-f', '--file', action='store', required=True, help="The yaml file to use") parser.add_argument('-i', '--id', action='store', default="all", help="The crawler id to use in zookeeper") parser.add_argument('-p', '--path', action='store', default="/scrapy-cluster/crawler/", help="The zookeeper path to use") parser.add_argument('-w', '--wipe', action='store_const', const=True, help="Remove the current config") parser.add_argument('-z', '--zoo-keeper', action='store', required=True, help="The Zookeeper connection <host>:<port>") args = vars(parser.parse_args()) filename = args['file'] id = args['id'] wipe = args['wipe'] zoo = args['zoo_keeper'] path = args['path'] zk = KazooClient(hosts=zoo) zk.start() # ensure path exists zk.ensure_path(path) bytes = open(filename, 'rb').read() if zk.exists(path): # push the conf file if not zk.exists(path + id) and not wipe: print("creaing conf node") zk.create(path + id, bytes) elif not wipe: print("updating conf file") zk.set(path + id, bytes) if wipe: zk.set(path + id, None) zk.stop()
[ "def", "main", "(", ")", ":", "import", "argparse", "from", "kazoo", ".", "client", "import", "KazooClient", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Crawler config file pusher to Zookeeper\"", ")", "parser", ".", "add_argument",...
A manual configuration file pusher for the crawlers. This will update Zookeeper with the contents of the file specified in the args.
[ "A", "manual", "configuration", "file", "pusher", "for", "the", "crawlers", ".", "This", "will", "update", "Zookeeper", "with", "the", "contents", "of", "the", "file", "specified", "in", "the", "args", "." ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/crawler/config/file_pusher.py#L5-L54
train
215,535
istresearch/scrapy-cluster
utils/scutils/log_factory.py
LogCallbackMixin.is_subdict
def is_subdict(self, a,b): ''' Return True if a is a subdict of b ''' return all((k in b and b[k]==v) for k,v in a.iteritems())
python
def is_subdict(self, a,b): ''' Return True if a is a subdict of b ''' return all((k in b and b[k]==v) for k,v in a.iteritems())
[ "def", "is_subdict", "(", "self", ",", "a", ",", "b", ")", ":", "return", "all", "(", "(", "k", "in", "b", "and", "b", "[", "k", "]", "==", "v", ")", "for", "k", ",", "v", "in", "a", ".", "iteritems", "(", ")", ")" ]
Return True if a is a subdict of b
[ "Return", "True", "if", "a", "is", "a", "subdict", "of", "b" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/log_factory.py#L62-L66
train
215,536
istresearch/scrapy-cluster
utils/scutils/log_factory.py
LogObject._check_log_level
def _check_log_level(self, level): ''' Ensures a valid log level @param level: the asked for level ''' if level not in list(self.level_dict.keys()): self.log_level = 'DEBUG' self.logger.warn("Unknown log level '{lev}', defaulting to DEBUG" .format(lev=level))
python
def _check_log_level(self, level): ''' Ensures a valid log level @param level: the asked for level ''' if level not in list(self.level_dict.keys()): self.log_level = 'DEBUG' self.logger.warn("Unknown log level '{lev}', defaulting to DEBUG" .format(lev=level))
[ "def", "_check_log_level", "(", "self", ",", "level", ")", ":", "if", "level", "not", "in", "list", "(", "self", ".", "level_dict", ".", "keys", "(", ")", ")", ":", "self", ".", "log_level", "=", "'DEBUG'", "self", ".", "logger", ".", "warn", "(", ...
Ensures a valid log level @param level: the asked for level
[ "Ensures", "a", "valid", "log", "level" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/log_factory.py#L169-L178
train
215,537
istresearch/scrapy-cluster
utils/scutils/log_factory.py
LogObject._get_formatter
def _get_formatter(self, json): ''' Return the proper log formatter @param json: Boolean value ''' if json: return jsonlogger.JsonFormatter() else: return logging.Formatter(self.format_string)
python
def _get_formatter(self, json): ''' Return the proper log formatter @param json: Boolean value ''' if json: return jsonlogger.JsonFormatter() else: return logging.Formatter(self.format_string)
[ "def", "_get_formatter", "(", "self", ",", "json", ")", ":", "if", "json", ":", "return", "jsonlogger", ".", "JsonFormatter", "(", ")", "else", ":", "return", "logging", ".", "Formatter", "(", "self", ".", "format_string", ")" ]
Return the proper log formatter @param json: Boolean value
[ "Return", "the", "proper", "log", "formatter" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/log_factory.py#L180-L189
train
215,538
istresearch/scrapy-cluster
utils/scutils/log_factory.py
LogObject.debug
def debug(self, message, extra={}): ''' Writes an error message to the log @param message: The message to write @param extra: The extras object to pass in ''' if self.level_dict['DEBUG'] >= self.level_dict[self.log_level]: extras = self.add_extras(extra, "DEBUG") self._write_message(message, extras) self.fire_callbacks('DEBUG', message, extra)
python
def debug(self, message, extra={}): ''' Writes an error message to the log @param message: The message to write @param extra: The extras object to pass in ''' if self.level_dict['DEBUG'] >= self.level_dict[self.log_level]: extras = self.add_extras(extra, "DEBUG") self._write_message(message, extras) self.fire_callbacks('DEBUG', message, extra)
[ "def", "debug", "(", "self", ",", "message", ",", "extra", "=", "{", "}", ")", ":", "if", "self", ".", "level_dict", "[", "'DEBUG'", "]", ">=", "self", ".", "level_dict", "[", "self", ".", "log_level", "]", ":", "extras", "=", "self", ".", "add_ext...
Writes an error message to the log @param message: The message to write @param extra: The extras object to pass in
[ "Writes", "an", "error", "message", "to", "the", "log" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/log_factory.py#L191-L201
train
215,539
istresearch/scrapy-cluster
utils/scutils/log_factory.py
LogObject._write_message
def _write_message(self, message, extra): ''' Writes the log output @param message: The message to write @param extra: The potential object to write ''' if not self.json: self._write_standard(message, extra) else: self._write_json(message, extra)
python
def _write_message(self, message, extra): ''' Writes the log output @param message: The message to write @param extra: The potential object to write ''' if not self.json: self._write_standard(message, extra) else: self._write_json(message, extra)
[ "def", "_write_message", "(", "self", ",", "message", ",", "extra", ")", ":", "if", "not", "self", ".", "json", ":", "self", ".", "_write_standard", "(", "message", ",", "extra", ")", "else", ":", "self", ".", "_write_json", "(", "message", ",", "extra...
Writes the log output @param message: The message to write @param extra: The potential object to write
[ "Writes", "the", "log", "output" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/log_factory.py#L260-L269
train
215,540
istresearch/scrapy-cluster
utils/scutils/log_factory.py
LogObject._write_standard
def _write_standard(self, message, extra): ''' Writes a standard log statement @param message: The message to write @param extra: The object to pull defaults from ''' level = extra['level'] if self.include_extra: del extra['timestamp'] del extra['level'] del extra['logger'] if len(extra) > 0: message += " " + str(extra) if level == 'INFO': self.logger.info(message) elif level == 'DEBUG': self.logger.debug(message) elif level == 'WARNING': self.logger.warning(message) elif level == 'ERROR': self.logger.error(message) elif level == 'CRITICAL': self.logger.critical(message) else: self.logger.debug(message)
python
def _write_standard(self, message, extra): ''' Writes a standard log statement @param message: The message to write @param extra: The object to pull defaults from ''' level = extra['level'] if self.include_extra: del extra['timestamp'] del extra['level'] del extra['logger'] if len(extra) > 0: message += " " + str(extra) if level == 'INFO': self.logger.info(message) elif level == 'DEBUG': self.logger.debug(message) elif level == 'WARNING': self.logger.warning(message) elif level == 'ERROR': self.logger.error(message) elif level == 'CRITICAL': self.logger.critical(message) else: self.logger.debug(message)
[ "def", "_write_standard", "(", "self", ",", "message", ",", "extra", ")", ":", "level", "=", "extra", "[", "'level'", "]", "if", "self", ".", "include_extra", ":", "del", "extra", "[", "'timestamp'", "]", "del", "extra", "[", "'level'", "]", "del", "ex...
Writes a standard log statement @param message: The message to write @param extra: The object to pull defaults from
[ "Writes", "a", "standard", "log", "statement" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/log_factory.py#L271-L297
train
215,541
istresearch/scrapy-cluster
utils/scutils/log_factory.py
LogObject._write_json
def _write_json(self, message, extra): ''' The JSON logger doesn't obey log levels @param message: The message to write @param extra: The object to write ''' self.logger.info(message, extra=extra)
python
def _write_json(self, message, extra): ''' The JSON logger doesn't obey log levels @param message: The message to write @param extra: The object to write ''' self.logger.info(message, extra=extra)
[ "def", "_write_json", "(", "self", ",", "message", ",", "extra", ")", ":", "self", ".", "logger", ".", "info", "(", "message", ",", "extra", "=", "extra", ")" ]
The JSON logger doesn't obey log levels @param message: The message to write @param extra: The object to write
[ "The", "JSON", "logger", "doesn", "t", "obey", "log", "levels" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/log_factory.py#L299-L306
train
215,542
istresearch/scrapy-cluster
utils/scutils/log_factory.py
LogObject.add_extras
def add_extras(self, dict, level): ''' Adds the log level to the dict object ''' my_copy = copy.deepcopy(dict) if 'level' not in my_copy: my_copy['level'] = level if 'timestamp' not in my_copy: my_copy['timestamp'] = self._get_time() if 'logger' not in my_copy: my_copy['logger'] = self.name return my_copy
python
def add_extras(self, dict, level): ''' Adds the log level to the dict object ''' my_copy = copy.deepcopy(dict) if 'level' not in my_copy: my_copy['level'] = level if 'timestamp' not in my_copy: my_copy['timestamp'] = self._get_time() if 'logger' not in my_copy: my_copy['logger'] = self.name return my_copy
[ "def", "add_extras", "(", "self", ",", "dict", ",", "level", ")", ":", "my_copy", "=", "copy", ".", "deepcopy", "(", "dict", ")", "if", "'level'", "not", "in", "my_copy", ":", "my_copy", "[", "'level'", "]", "=", "level", "if", "'timestamp'", "not", ...
Adds the log level to the dict object
[ "Adds", "the", "log", "level", "to", "the", "dict", "object" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/log_factory.py#L315-L326
train
215,543
istresearch/scrapy-cluster
crawler/crawling/log_retry_middleware.py
LogRetryMiddleware._increment_504_stat
def _increment_504_stat(self, request): ''' Increments the 504 stat counters @param request: The scrapy request in the spider ''' for key in self.stats_dict: if key == 'lifetime': unique = request.url + str(time.time()) self.stats_dict[key].increment(unique) else: self.stats_dict[key].increment() self.logger.debug("Incremented status_code '504' stats")
python
def _increment_504_stat(self, request): ''' Increments the 504 stat counters @param request: The scrapy request in the spider ''' for key in self.stats_dict: if key == 'lifetime': unique = request.url + str(time.time()) self.stats_dict[key].increment(unique) else: self.stats_dict[key].increment() self.logger.debug("Incremented status_code '504' stats")
[ "def", "_increment_504_stat", "(", "self", ",", "request", ")", ":", "for", "key", "in", "self", ".", "stats_dict", ":", "if", "key", "==", "'lifetime'", ":", "unique", "=", "request", ".", "url", "+", "str", "(", "time", ".", "time", "(", ")", ")", ...
Increments the 504 stat counters @param request: The scrapy request in the spider
[ "Increments", "the", "504", "stat", "counters" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/crawler/crawling/log_retry_middleware.py#L149-L161
train
215,544
istresearch/scrapy-cluster
utils/scutils/redis_throttled_queue.py
RedisThrottledQueue.clear
def clear(self): ''' Clears all data associated with the throttled queue ''' self.redis_conn.delete(self.window_key) self.redis_conn.delete(self.moderate_key) self.queue.clear()
python
def clear(self): ''' Clears all data associated with the throttled queue ''' self.redis_conn.delete(self.window_key) self.redis_conn.delete(self.moderate_key) self.queue.clear()
[ "def", "clear", "(", "self", ")", ":", "self", ".", "redis_conn", ".", "delete", "(", "self", ".", "window_key", ")", "self", ".", "redis_conn", ".", "delete", "(", "self", ".", "moderate_key", ")", "self", ".", "queue", ".", "clear", "(", ")" ]
Clears all data associated with the throttled queue
[ "Clears", "all", "data", "associated", "with", "the", "throttled", "queue" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/redis_throttled_queue.py#L76-L82
train
215,545
istresearch/scrapy-cluster
utils/scutils/redis_throttled_queue.py
RedisThrottledQueue.pop
def pop(self, *args): ''' Non-blocking from throttled queue standpoint, tries to return a queue pop request, only will return a request if the given time window has not been exceeded @return: The item if the throttle limit has not been hit, otherwise None ''' if self.allowed(): if self.elastic_kick_in < self.limit: self.elastic_kick_in += 1 return self.queue.pop(*args) else: return None
python
def pop(self, *args): ''' Non-blocking from throttled queue standpoint, tries to return a queue pop request, only will return a request if the given time window has not been exceeded @return: The item if the throttle limit has not been hit, otherwise None ''' if self.allowed(): if self.elastic_kick_in < self.limit: self.elastic_kick_in += 1 return self.queue.pop(*args) else: return None
[ "def", "pop", "(", "self", ",", "*", "args", ")", ":", "if", "self", ".", "allowed", "(", ")", ":", "if", "self", ".", "elastic_kick_in", "<", "self", ".", "limit", ":", "self", ".", "elastic_kick_in", "+=", "1", "return", "self", ".", "queue", "."...
Non-blocking from throttled queue standpoint, tries to return a queue pop request, only will return a request if the given time window has not been exceeded @return: The item if the throttle limit has not been hit, otherwise None
[ "Non", "-", "blocking", "from", "throttled", "queue", "standpoint", "tries", "to", "return", "a", "queue", "pop", "request", "only", "will", "return", "a", "request", "if", "the", "given", "time", "window", "has", "not", "been", "exceeded" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/redis_throttled_queue.py#L90-L104
train
215,546
istresearch/scrapy-cluster
utils/scutils/redis_throttled_queue.py
RedisThrottledQueue.allowed
def allowed(self): ''' Check to see if the pop request is allowed @return: True means the maximum was not been reached for the current time window, thus allowing what ever operation follows ''' # Expire old keys (hits) expires = time.time() - self.window self.redis_conn.zremrangebyscore(self.window_key, '-inf', expires) # check if we are hitting too fast for moderation if self.moderation: with self.redis_conn.pipeline() as pipe: try: pipe.watch(self.moderate_key) # ---- LOCK # from this point onward if no errors are raised we # successfully incremented the counter curr_time = time.time() if self.is_moderated(curr_time, pipe) and not \ self.check_elastic(): return False # passed the moderation limit, now check time window # If we have less keys than max, update out moderate key if self.test_hits(): # this is a valid transaction, set the new time pipe.multi() pipe.set(name=self.moderate_key, value=str(curr_time), ex=int(self.window * 2)) pipe.execute() return True except WatchError: # watch was changed, another thread just incremented # the value return False # If we currently have more keys than max, # then limit the action else: return self.test_hits() return False
python
def allowed(self): ''' Check to see if the pop request is allowed @return: True means the maximum was not been reached for the current time window, thus allowing what ever operation follows ''' # Expire old keys (hits) expires = time.time() - self.window self.redis_conn.zremrangebyscore(self.window_key, '-inf', expires) # check if we are hitting too fast for moderation if self.moderation: with self.redis_conn.pipeline() as pipe: try: pipe.watch(self.moderate_key) # ---- LOCK # from this point onward if no errors are raised we # successfully incremented the counter curr_time = time.time() if self.is_moderated(curr_time, pipe) and not \ self.check_elastic(): return False # passed the moderation limit, now check time window # If we have less keys than max, update out moderate key if self.test_hits(): # this is a valid transaction, set the new time pipe.multi() pipe.set(name=self.moderate_key, value=str(curr_time), ex=int(self.window * 2)) pipe.execute() return True except WatchError: # watch was changed, another thread just incremented # the value return False # If we currently have more keys than max, # then limit the action else: return self.test_hits() return False
[ "def", "allowed", "(", "self", ")", ":", "# Expire old keys (hits)", "expires", "=", "time", ".", "time", "(", ")", "-", "self", ".", "window", "self", ".", "redis_conn", ".", "zremrangebyscore", "(", "self", ".", "window_key", ",", "'-inf'", ",", "expires...
Check to see if the pop request is allowed @return: True means the maximum was not been reached for the current time window, thus allowing what ever operation follows
[ "Check", "to", "see", "if", "the", "pop", "request", "is", "allowed" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/redis_throttled_queue.py#L112-L157
train
215,547
istresearch/scrapy-cluster
utils/scutils/redis_throttled_queue.py
RedisThrottledQueue.check_elastic
def check_elastic(self): ''' Checks if we need to break moderation in order to maintain our desired throttle limit @return: True if we need to break moderation ''' if self.elastic and self.elastic_kick_in == self.limit: value = self.redis_conn.zcard(self.window_key) if self.limit - value > self.elastic_buffer: return True return False
python
def check_elastic(self): ''' Checks if we need to break moderation in order to maintain our desired throttle limit @return: True if we need to break moderation ''' if self.elastic and self.elastic_kick_in == self.limit: value = self.redis_conn.zcard(self.window_key) if self.limit - value > self.elastic_buffer: return True return False
[ "def", "check_elastic", "(", "self", ")", ":", "if", "self", ".", "elastic", "and", "self", ".", "elastic_kick_in", "==", "self", ".", "limit", ":", "value", "=", "self", ".", "redis_conn", ".", "zcard", "(", "self", ".", "window_key", ")", "if", "self...
Checks if we need to break moderation in order to maintain our desired throttle limit @return: True if we need to break moderation
[ "Checks", "if", "we", "need", "to", "break", "moderation", "in", "order", "to", "maintain", "our", "desired", "throttle", "limit" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/redis_throttled_queue.py#L159-L170
train
215,548
istresearch/scrapy-cluster
utils/scutils/redis_throttled_queue.py
RedisThrottledQueue.is_moderated
def is_moderated(self, curr_time, pipe): ''' Tests to see if the moderation limit is not exceeded @return: True if the moderation limit is exceeded ''' # get key, otherwise default the moderate key expired and # we dont care value = pipe.get(self.moderate_key) if value is None: value = 0.0 else: value = float(value) # check moderation difference if (curr_time - value) < self.moderation: return True return False
python
def is_moderated(self, curr_time, pipe): ''' Tests to see if the moderation limit is not exceeded @return: True if the moderation limit is exceeded ''' # get key, otherwise default the moderate key expired and # we dont care value = pipe.get(self.moderate_key) if value is None: value = 0.0 else: value = float(value) # check moderation difference if (curr_time - value) < self.moderation: return True return False
[ "def", "is_moderated", "(", "self", ",", "curr_time", ",", "pipe", ")", ":", "# get key, otherwise default the moderate key expired and", "# we dont care", "value", "=", "pipe", ".", "get", "(", "self", ".", "moderate_key", ")", "if", "value", "is", "None", ":", ...
Tests to see if the moderation limit is not exceeded @return: True if the moderation limit is exceeded
[ "Tests", "to", "see", "if", "the", "moderation", "limit", "is", "not", "exceeded" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/redis_throttled_queue.py#L172-L190
train
215,549
istresearch/scrapy-cluster
redis-monitor/plugins/info_monitor.py
InfoMonitor._get_bin
def _get_bin(self, key): ''' Returns a binned dictionary based on redis zscore @return: The sorted dict ''' # keys based on score sortedDict = {} # this doesnt return them in order, need to bin first for item in self.redis_conn.zscan_iter(key): my_item = ujson.loads(item[0]) # score is negated in redis my_score = -item[1] if my_score not in sortedDict: sortedDict[my_score] = [] sortedDict[my_score].append(my_item) return sortedDict
python
def _get_bin(self, key): ''' Returns a binned dictionary based on redis zscore @return: The sorted dict ''' # keys based on score sortedDict = {} # this doesnt return them in order, need to bin first for item in self.redis_conn.zscan_iter(key): my_item = ujson.loads(item[0]) # score is negated in redis my_score = -item[1] if my_score not in sortedDict: sortedDict[my_score] = [] sortedDict[my_score].append(my_item) return sortedDict
[ "def", "_get_bin", "(", "self", ",", "key", ")", ":", "# keys based on score", "sortedDict", "=", "{", "}", "# this doesnt return them in order, need to bin first", "for", "item", "in", "self", ".", "redis_conn", ".", "zscan_iter", "(", "key", ")", ":", "my_item",...
Returns a binned dictionary based on redis zscore @return: The sorted dict
[ "Returns", "a", "binned", "dictionary", "based", "on", "redis", "zscore" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/plugins/info_monitor.py#L60-L79
train
215,550
istresearch/scrapy-cluster
redis-monitor/plugins/info_monitor.py
InfoMonitor._build_appid_info
def _build_appid_info(self, master, dict): ''' Builds the appid info object @param master: the master dict @param dict: the dict object received @return: the appid info object ''' master['total_crawlids'] = 0 master['total_pending'] = 0 master['total_domains'] = 0 master['crawlids'] = {} master['appid'] = dict['appid'] master['spiderid'] = dict['spiderid'] # used for finding total count of domains domain_dict = {} # get all domain queues match_string = '{sid}:*:queue'.format(sid=dict['spiderid']) for key in self.redis_conn.scan_iter(match=match_string): domain = key.split(":")[1] sortedDict = self._get_bin(key) # now iterate through binned dict for score in sortedDict: for item in sortedDict[score]: if 'meta' in item: item = item['meta'] if item['appid'] == dict['appid']: crawlid = item['crawlid'] # add new crawlid to master dict if crawlid not in master['crawlids']: master['crawlids'][crawlid] = { 'total': 0, 'domains': {}, 'distinct_domains': 0 } if 'expires' in item and item['expires'] != 0: master['crawlids'][crawlid]['expires'] = item['expires'] master['total_crawlids'] += 1 master['crawlids'][crawlid]['total'] = master['crawlids'][crawlid]['total'] + 1 if domain not in master['crawlids'][crawlid]['domains']: master['crawlids'][crawlid]['domains'][domain] = { 'total': 0, 'high_priority': -9999, 'low_priority': 9999, } master['crawlids'][crawlid]['distinct_domains'] += 1 domain_dict[domain] = True master['crawlids'][crawlid]['domains'][domain]['total'] = master['crawlids'][crawlid]['domains'][domain]['total'] + 1 if item['priority'] > master['crawlids'][crawlid]['domains'][domain]['high_priority']: master['crawlids'][crawlid]['domains'][domain]['high_priority'] = item['priority'] if item['priority'] < master['crawlids'][crawlid]['domains'][domain]['low_priority']: master['crawlids'][crawlid]['domains'][domain]['low_priority'] = item['priority'] master['total_pending'] += 1 master['total_domains'] = len(domain_dict) return master
python
def _build_appid_info(self, master, dict): ''' Builds the appid info object @param master: the master dict @param dict: the dict object received @return: the appid info object ''' master['total_crawlids'] = 0 master['total_pending'] = 0 master['total_domains'] = 0 master['crawlids'] = {} master['appid'] = dict['appid'] master['spiderid'] = dict['spiderid'] # used for finding total count of domains domain_dict = {} # get all domain queues match_string = '{sid}:*:queue'.format(sid=dict['spiderid']) for key in self.redis_conn.scan_iter(match=match_string): domain = key.split(":")[1] sortedDict = self._get_bin(key) # now iterate through binned dict for score in sortedDict: for item in sortedDict[score]: if 'meta' in item: item = item['meta'] if item['appid'] == dict['appid']: crawlid = item['crawlid'] # add new crawlid to master dict if crawlid not in master['crawlids']: master['crawlids'][crawlid] = { 'total': 0, 'domains': {}, 'distinct_domains': 0 } if 'expires' in item and item['expires'] != 0: master['crawlids'][crawlid]['expires'] = item['expires'] master['total_crawlids'] += 1 master['crawlids'][crawlid]['total'] = master['crawlids'][crawlid]['total'] + 1 if domain not in master['crawlids'][crawlid]['domains']: master['crawlids'][crawlid]['domains'][domain] = { 'total': 0, 'high_priority': -9999, 'low_priority': 9999, } master['crawlids'][crawlid]['distinct_domains'] += 1 domain_dict[domain] = True master['crawlids'][crawlid]['domains'][domain]['total'] = master['crawlids'][crawlid]['domains'][domain]['total'] + 1 if item['priority'] > master['crawlids'][crawlid]['domains'][domain]['high_priority']: master['crawlids'][crawlid]['domains'][domain]['high_priority'] = item['priority'] if item['priority'] < master['crawlids'][crawlid]['domains'][domain]['low_priority']: master['crawlids'][crawlid]['domains'][domain]['low_priority'] = item['priority'] master['total_pending'] += 1 master['total_domains'] = len(domain_dict) return master
[ "def", "_build_appid_info", "(", "self", ",", "master", ",", "dict", ")", ":", "master", "[", "'total_crawlids'", "]", "=", "0", "master", "[", "'total_pending'", "]", "=", "0", "master", "[", "'total_domains'", "]", "=", "0", "master", "[", "'crawlids'", ...
Builds the appid info object @param master: the master dict @param dict: the dict object received @return: the appid info object
[ "Builds", "the", "appid", "info", "object" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/plugins/info_monitor.py#L81-L150
train
215,551
istresearch/scrapy-cluster
redis-monitor/plugins/info_monitor.py
InfoMonitor._build_crawlid_info
def _build_crawlid_info(self, master, dict): ''' Builds the crawlid info object @param master: the master dict @param dict: the dict object received @return: the crawlid info object ''' master['total_pending'] = 0 master['total_domains'] = 0 master['appid'] = dict['appid'] master['crawlid'] = dict['crawlid'] master['spiderid'] = dict['spiderid'] master['domains'] = {} timeout_key = 'timeout:{sid}:{aid}:{cid}'.format(sid=dict['spiderid'], aid=dict['appid'], cid=dict['crawlid']) if self.redis_conn.exists(timeout_key): master['expires'] = self.redis_conn.get(timeout_key) # get all domain queues match_string = '{sid}:*:queue'.format(sid=dict['spiderid']) for key in self.redis_conn.scan_iter(match=match_string): domain = key.split(":")[1] sortedDict = self._get_bin(key) # now iterate through binned dict for score in sortedDict: for item in sortedDict[score]: if 'meta' in item: item = item['meta'] if item['appid'] == dict['appid'] and item['crawlid'] == dict['crawlid']: if domain not in master['domains']: master['domains'][domain] = {} master['domains'][domain]['total'] = 0 master['domains'][domain]['high_priority'] = -9999 master['domains'][domain]['low_priority'] = 9999 master['total_domains'] = master['total_domains'] + 1 master['domains'][domain]['total'] = master['domains'][domain]['total'] + 1 if item['priority'] > master['domains'][domain]['high_priority']: master['domains'][domain]['high_priority'] = item['priority'] if item['priority'] < master['domains'][domain]['low_priority']: master['domains'][domain]['low_priority'] = item['priority'] master['total_pending'] = master['total_pending'] + 1 return master
python
def _build_crawlid_info(self, master, dict): ''' Builds the crawlid info object @param master: the master dict @param dict: the dict object received @return: the crawlid info object ''' master['total_pending'] = 0 master['total_domains'] = 0 master['appid'] = dict['appid'] master['crawlid'] = dict['crawlid'] master['spiderid'] = dict['spiderid'] master['domains'] = {} timeout_key = 'timeout:{sid}:{aid}:{cid}'.format(sid=dict['spiderid'], aid=dict['appid'], cid=dict['crawlid']) if self.redis_conn.exists(timeout_key): master['expires'] = self.redis_conn.get(timeout_key) # get all domain queues match_string = '{sid}:*:queue'.format(sid=dict['spiderid']) for key in self.redis_conn.scan_iter(match=match_string): domain = key.split(":")[1] sortedDict = self._get_bin(key) # now iterate through binned dict for score in sortedDict: for item in sortedDict[score]: if 'meta' in item: item = item['meta'] if item['appid'] == dict['appid'] and item['crawlid'] == dict['crawlid']: if domain not in master['domains']: master['domains'][domain] = {} master['domains'][domain]['total'] = 0 master['domains'][domain]['high_priority'] = -9999 master['domains'][domain]['low_priority'] = 9999 master['total_domains'] = master['total_domains'] + 1 master['domains'][domain]['total'] = master['domains'][domain]['total'] + 1 if item['priority'] > master['domains'][domain]['high_priority']: master['domains'][domain]['high_priority'] = item['priority'] if item['priority'] < master['domains'][domain]['low_priority']: master['domains'][domain]['low_priority'] = item['priority'] master['total_pending'] = master['total_pending'] + 1 return master
[ "def", "_build_crawlid_info", "(", "self", ",", "master", ",", "dict", ")", ":", "master", "[", "'total_pending'", "]", "=", "0", "master", "[", "'total_domains'", "]", "=", "0", "master", "[", "'appid'", "]", "=", "dict", "[", "'appid'", "]", "master", ...
Builds the crawlid info object @param master: the master dict @param dict: the dict object received @return: the crawlid info object
[ "Builds", "the", "crawlid", "info", "object" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/plugins/info_monitor.py#L152-L202
train
215,552
istresearch/scrapy-cluster
redis-monitor/plugins/stop_monitor.py
StopMonitor._purge_crawl
def _purge_crawl(self, spiderid, appid, crawlid): ''' Wrapper for purging the crawlid from the queues @param spiderid: the spider id @param appid: the app id @param crawlid: the crawl id @return: The number of requests purged ''' # purge three times to try to make sure everything is cleaned total = self._mini_purge(spiderid, appid, crawlid) total = total + self._mini_purge(spiderid, appid, crawlid) total = total + self._mini_purge(spiderid, appid, crawlid) return total
python
def _purge_crawl(self, spiderid, appid, crawlid): ''' Wrapper for purging the crawlid from the queues @param spiderid: the spider id @param appid: the app id @param crawlid: the crawl id @return: The number of requests purged ''' # purge three times to try to make sure everything is cleaned total = self._mini_purge(spiderid, appid, crawlid) total = total + self._mini_purge(spiderid, appid, crawlid) total = total + self._mini_purge(spiderid, appid, crawlid) return total
[ "def", "_purge_crawl", "(", "self", ",", "spiderid", ",", "appid", ",", "crawlid", ")", ":", "# purge three times to try to make sure everything is cleaned", "total", "=", "self", ".", "_mini_purge", "(", "spiderid", ",", "appid", ",", "crawlid", ")", "total", "="...
Wrapper for purging the crawlid from the queues @param spiderid: the spider id @param appid: the app id @param crawlid: the crawl id @return: The number of requests purged
[ "Wrapper", "for", "purging", "the", "crawlid", "from", "the", "queues" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/plugins/stop_monitor.py#L73-L87
train
215,553
istresearch/scrapy-cluster
redis-monitor/plugins/stop_monitor.py
StopMonitor._mini_purge
def _mini_purge(self, spiderid, appid, crawlid): ''' Actually purges the crawlid from the queue @param spiderid: the spider id @param appid: the app id @param crawlid: the crawl id @return: The number of requests purged ''' total_purged = 0 match_string = '{sid}:*:queue'.format(sid=spiderid) # using scan for speed vs keys for key in self.redis_conn.scan_iter(match=match_string): for item in self.redis_conn.zscan_iter(key): item_key = item[0] item = ujson.loads(item_key) if 'meta' in item: item = item['meta'] if item['appid'] == appid and item['crawlid'] == crawlid: self.redis_conn.zrem(key, item_key) total_purged = total_purged + 1 return total_purged
python
def _mini_purge(self, spiderid, appid, crawlid): ''' Actually purges the crawlid from the queue @param spiderid: the spider id @param appid: the app id @param crawlid: the crawl id @return: The number of requests purged ''' total_purged = 0 match_string = '{sid}:*:queue'.format(sid=spiderid) # using scan for speed vs keys for key in self.redis_conn.scan_iter(match=match_string): for item in self.redis_conn.zscan_iter(key): item_key = item[0] item = ujson.loads(item_key) if 'meta' in item: item = item['meta'] if item['appid'] == appid and item['crawlid'] == crawlid: self.redis_conn.zrem(key, item_key) total_purged = total_purged + 1 return total_purged
[ "def", "_mini_purge", "(", "self", ",", "spiderid", ",", "appid", ",", "crawlid", ")", ":", "total_purged", "=", "0", "match_string", "=", "'{sid}:*:queue'", ".", "format", "(", "sid", "=", "spiderid", ")", "# using scan for speed vs keys", "for", "key", "in",...
Actually purges the crawlid from the queue @param spiderid: the spider id @param appid: the app id @param crawlid: the crawl id @return: The number of requests purged
[ "Actually", "purges", "the", "crawlid", "from", "the", "queue" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/plugins/stop_monitor.py#L89-L113
train
215,554
istresearch/scrapy-cluster
rest/rest_service.py
log_call
def log_call(call_name): """Log the API call to the logger.""" def decorator(f): @wraps(f) def wrapper(*args, **kw): instance = args[0] instance.logger.info(call_name, {"content": request.get_json()}) return f(*args, **kw) return wrapper return decorator
python
def log_call(call_name): """Log the API call to the logger.""" def decorator(f): @wraps(f) def wrapper(*args, **kw): instance = args[0] instance.logger.info(call_name, {"content": request.get_json()}) return f(*args, **kw) return wrapper return decorator
[ "def", "log_call", "(", "call_name", ")", ":", "def", "decorator", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "instance", "=", "args", "[", "0", "]", "instance", ".", "log...
Log the API call to the logger.
[ "Log", "the", "API", "call", "to", "the", "logger", "." ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L38-L47
train
215,555
istresearch/scrapy-cluster
rest/rest_service.py
error_catch
def error_catch(f): """Handle unexpected errors within the rest function.""" @wraps(f) def wrapper(*args, **kw): instance = args[0] try: result = f(*args, **kw) if isinstance(result, tuple): return jsonify(result[0]), result[1] else: return jsonify(result), 200 except Exception as e: ret_dict = instance._create_ret_object(instance.FAILURE, None, True, instance.UNKNOWN_ERROR) log_dict = deepcopy(ret_dict) log_dict['error']['cause'] = e.message log_dict['error']['exception'] = str(e) log_dict['error']['ex'] = traceback.format_exc() instance.logger.error("Uncaught Exception Thrown", log_dict) return jsonify(ret_dict), 500 return wrapper
python
def error_catch(f): """Handle unexpected errors within the rest function.""" @wraps(f) def wrapper(*args, **kw): instance = args[0] try: result = f(*args, **kw) if isinstance(result, tuple): return jsonify(result[0]), result[1] else: return jsonify(result), 200 except Exception as e: ret_dict = instance._create_ret_object(instance.FAILURE, None, True, instance.UNKNOWN_ERROR) log_dict = deepcopy(ret_dict) log_dict['error']['cause'] = e.message log_dict['error']['exception'] = str(e) log_dict['error']['ex'] = traceback.format_exc() instance.logger.error("Uncaught Exception Thrown", log_dict) return jsonify(ret_dict), 500 return wrapper
[ "def", "error_catch", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "instance", "=", "args", "[", "0", "]", "try", ":", "result", "=", "f", "(", "*", "args", ",", "*", "*...
Handle unexpected errors within the rest function.
[ "Handle", "unexpected", "errors", "within", "the", "rest", "function", "." ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L50-L71
train
215,556
istresearch/scrapy-cluster
rest/rest_service.py
validate_json
def validate_json(f): """Validate that the call is JSON.""" @wraps(f) def wrapper(*args, **kw): instance = args[0] try: if request.get_json() is None: ret_dict = instance._create_ret_object(instance.FAILURE, None, True, instance.MUST_JSON) instance.logger.error(instance.MUST_JSON) return jsonify(ret_dict), 400 except BadRequest: ret_dict = instance._create_ret_object(instance.FAILURE, None, True, instance.MUST_JSON) instance.logger.error(instance.MUST_JSON) return jsonify(ret_dict), 400 instance.logger.debug("JSON is valid") return f(*args, **kw) return wrapper
python
def validate_json(f): """Validate that the call is JSON.""" @wraps(f) def wrapper(*args, **kw): instance = args[0] try: if request.get_json() is None: ret_dict = instance._create_ret_object(instance.FAILURE, None, True, instance.MUST_JSON) instance.logger.error(instance.MUST_JSON) return jsonify(ret_dict), 400 except BadRequest: ret_dict = instance._create_ret_object(instance.FAILURE, None, True, instance.MUST_JSON) instance.logger.error(instance.MUST_JSON) return jsonify(ret_dict), 400 instance.logger.debug("JSON is valid") return f(*args, **kw) return wrapper
[ "def", "validate_json", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "instance", "=", "args", "[", "0", "]", "try", ":", "if", "request", ".", "get_json", "(", ")", "is", ...
Validate that the call is JSON.
[ "Validate", "that", "the", "call", "is", "JSON", "." ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L74-L94
train
215,557
istresearch/scrapy-cluster
rest/rest_service.py
validate_schema
def validate_schema(schema_name): """Validate the JSON against a required schema_name.""" def decorator(f): @wraps(f) def wrapper(*args, **kw): instance = args[0] try: instance.validator(instance.schemas[schema_name]).validate(request.get_json()) except ValidationError, e: ret_dict = instance._create_ret_object(instance.FAILURE, None, True, instance.BAD_SCHEMA, e.message) instance.logger.error("Invalid Schema", ret_dict) return jsonify(ret_dict), 400 instance.logger.debug("Schema is valid") return f(*args, **kw) return wrapper return decorator
python
def validate_schema(schema_name): """Validate the JSON against a required schema_name.""" def decorator(f): @wraps(f) def wrapper(*args, **kw): instance = args[0] try: instance.validator(instance.schemas[schema_name]).validate(request.get_json()) except ValidationError, e: ret_dict = instance._create_ret_object(instance.FAILURE, None, True, instance.BAD_SCHEMA, e.message) instance.logger.error("Invalid Schema", ret_dict) return jsonify(ret_dict), 400 instance.logger.debug("Schema is valid") return f(*args, **kw) return wrapper return decorator
[ "def", "validate_schema", "(", "schema_name", ")", ":", "def", "decorator", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "instance", "=", "args", "[", "0", "]", "try", ":", ...
Validate the JSON against a required schema_name.
[ "Validate", "the", "JSON", "against", "a", "required", "schema_name", "." ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L97-L115
train
215,558
istresearch/scrapy-cluster
rest/rest_service.py
RestService._load_schemas
def _load_schemas(self): """Loads any schemas for JSON validation""" for filename in os.listdir(self.settings['SCHEMA_DIR']): if filename[-4:] == 'json': name = filename[:-5] with open(self.settings['SCHEMA_DIR'] + filename) as the_file: self.schemas[name] = json.load(the_file) self.logger.debug("Successfully loaded " + filename + " schema")
python
def _load_schemas(self): """Loads any schemas for JSON validation""" for filename in os.listdir(self.settings['SCHEMA_DIR']): if filename[-4:] == 'json': name = filename[:-5] with open(self.settings['SCHEMA_DIR'] + filename) as the_file: self.schemas[name] = json.load(the_file) self.logger.debug("Successfully loaded " + filename + " schema")
[ "def", "_load_schemas", "(", "self", ")", ":", "for", "filename", "in", "os", ".", "listdir", "(", "self", ".", "settings", "[", "'SCHEMA_DIR'", "]", ")", ":", "if", "filename", "[", "-", "4", ":", "]", "==", "'json'", ":", "name", "=", "filename", ...
Loads any schemas for JSON validation
[ "Loads", "any", "schemas", "for", "JSON", "validation" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L198-L205
train
215,559
istresearch/scrapy-cluster
rest/rest_service.py
RestService._spawn_redis_connection_thread
def _spawn_redis_connection_thread(self): """Spawns a redis connection thread""" self.logger.debug("Spawn redis connection thread") self.redis_connected = False self._redis_thread = Thread(target=self._setup_redis) self._redis_thread.setDaemon(True) self._redis_thread.start()
python
def _spawn_redis_connection_thread(self): """Spawns a redis connection thread""" self.logger.debug("Spawn redis connection thread") self.redis_connected = False self._redis_thread = Thread(target=self._setup_redis) self._redis_thread.setDaemon(True) self._redis_thread.start()
[ "def", "_spawn_redis_connection_thread", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Spawn redis connection thread\"", ")", "self", ".", "redis_connected", "=", "False", "self", ".", "_redis_thread", "=", "Thread", "(", "target", "=", "se...
Spawns a redis connection thread
[ "Spawns", "a", "redis", "connection", "thread" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L228-L234
train
215,560
istresearch/scrapy-cluster
rest/rest_service.py
RestService._spawn_kafka_connection_thread
def _spawn_kafka_connection_thread(self): """Spawns a kafka connection thread""" self.logger.debug("Spawn kafka connection thread") self.kafka_connected = False self._kafka_thread = Thread(target=self._setup_kafka) self._kafka_thread.setDaemon(True) self._kafka_thread.start()
python
def _spawn_kafka_connection_thread(self): """Spawns a kafka connection thread""" self.logger.debug("Spawn kafka connection thread") self.kafka_connected = False self._kafka_thread = Thread(target=self._setup_kafka) self._kafka_thread.setDaemon(True) self._kafka_thread.start()
[ "def", "_spawn_kafka_connection_thread", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Spawn kafka connection thread\"", ")", "self", ".", "kafka_connected", "=", "False", "self", ".", "_kafka_thread", "=", "Thread", "(", "target", "=", "se...
Spawns a kafka connection thread
[ "Spawns", "a", "kafka", "connection", "thread" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L236-L242
train
215,561
istresearch/scrapy-cluster
rest/rest_service.py
RestService._consumer_loop
def _consumer_loop(self): """The main consumer loop""" self.logger.debug("running main consumer thread") while not self.closed: if self.kafka_connected: self._process_messages() time.sleep(self.settings['KAFKA_CONSUMER_SLEEP_TIME'])
python
def _consumer_loop(self): """The main consumer loop""" self.logger.debug("running main consumer thread") while not self.closed: if self.kafka_connected: self._process_messages() time.sleep(self.settings['KAFKA_CONSUMER_SLEEP_TIME'])
[ "def", "_consumer_loop", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"running main consumer thread\"", ")", "while", "not", "self", ".", "closed", ":", "if", "self", ".", "kafka_connected", ":", "self", ".", "_process_messages", "(", "...
The main consumer loop
[ "The", "main", "consumer", "loop" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L251-L257
train
215,562
istresearch/scrapy-cluster
rest/rest_service.py
RestService._process_messages
def _process_messages(self): """Processes messages received from kafka""" try: for message in self.consumer: try: if message is None: self.logger.debug("no message") break loaded_dict = json.loads(message.value) self.logger.debug("got valid kafka message") with self.uuids_lock: if 'uuid' in loaded_dict: if loaded_dict['uuid'] in self.uuids and \ self.uuids[loaded_dict['uuid']] != 'poll': self.logger.debug("Found Kafka message from request") self.uuids[loaded_dict['uuid']] = loaded_dict else: self.logger.debug("Got poll result") self._send_result_to_redis(loaded_dict) else: self.logger.debug("Got message not intended for this process") except ValueError: extras = {} if message is not None: extras["data"] = message.value self.logger.warning('Unparseable JSON Received from kafka', extra=extras) self._check_kafka_disconnect() except OffsetOutOfRangeError: # consumer has no idea where they are self.consumer.seek_to_end() self.logger.error("Kafka offset out of range error")
python
def _process_messages(self): """Processes messages received from kafka""" try: for message in self.consumer: try: if message is None: self.logger.debug("no message") break loaded_dict = json.loads(message.value) self.logger.debug("got valid kafka message") with self.uuids_lock: if 'uuid' in loaded_dict: if loaded_dict['uuid'] in self.uuids and \ self.uuids[loaded_dict['uuid']] != 'poll': self.logger.debug("Found Kafka message from request") self.uuids[loaded_dict['uuid']] = loaded_dict else: self.logger.debug("Got poll result") self._send_result_to_redis(loaded_dict) else: self.logger.debug("Got message not intended for this process") except ValueError: extras = {} if message is not None: extras["data"] = message.value self.logger.warning('Unparseable JSON Received from kafka', extra=extras) self._check_kafka_disconnect() except OffsetOutOfRangeError: # consumer has no idea where they are self.consumer.seek_to_end() self.logger.error("Kafka offset out of range error")
[ "def", "_process_messages", "(", "self", ")", ":", "try", ":", "for", "message", "in", "self", ".", "consumer", ":", "try", ":", "if", "message", "is", "None", ":", "self", ".", "logger", ".", "debug", "(", "\"no message\"", ")", "break", "loaded_dict", ...
Processes messages received from kafka
[ "Processes", "messages", "received", "from", "kafka" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L259-L293
train
215,563
istresearch/scrapy-cluster
rest/rest_service.py
RestService._send_result_to_redis
def _send_result_to_redis(self, result): """Sends the result of a poll to redis to be used potentially by another process @param result: the result retrieved from kafka""" if self.redis_connected: self.logger.debug("Sending result to redis") try: key = "rest:poll:{u}".format(u=result['uuid']) self.redis_conn.set(key, json.dumps(result)) except ConnectionError: self.logger.error("Lost connection to Redis") self._spawn_redis_connection_thread() else: self.logger.warning("Unable to send result to redis, not connected")
python
def _send_result_to_redis(self, result): """Sends the result of a poll to redis to be used potentially by another process @param result: the result retrieved from kafka""" if self.redis_connected: self.logger.debug("Sending result to redis") try: key = "rest:poll:{u}".format(u=result['uuid']) self.redis_conn.set(key, json.dumps(result)) except ConnectionError: self.logger.error("Lost connection to Redis") self._spawn_redis_connection_thread() else: self.logger.warning("Unable to send result to redis, not connected")
[ "def", "_send_result_to_redis", "(", "self", ",", "result", ")", ":", "if", "self", ".", "redis_connected", ":", "self", ".", "logger", ".", "debug", "(", "\"Sending result to redis\"", ")", "try", ":", "key", "=", "\"rest:poll:{u}\"", ".", "format", "(", "u...
Sends the result of a poll to redis to be used potentially by another process @param result: the result retrieved from kafka
[ "Sends", "the", "result", "of", "a", "poll", "to", "redis", "to", "be", "used", "potentially", "by", "another", "process" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L295-L309
train
215,564
istresearch/scrapy-cluster
rest/rest_service.py
RestService._check_kafka_disconnect
def _check_kafka_disconnect(self): """Checks the kafka connection is still valid""" for node_id in self.consumer._client._conns: conn = self.consumer._client._conns[node_id] if conn.state == ConnectionStates.DISCONNECTED or \ conn.state == ConnectionStates.DISCONNECTING: self._spawn_kafka_connection_thread() break
python
def _check_kafka_disconnect(self): """Checks the kafka connection is still valid""" for node_id in self.consumer._client._conns: conn = self.consumer._client._conns[node_id] if conn.state == ConnectionStates.DISCONNECTED or \ conn.state == ConnectionStates.DISCONNECTING: self._spawn_kafka_connection_thread() break
[ "def", "_check_kafka_disconnect", "(", "self", ")", ":", "for", "node_id", "in", "self", ".", "consumer", ".", "_client", ".", "_conns", ":", "conn", "=", "self", ".", "consumer", ".", "_client", ".", "_conns", "[", "node_id", "]", "if", "conn", ".", "...
Checks the kafka connection is still valid
[ "Checks", "the", "kafka", "connection", "is", "still", "valid" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L311-L318
train
215,565
istresearch/scrapy-cluster
rest/rest_service.py
RestService._heartbeat_loop
def _heartbeat_loop(self): """A main run loop thread to do work""" self.logger.debug("running main heartbeat thread") while not self.closed: time.sleep(self.settings['SLEEP_TIME']) self._report_self()
python
def _heartbeat_loop(self): """A main run loop thread to do work""" self.logger.debug("running main heartbeat thread") while not self.closed: time.sleep(self.settings['SLEEP_TIME']) self._report_self()
[ "def", "_heartbeat_loop", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"running main heartbeat thread\"", ")", "while", "not", "self", ".", "closed", ":", "time", ".", "sleep", "(", "self", ".", "settings", "[", "'SLEEP_TIME'", "]", "...
A main run loop thread to do work
[ "A", "main", "run", "loop", "thread", "to", "do", "work" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L320-L325
train
215,566
istresearch/scrapy-cluster
rest/rest_service.py
RestService._setup_redis
def _setup_redis(self): """Returns a Redis Client""" if not self.closed: try: self.logger.debug("Creating redis connection to host " + str(self.settings['REDIS_HOST'])) self.redis_conn = redis.StrictRedis(host=self.settings['REDIS_HOST'], port=self.settings['REDIS_PORT'], db=self.settings['REDIS_DB']) self.redis_conn.info() self.redis_connected = True self.logger.info("Successfully connected to redis") except KeyError as e: self.logger.error('Missing setting named ' + str(e), {'ex': traceback.format_exc()}) except: self.logger.error("Couldn't initialize redis client.", {'ex': traceback.format_exc()}) raise
python
def _setup_redis(self): """Returns a Redis Client""" if not self.closed: try: self.logger.debug("Creating redis connection to host " + str(self.settings['REDIS_HOST'])) self.redis_conn = redis.StrictRedis(host=self.settings['REDIS_HOST'], port=self.settings['REDIS_PORT'], db=self.settings['REDIS_DB']) self.redis_conn.info() self.redis_connected = True self.logger.info("Successfully connected to redis") except KeyError as e: self.logger.error('Missing setting named ' + str(e), {'ex': traceback.format_exc()}) except: self.logger.error("Couldn't initialize redis client.", {'ex': traceback.format_exc()}) raise
[ "def", "_setup_redis", "(", "self", ")", ":", "if", "not", "self", ".", "closed", ":", "try", ":", "self", ".", "logger", ".", "debug", "(", "\"Creating redis connection to host \"", "+", "str", "(", "self", ".", "settings", "[", "'REDIS_HOST'", "]", ")", ...
Returns a Redis Client
[ "Returns", "a", "Redis", "Client" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L347-L365
train
215,567
istresearch/scrapy-cluster
rest/rest_service.py
RestService._setup_kafka
def _setup_kafka(self): """ Sets up kafka connections """ # close older connections if self.consumer is not None: self.logger.debug("Closing existing kafka consumer") self.consumer.close() self.consumer = None if self.producer is not None: self.logger.debug("Closing existing kafka producer") self.producer.flush() self.producer.close(timeout=10) self.producer = None # create new connections self._consumer_thread = None self.logger.debug("Creating kafka connections") self.consumer = self._create_consumer() if not self.closed: self.logger.debug("Kafka Conumer created") self.producer = self._create_producer() if not self.closed: self.logger.debug("Kafka Producer created") if not self.closed: self.kafka_connected = True self.logger.info("Connected successfully to Kafka") self._spawn_kafka_consumer_thread()
python
def _setup_kafka(self): """ Sets up kafka connections """ # close older connections if self.consumer is not None: self.logger.debug("Closing existing kafka consumer") self.consumer.close() self.consumer = None if self.producer is not None: self.logger.debug("Closing existing kafka producer") self.producer.flush() self.producer.close(timeout=10) self.producer = None # create new connections self._consumer_thread = None self.logger.debug("Creating kafka connections") self.consumer = self._create_consumer() if not self.closed: self.logger.debug("Kafka Conumer created") self.producer = self._create_producer() if not self.closed: self.logger.debug("Kafka Producer created") if not self.closed: self.kafka_connected = True self.logger.info("Connected successfully to Kafka") self._spawn_kafka_consumer_thread()
[ "def", "_setup_kafka", "(", "self", ")", ":", "# close older connections", "if", "self", ".", "consumer", "is", "not", "None", ":", "self", ".", "logger", ".", "debug", "(", "\"Closing existing kafka consumer\"", ")", "self", ".", "consumer", ".", "close", "("...
Sets up kafka connections
[ "Sets", "up", "kafka", "connections" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L367-L395
train
215,568
istresearch/scrapy-cluster
rest/rest_service.py
RestService._create_consumer
def _create_consumer(self): """Tries to establing the Kafka consumer connection""" if not self.closed: try: self.logger.debug("Creating new kafka consumer using brokers: " + str(self.settings['KAFKA_HOSTS']) + ' and topic ' + self.settings['KAFKA_TOPIC_PREFIX'] + ".outbound_firehose") return KafkaConsumer( self.settings['KAFKA_TOPIC_PREFIX'] + ".outbound_firehose", group_id=None, bootstrap_servers=self.settings['KAFKA_HOSTS'], consumer_timeout_ms=self.settings['KAFKA_CONSUMER_TIMEOUT'], auto_offset_reset=self.settings['KAFKA_CONSUMER_AUTO_OFFSET_RESET'], auto_commit_interval_ms=self.settings['KAFKA_CONSUMER_COMMIT_INTERVAL_MS'], enable_auto_commit=self.settings['KAFKA_CONSUMER_AUTO_COMMIT_ENABLE'], max_partition_fetch_bytes=self.settings['KAFKA_CONSUMER_FETCH_MESSAGE_MAX_BYTES']) except KeyError as e: self.logger.error('Missing setting named ' + str(e), {'ex': traceback.format_exc()}) except: self.logger.error("Couldn't initialize kafka consumer for topic", {'ex': traceback.format_exc()}) raise
python
def _create_consumer(self): """Tries to establing the Kafka consumer connection""" if not self.closed: try: self.logger.debug("Creating new kafka consumer using brokers: " + str(self.settings['KAFKA_HOSTS']) + ' and topic ' + self.settings['KAFKA_TOPIC_PREFIX'] + ".outbound_firehose") return KafkaConsumer( self.settings['KAFKA_TOPIC_PREFIX'] + ".outbound_firehose", group_id=None, bootstrap_servers=self.settings['KAFKA_HOSTS'], consumer_timeout_ms=self.settings['KAFKA_CONSUMER_TIMEOUT'], auto_offset_reset=self.settings['KAFKA_CONSUMER_AUTO_OFFSET_RESET'], auto_commit_interval_ms=self.settings['KAFKA_CONSUMER_COMMIT_INTERVAL_MS'], enable_auto_commit=self.settings['KAFKA_CONSUMER_AUTO_COMMIT_ENABLE'], max_partition_fetch_bytes=self.settings['KAFKA_CONSUMER_FETCH_MESSAGE_MAX_BYTES']) except KeyError as e: self.logger.error('Missing setting named ' + str(e), {'ex': traceback.format_exc()}) except: self.logger.error("Couldn't initialize kafka consumer for topic", {'ex': traceback.format_exc()}) raise
[ "def", "_create_consumer", "(", "self", ")", ":", "if", "not", "self", ".", "closed", ":", "try", ":", "self", ".", "logger", ".", "debug", "(", "\"Creating new kafka consumer using brokers: \"", "+", "str", "(", "self", ".", "settings", "[", "'KAFKA_HOSTS'", ...
Tries to establing the Kafka consumer connection
[ "Tries", "to", "establing", "the", "Kafka", "consumer", "connection" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L398-L422
train
215,569
istresearch/scrapy-cluster
rest/rest_service.py
RestService.run
def run(self): """Main flask run loop""" self.logger.info("Running main flask method on port " + str(self.settings['FLASK_PORT'])) self.app.run(host='0.0.0.0', port=self.settings['FLASK_PORT'])
python
def run(self): """Main flask run loop""" self.logger.info("Running main flask method on port " + str(self.settings['FLASK_PORT'])) self.app.run(host='0.0.0.0', port=self.settings['FLASK_PORT'])
[ "def", "run", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Running main flask method on port \"", "+", "str", "(", "self", ".", "settings", "[", "'FLASK_PORT'", "]", ")", ")", "self", ".", "app", ".", "run", "(", "host", "=", "'0....
Main flask run loop
[ "Main", "flask", "run", "loop" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L445-L449
train
215,570
istresearch/scrapy-cluster
rest/rest_service.py
RestService._create_ret_object
def _create_ret_object(self, status=SUCCESS, data=None, error=False, error_message=None, error_cause=None): """ Create generic reponse objects. :param str status: The SUCCESS or FAILURE of the request :param obj data: The data to return :param bool error: Set to True to add Error response :param str error_message: The generic error message :param str error_cause: The cause of the error :returns: A dictionary of values """ ret = {} if status == self.FAILURE: ret['status'] = self.FAILURE else: ret['status'] = self.SUCCESS ret['data'] = data if error: ret['error'] = {} if error_message is not None: ret['error']['message'] = error_message if error_cause is not None: ret['error']['cause'] = error_cause else: ret['error'] = None return ret
python
def _create_ret_object(self, status=SUCCESS, data=None, error=False, error_message=None, error_cause=None): """ Create generic reponse objects. :param str status: The SUCCESS or FAILURE of the request :param obj data: The data to return :param bool error: Set to True to add Error response :param str error_message: The generic error message :param str error_cause: The cause of the error :returns: A dictionary of values """ ret = {} if status == self.FAILURE: ret['status'] = self.FAILURE else: ret['status'] = self.SUCCESS ret['data'] = data if error: ret['error'] = {} if error_message is not None: ret['error']['message'] = error_message if error_cause is not None: ret['error']['cause'] = error_cause else: ret['error'] = None return ret
[ "def", "_create_ret_object", "(", "self", ",", "status", "=", "SUCCESS", ",", "data", "=", "None", ",", "error", "=", "False", ",", "error_message", "=", "None", ",", "error_cause", "=", "None", ")", ":", "ret", "=", "{", "}", "if", "status", "==", "...
Create generic reponse objects. :param str status: The SUCCESS or FAILURE of the request :param obj data: The data to return :param bool error: Set to True to add Error response :param str error_message: The generic error message :param str error_cause: The cause of the error :returns: A dictionary of values
[ "Create", "generic", "reponse", "objects", "." ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L451-L478
train
215,571
istresearch/scrapy-cluster
rest/rest_service.py
RestService._close_thread
def _close_thread(self, thread, thread_name): """Closes daemon threads @param thread: the thread to close @param thread_name: a human readable name of the thread """ if thread is not None and thread.isAlive(): self.logger.debug("Waiting for {} thread to close".format(thread_name)) thread.join(timeout=self.settings['DAEMON_THREAD_JOIN_TIMEOUT']) if thread.isAlive(): self.logger.warn("{} daemon thread unable to be shutdown" " within timeout".format(thread_name))
python
def _close_thread(self, thread, thread_name): """Closes daemon threads @param thread: the thread to close @param thread_name: a human readable name of the thread """ if thread is not None and thread.isAlive(): self.logger.debug("Waiting for {} thread to close".format(thread_name)) thread.join(timeout=self.settings['DAEMON_THREAD_JOIN_TIMEOUT']) if thread.isAlive(): self.logger.warn("{} daemon thread unable to be shutdown" " within timeout".format(thread_name))
[ "def", "_close_thread", "(", "self", ",", "thread", ",", "thread_name", ")", ":", "if", "thread", "is", "not", "None", "and", "thread", ".", "isAlive", "(", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Waiting for {} thread to close\"", ".", "for...
Closes daemon threads @param thread: the thread to close @param thread_name: a human readable name of the thread
[ "Closes", "daemon", "threads" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L480-L491
train
215,572
istresearch/scrapy-cluster
rest/rest_service.py
RestService.close
def close(self): """ Cleans up anything from the process """ self.logger.info("Closing Rest Service") self.closed = True # close threads self._close_thread(self._redis_thread, "Redis setup") self._close_thread(self._heartbeat_thread, "Heartbeat") self._close_thread(self._kafka_thread, "Kafka setup") self._close_thread(self._consumer_thread, "Consumer") # close kafka if self.consumer is not None: self.logger.debug("Closing kafka consumer") self.consumer.close() if self.producer is not None: self.logger.debug("Closing kafka producer") self.producer.close(timeout=10)
python
def close(self): """ Cleans up anything from the process """ self.logger.info("Closing Rest Service") self.closed = True # close threads self._close_thread(self._redis_thread, "Redis setup") self._close_thread(self._heartbeat_thread, "Heartbeat") self._close_thread(self._kafka_thread, "Kafka setup") self._close_thread(self._consumer_thread, "Consumer") # close kafka if self.consumer is not None: self.logger.debug("Closing kafka consumer") self.consumer.close() if self.producer is not None: self.logger.debug("Closing kafka producer") self.producer.close(timeout=10)
[ "def", "close", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Closing Rest Service\"", ")", "self", ".", "closed", "=", "True", "# close threads", "self", ".", "_close_thread", "(", "self", ".", "_redis_thread", ",", "\"Redis setup\"", "...
Cleans up anything from the process
[ "Cleans", "up", "anything", "from", "the", "process" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L493-L512
train
215,573
istresearch/scrapy-cluster
rest/rest_service.py
RestService._calculate_health
def _calculate_health(self): """Returns a string representation of the node health @returns: GREEN if fully connected, YELLOW if partially connected, RED if not connected """ if self.redis_connected and self.kafka_connected: return "GREEN" elif self.redis_connected or self.kafka_connected: return "YELLOW" else: return "RED"
python
def _calculate_health(self): """Returns a string representation of the node health @returns: GREEN if fully connected, YELLOW if partially connected, RED if not connected """ if self.redis_connected and self.kafka_connected: return "GREEN" elif self.redis_connected or self.kafka_connected: return "YELLOW" else: return "RED"
[ "def", "_calculate_health", "(", "self", ")", ":", "if", "self", ".", "redis_connected", "and", "self", ".", "kafka_connected", ":", "return", "\"GREEN\"", "elif", "self", ".", "redis_connected", "or", "self", ".", "kafka_connected", ":", "return", "\"YELLOW\"",...
Returns a string representation of the node health @returns: GREEN if fully connected, YELLOW if partially connected, RED if not connected
[ "Returns", "a", "string", "representation", "of", "the", "node", "health" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L514-L525
train
215,574
istresearch/scrapy-cluster
rest/rest_service.py
RestService._feed_to_kafka
def _feed_to_kafka(self, json_item): """Sends a request to Kafka :param json_item: The json item to send :returns: A boolean indicating whther the data was sent successfully or not """ @MethodTimer.timeout(self.settings['KAFKA_FEED_TIMEOUT'], False) def _feed(json_item): try: self.logger.debug("Sending json to kafka at " + str(self.settings['KAFKA_PRODUCER_TOPIC'])) future = self.producer.send(self.settings['KAFKA_PRODUCER_TOPIC'], json_item) future.add_callback(self._kafka_success) future.add_errback(self._kafka_failure) self.producer.flush() return True except Exception as e: self.logger.error("Lost connection to Kafka") self._spawn_kafka_connection_thread() return False return _feed(json_item)
python
def _feed_to_kafka(self, json_item): """Sends a request to Kafka :param json_item: The json item to send :returns: A boolean indicating whther the data was sent successfully or not """ @MethodTimer.timeout(self.settings['KAFKA_FEED_TIMEOUT'], False) def _feed(json_item): try: self.logger.debug("Sending json to kafka at " + str(self.settings['KAFKA_PRODUCER_TOPIC'])) future = self.producer.send(self.settings['KAFKA_PRODUCER_TOPIC'], json_item) future.add_callback(self._kafka_success) future.add_errback(self._kafka_failure) self.producer.flush() return True except Exception as e: self.logger.error("Lost connection to Kafka") self._spawn_kafka_connection_thread() return False return _feed(json_item)
[ "def", "_feed_to_kafka", "(", "self", ",", "json_item", ")", ":", "@", "MethodTimer", ".", "timeout", "(", "self", ".", "settings", "[", "'KAFKA_FEED_TIMEOUT'", "]", ",", "False", ")", "def", "_feed", "(", "json_item", ")", ":", "try", ":", "self", ".", ...
Sends a request to Kafka :param json_item: The json item to send :returns: A boolean indicating whther the data was sent successfully or not
[ "Sends", "a", "request", "to", "Kafka" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L540-L565
train
215,575
istresearch/scrapy-cluster
rest/rest_service.py
RestService._decorate_routes
def _decorate_routes(self): """ Decorates the routes to use within the flask app """ self.logger.debug("Decorating routes") # self.app.add_url_rule('/', 'catch', self.catch, methods=['GET'], # defaults={'path': ''}) self.app.add_url_rule('/<path:path>', 'catch', self.catch, methods=['GET', 'POST'], defaults={'path': ''}) self.app.add_url_rule('/', 'index', self.index, methods=['POST', 'GET']) self.app.add_url_rule('/feed', 'feed', self.feed, methods=['POST']) self.app.add_url_rule('/poll', 'poll', self.poll, methods=['POST'])
python
def _decorate_routes(self): """ Decorates the routes to use within the flask app """ self.logger.debug("Decorating routes") # self.app.add_url_rule('/', 'catch', self.catch, methods=['GET'], # defaults={'path': ''}) self.app.add_url_rule('/<path:path>', 'catch', self.catch, methods=['GET', 'POST'], defaults={'path': ''}) self.app.add_url_rule('/', 'index', self.index, methods=['POST', 'GET']) self.app.add_url_rule('/feed', 'feed', self.feed, methods=['POST']) self.app.add_url_rule('/poll', 'poll', self.poll, methods=['POST'])
[ "def", "_decorate_routes", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Decorating routes\"", ")", "# self.app.add_url_rule('/', 'catch', self.catch, methods=['GET'],", "# defaults={'path': ''})", "self", ".", "app", ".", "add_url...
Decorates the routes to use within the flask app
[ "Decorates", "the", "routes", "to", "use", "within", "the", "flask", "app" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L569-L583
train
215,576
istresearch/scrapy-cluster
rest/rest_service.py
RestService.poll
def poll(self): """Retrieves older requests that may not make it back quick enough""" if self.redis_connected: json_item = request.get_json() result = None try: key = "rest:poll:{u}".format(u=json_item['poll_id']) result = self.redis_conn.get(key) if result is not None: result = json.loads(result) self.logger.debug("Found previous poll") self.redis_conn.delete(key) return self._create_ret_object(self.SUCCESS, result) else: self.logger.debug("poll key does not exist") return self._create_ret_object(self.FAILURE, None, True, "Could not find matching poll_id"), 404 except ConnectionError: self.logger.error("Lost connection to Redis") self._spawn_redis_connection_thread() except ValueError: extras = { "value": result } self.logger.warning('Unparseable JSON Received from redis', extra=extras) self.redis_conn.delete(key) return self._create_ret_object(self.FAILURE, None, True, "Unparseable JSON Received " "from redis"), 500 self.logger.warn("Unable to poll redis, not connected") return self._create_ret_object(self.FAILURE, None, True, "Unable to connect to Redis"), 500
python
def poll(self): """Retrieves older requests that may not make it back quick enough""" if self.redis_connected: json_item = request.get_json() result = None try: key = "rest:poll:{u}".format(u=json_item['poll_id']) result = self.redis_conn.get(key) if result is not None: result = json.loads(result) self.logger.debug("Found previous poll") self.redis_conn.delete(key) return self._create_ret_object(self.SUCCESS, result) else: self.logger.debug("poll key does not exist") return self._create_ret_object(self.FAILURE, None, True, "Could not find matching poll_id"), 404 except ConnectionError: self.logger.error("Lost connection to Redis") self._spawn_redis_connection_thread() except ValueError: extras = { "value": result } self.logger.warning('Unparseable JSON Received from redis', extra=extras) self.redis_conn.delete(key) return self._create_ret_object(self.FAILURE, None, True, "Unparseable JSON Received " "from redis"), 500 self.logger.warn("Unable to poll redis, not connected") return self._create_ret_object(self.FAILURE, None, True, "Unable to connect to Redis"), 500
[ "def", "poll", "(", "self", ")", ":", "if", "self", ".", "redis_connected", ":", "json_item", "=", "request", ".", "get_json", "(", ")", "result", "=", "None", "try", ":", "key", "=", "\"rest:poll:{u}\"", ".", "format", "(", "u", "=", "json_item", "[",...
Retrieves older requests that may not make it back quick enough
[ "Retrieves", "older", "requests", "that", "may", "not", "make", "it", "back", "quick", "enough" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L661-L695
train
215,577
vimalloc/flask-jwt-extended
flask_jwt_extended/utils.py
create_refresh_token
def create_refresh_token(identity, expires_delta=None, user_claims=None): """ Creates a new refresh token. :param identity: The identity of this token, which can be any data that is json serializable. It can also be a python object, in which case you can use the :meth:`~flask_jwt_extended.JWTManager.user_identity_loader` to define a callback function that will be used to pull a json serializable identity out of the object. :param expires_delta: A `datetime.timedelta` for how long this token should last before it expires. Set to False to disable expiration. If this is None, it will use the 'JWT_REFRESH_TOKEN_EXPIRES` config value (see :ref:`Configuration Options`) :param user_claims: Optionnal JSON serializable to override user claims. :return: An encoded refresh token """ jwt_manager = _get_jwt_manager() return jwt_manager._create_refresh_token(identity, expires_delta, user_claims)
python
def create_refresh_token(identity, expires_delta=None, user_claims=None): """ Creates a new refresh token. :param identity: The identity of this token, which can be any data that is json serializable. It can also be a python object, in which case you can use the :meth:`~flask_jwt_extended.JWTManager.user_identity_loader` to define a callback function that will be used to pull a json serializable identity out of the object. :param expires_delta: A `datetime.timedelta` for how long this token should last before it expires. Set to False to disable expiration. If this is None, it will use the 'JWT_REFRESH_TOKEN_EXPIRES` config value (see :ref:`Configuration Options`) :param user_claims: Optionnal JSON serializable to override user claims. :return: An encoded refresh token """ jwt_manager = _get_jwt_manager() return jwt_manager._create_refresh_token(identity, expires_delta, user_claims)
[ "def", "create_refresh_token", "(", "identity", ",", "expires_delta", "=", "None", ",", "user_claims", "=", "None", ")", ":", "jwt_manager", "=", "_get_jwt_manager", "(", ")", "return", "jwt_manager", ".", "_create_refresh_token", "(", "identity", ",", "expires_de...
Creates a new refresh token. :param identity: The identity of this token, which can be any data that is json serializable. It can also be a python object, in which case you can use the :meth:`~flask_jwt_extended.JWTManager.user_identity_loader` to define a callback function that will be used to pull a json serializable identity out of the object. :param expires_delta: A `datetime.timedelta` for how long this token should last before it expires. Set to False to disable expiration. If this is None, it will use the 'JWT_REFRESH_TOKEN_EXPIRES` config value (see :ref:`Configuration Options`) :param user_claims: Optionnal JSON serializable to override user claims. :return: An encoded refresh token
[ "Creates", "a", "new", "refresh", "token", "." ]
569d3b89eb5d2586d0cff4581a346229c623cefc
https://github.com/vimalloc/flask-jwt-extended/blob/569d3b89eb5d2586d0cff4581a346229c623cefc/flask_jwt_extended/utils.py#L160-L179
train
215,578
vimalloc/flask-jwt-extended
examples/database_blacklist/blacklist_helpers.py
is_token_revoked
def is_token_revoked(decoded_token): """ Checks if the given token is revoked or not. Because we are adding all the tokens that we create into this database, if the token is not present in the database we are going to consider it revoked, as we don't know where it was created. """ jti = decoded_token['jti'] try: token = TokenBlacklist.query.filter_by(jti=jti).one() return token.revoked except NoResultFound: return True
python
def is_token_revoked(decoded_token): """ Checks if the given token is revoked or not. Because we are adding all the tokens that we create into this database, if the token is not present in the database we are going to consider it revoked, as we don't know where it was created. """ jti = decoded_token['jti'] try: token = TokenBlacklist.query.filter_by(jti=jti).one() return token.revoked except NoResultFound: return True
[ "def", "is_token_revoked", "(", "decoded_token", ")", ":", "jti", "=", "decoded_token", "[", "'jti'", "]", "try", ":", "token", "=", "TokenBlacklist", ".", "query", ".", "filter_by", "(", "jti", "=", "jti", ")", ".", "one", "(", ")", "return", "token", ...
Checks if the given token is revoked or not. Because we are adding all the tokens that we create into this database, if the token is not present in the database we are going to consider it revoked, as we don't know where it was created.
[ "Checks", "if", "the", "given", "token", "is", "revoked", "or", "not", ".", "Because", "we", "are", "adding", "all", "the", "tokens", "that", "we", "create", "into", "this", "database", "if", "the", "token", "is", "not", "present", "in", "the", "database...
569d3b89eb5d2586d0cff4581a346229c623cefc
https://github.com/vimalloc/flask-jwt-extended/blob/569d3b89eb5d2586d0cff4581a346229c623cefc/examples/database_blacklist/blacklist_helpers.py#L42-L54
train
215,579
vimalloc/flask-jwt-extended
examples/database_blacklist/blacklist_helpers.py
revoke_token
def revoke_token(token_id, user): """ Revokes the given token. Raises a TokenNotFound error if the token does not exist in the database """ try: token = TokenBlacklist.query.filter_by(id=token_id, user_identity=user).one() token.revoked = True db.session.commit() except NoResultFound: raise TokenNotFound("Could not find the token {}".format(token_id))
python
def revoke_token(token_id, user): """ Revokes the given token. Raises a TokenNotFound error if the token does not exist in the database """ try: token = TokenBlacklist.query.filter_by(id=token_id, user_identity=user).one() token.revoked = True db.session.commit() except NoResultFound: raise TokenNotFound("Could not find the token {}".format(token_id))
[ "def", "revoke_token", "(", "token_id", ",", "user", ")", ":", "try", ":", "token", "=", "TokenBlacklist", ".", "query", ".", "filter_by", "(", "id", "=", "token_id", ",", "user_identity", "=", "user", ")", ".", "one", "(", ")", "token", ".", "revoked"...
Revokes the given token. Raises a TokenNotFound error if the token does not exist in the database
[ "Revokes", "the", "given", "token", ".", "Raises", "a", "TokenNotFound", "error", "if", "the", "token", "does", "not", "exist", "in", "the", "database" ]
569d3b89eb5d2586d0cff4581a346229c623cefc
https://github.com/vimalloc/flask-jwt-extended/blob/569d3b89eb5d2586d0cff4581a346229c623cefc/examples/database_blacklist/blacklist_helpers.py#L65-L75
train
215,580
vimalloc/flask-jwt-extended
examples/database_blacklist/blacklist_helpers.py
prune_database
def prune_database(): """ Delete tokens that have expired from the database. How (and if) you call this is entirely up you. You could expose it to an endpoint that only administrators could call, you could run it as a cron, set it up with flask cli, etc. """ now = datetime.now() expired = TokenBlacklist.query.filter(TokenBlacklist.expires < now).all() for token in expired: db.session.delete(token) db.session.commit()
python
def prune_database(): """ Delete tokens that have expired from the database. How (and if) you call this is entirely up you. You could expose it to an endpoint that only administrators could call, you could run it as a cron, set it up with flask cli, etc. """ now = datetime.now() expired = TokenBlacklist.query.filter(TokenBlacklist.expires < now).all() for token in expired: db.session.delete(token) db.session.commit()
[ "def", "prune_database", "(", ")", ":", "now", "=", "datetime", ".", "now", "(", ")", "expired", "=", "TokenBlacklist", ".", "query", ".", "filter", "(", "TokenBlacklist", ".", "expires", "<", "now", ")", ".", "all", "(", ")", "for", "token", "in", "...
Delete tokens that have expired from the database. How (and if) you call this is entirely up you. You could expose it to an endpoint that only administrators could call, you could run it as a cron, set it up with flask cli, etc.
[ "Delete", "tokens", "that", "have", "expired", "from", "the", "database", "." ]
569d3b89eb5d2586d0cff4581a346229c623cefc
https://github.com/vimalloc/flask-jwt-extended/blob/569d3b89eb5d2586d0cff4581a346229c623cefc/examples/database_blacklist/blacklist_helpers.py#L91-L103
train
215,581
vimalloc/flask-jwt-extended
flask_jwt_extended/view_decorators.py
verify_jwt_in_request
def verify_jwt_in_request(): """ Ensure that the requester has a valid access token. This does not check the freshness of the access token. Raises an appropiate exception there is no token or if the token is invalid. """ if request.method not in config.exempt_methods: jwt_data = _decode_jwt_from_request(request_type='access') ctx_stack.top.jwt = jwt_data verify_token_claims(jwt_data) _load_user(jwt_data[config.identity_claim_key])
python
def verify_jwt_in_request(): """ Ensure that the requester has a valid access token. This does not check the freshness of the access token. Raises an appropiate exception there is no token or if the token is invalid. """ if request.method not in config.exempt_methods: jwt_data = _decode_jwt_from_request(request_type='access') ctx_stack.top.jwt = jwt_data verify_token_claims(jwt_data) _load_user(jwt_data[config.identity_claim_key])
[ "def", "verify_jwt_in_request", "(", ")", ":", "if", "request", ".", "method", "not", "in", "config", ".", "exempt_methods", ":", "jwt_data", "=", "_decode_jwt_from_request", "(", "request_type", "=", "'access'", ")", "ctx_stack", ".", "top", ".", "jwt", "=", ...
Ensure that the requester has a valid access token. This does not check the freshness of the access token. Raises an appropiate exception there is no token or if the token is invalid.
[ "Ensure", "that", "the", "requester", "has", "a", "valid", "access", "token", ".", "This", "does", "not", "check", "the", "freshness", "of", "the", "access", "token", ".", "Raises", "an", "appropiate", "exception", "there", "is", "no", "token", "or", "if",...
569d3b89eb5d2586d0cff4581a346229c623cefc
https://github.com/vimalloc/flask-jwt-extended/blob/569d3b89eb5d2586d0cff4581a346229c623cefc/flask_jwt_extended/view_decorators.py#L24-L34
train
215,582
vimalloc/flask-jwt-extended
flask_jwt_extended/view_decorators.py
verify_fresh_jwt_in_request
def verify_fresh_jwt_in_request(): """ Ensure that the requester has a valid and fresh access token. Raises an appropiate exception if there is no token, the token is invalid, or the token is not marked as fresh. """ if request.method not in config.exempt_methods: jwt_data = _decode_jwt_from_request(request_type='access') ctx_stack.top.jwt = jwt_data fresh = jwt_data['fresh'] if isinstance(fresh, bool): if not fresh: raise FreshTokenRequired('Fresh token required') else: now = timegm(datetime.utcnow().utctimetuple()) if fresh < now: raise FreshTokenRequired('Fresh token required') verify_token_claims(jwt_data) _load_user(jwt_data[config.identity_claim_key])
python
def verify_fresh_jwt_in_request(): """ Ensure that the requester has a valid and fresh access token. Raises an appropiate exception if there is no token, the token is invalid, or the token is not marked as fresh. """ if request.method not in config.exempt_methods: jwt_data = _decode_jwt_from_request(request_type='access') ctx_stack.top.jwt = jwt_data fresh = jwt_data['fresh'] if isinstance(fresh, bool): if not fresh: raise FreshTokenRequired('Fresh token required') else: now = timegm(datetime.utcnow().utctimetuple()) if fresh < now: raise FreshTokenRequired('Fresh token required') verify_token_claims(jwt_data) _load_user(jwt_data[config.identity_claim_key])
[ "def", "verify_fresh_jwt_in_request", "(", ")", ":", "if", "request", ".", "method", "not", "in", "config", ".", "exempt_methods", ":", "jwt_data", "=", "_decode_jwt_from_request", "(", "request_type", "=", "'access'", ")", "ctx_stack", ".", "top", ".", "jwt", ...
Ensure that the requester has a valid and fresh access token. Raises an appropiate exception if there is no token, the token is invalid, or the token is not marked as fresh.
[ "Ensure", "that", "the", "requester", "has", "a", "valid", "and", "fresh", "access", "token", ".", "Raises", "an", "appropiate", "exception", "if", "there", "is", "no", "token", "the", "token", "is", "invalid", "or", "the", "token", "is", "not", "marked", ...
569d3b89eb5d2586d0cff4581a346229c623cefc
https://github.com/vimalloc/flask-jwt-extended/blob/569d3b89eb5d2586d0cff4581a346229c623cefc/flask_jwt_extended/view_decorators.py#L58-L76
train
215,583
vimalloc/flask-jwt-extended
flask_jwt_extended/view_decorators.py
jwt_optional
def jwt_optional(fn): """ A decorator to optionally protect a Flask endpoint If an access token in present in the request, this will call the endpoint with :func:`~flask_jwt_extended.get_jwt_identity` having the identity of the access token. If no access token is present in the request, this endpoint will still be called, but :func:`~flask_jwt_extended.get_jwt_identity` will return `None` instead. If there is an invalid access token in the request (expired, tampered with, etc), this will still call the appropriate error handler instead of allowing the endpoint to be called as if there is no access token in the request. """ @wraps(fn) def wrapper(*args, **kwargs): verify_jwt_in_request_optional() return fn(*args, **kwargs) return wrapper
python
def jwt_optional(fn): """ A decorator to optionally protect a Flask endpoint If an access token in present in the request, this will call the endpoint with :func:`~flask_jwt_extended.get_jwt_identity` having the identity of the access token. If no access token is present in the request, this endpoint will still be called, but :func:`~flask_jwt_extended.get_jwt_identity` will return `None` instead. If there is an invalid access token in the request (expired, tampered with, etc), this will still call the appropriate error handler instead of allowing the endpoint to be called as if there is no access token in the request. """ @wraps(fn) def wrapper(*args, **kwargs): verify_jwt_in_request_optional() return fn(*args, **kwargs) return wrapper
[ "def", "jwt_optional", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "verify_jwt_in_request_optional", "(", ")", "return", "fn", "(", "*", "args", ",", "*", "*", "kwargs", ...
A decorator to optionally protect a Flask endpoint If an access token in present in the request, this will call the endpoint with :func:`~flask_jwt_extended.get_jwt_identity` having the identity of the access token. If no access token is present in the request, this endpoint will still be called, but :func:`~flask_jwt_extended.get_jwt_identity` will return `None` instead. If there is an invalid access token in the request (expired, tampered with, etc), this will still call the appropriate error handler instead of allowing the endpoint to be called as if there is no access token in the request.
[ "A", "decorator", "to", "optionally", "protect", "a", "Flask", "endpoint" ]
569d3b89eb5d2586d0cff4581a346229c623cefc
https://github.com/vimalloc/flask-jwt-extended/blob/569d3b89eb5d2586d0cff4581a346229c623cefc/flask_jwt_extended/view_decorators.py#L107-L125
train
215,584
MycroftAI/mycroft-precise
precise/model.py
load_precise_model
def load_precise_model(model_name: str) -> Any: """Loads a Keras model from file, handling custom loss function""" if not model_name.endswith('.net'): print('Warning: Unknown model type, ', model_name) inject_params(model_name) return load_keras().models.load_model(model_name)
python
def load_precise_model(model_name: str) -> Any: """Loads a Keras model from file, handling custom loss function""" if not model_name.endswith('.net'): print('Warning: Unknown model type, ', model_name) inject_params(model_name) return load_keras().models.load_model(model_name)
[ "def", "load_precise_model", "(", "model_name", ":", "str", ")", "->", "Any", ":", "if", "not", "model_name", ".", "endswith", "(", "'.net'", ")", ":", "print", "(", "'Warning: Unknown model type, '", ",", "model_name", ")", "inject_params", "(", "model_name", ...
Loads a Keras model from file, handling custom loss function
[ "Loads", "a", "Keras", "model", "from", "file", "handling", "custom", "loss", "function" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/model.py#L42-L48
train
215,585
MycroftAI/mycroft-precise
precise/model.py
create_model
def create_model(model_name: Optional[str], params: ModelParams) -> 'Sequential': """ Load or create a precise model Args: model_name: Name of model params: Parameters used to create the model Returns: model: Loaded Keras model """ if model_name and isfile(model_name): print('Loading from ' + model_name + '...') model = load_precise_model(model_name) else: from keras.layers.core import Dense from keras.layers.recurrent import GRU from keras.models import Sequential model = Sequential() model.add(GRU( params.recurrent_units, activation='linear', input_shape=(pr.n_features, pr.feature_size), dropout=params.dropout, name='net' )) model.add(Dense(1, activation='sigmoid')) load_keras() metrics = ['accuracy'] + params.extra_metrics * [false_pos, false_neg] set_loss_bias(params.loss_bias) for i in model.layers[:params.freeze_till]: i.trainable = False model.compile('rmsprop', weighted_log_loss, metrics=(not params.skip_acc) * metrics) return model
python
def create_model(model_name: Optional[str], params: ModelParams) -> 'Sequential': """ Load or create a precise model Args: model_name: Name of model params: Parameters used to create the model Returns: model: Loaded Keras model """ if model_name and isfile(model_name): print('Loading from ' + model_name + '...') model = load_precise_model(model_name) else: from keras.layers.core import Dense from keras.layers.recurrent import GRU from keras.models import Sequential model = Sequential() model.add(GRU( params.recurrent_units, activation='linear', input_shape=(pr.n_features, pr.feature_size), dropout=params.dropout, name='net' )) model.add(Dense(1, activation='sigmoid')) load_keras() metrics = ['accuracy'] + params.extra_metrics * [false_pos, false_neg] set_loss_bias(params.loss_bias) for i in model.layers[:params.freeze_till]: i.trainable = False model.compile('rmsprop', weighted_log_loss, metrics=(not params.skip_acc) * metrics) return model
[ "def", "create_model", "(", "model_name", ":", "Optional", "[", "str", "]", ",", "params", ":", "ModelParams", ")", "->", "'Sequential'", ":", "if", "model_name", "and", "isfile", "(", "model_name", ")", ":", "print", "(", "'Loading from '", "+", "model_name...
Load or create a precise model Args: model_name: Name of model params: Parameters used to create the model Returns: model: Loaded Keras model
[ "Load", "or", "create", "a", "precise", "model" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/model.py#L51-L83
train
215,586
MycroftAI/mycroft-precise
precise/scripts/train_generated.py
GeneratedTrainer.layer_with
def layer_with(self, sample: np.ndarray, value: int) -> np.ndarray: """Create an identical 2d array where the second row is filled with value""" b = np.full((2, len(sample)), value, dtype=float) b[0] = sample return b
python
def layer_with(self, sample: np.ndarray, value: int) -> np.ndarray: """Create an identical 2d array where the second row is filled with value""" b = np.full((2, len(sample)), value, dtype=float) b[0] = sample return b
[ "def", "layer_with", "(", "self", ",", "sample", ":", "np", ".", "ndarray", ",", "value", ":", "int", ")", "->", "np", ".", "ndarray", ":", "b", "=", "np", ".", "full", "(", "(", "2", ",", "len", "(", "sample", ")", ")", ",", "value", ",", "d...
Create an identical 2d array where the second row is filled with value
[ "Create", "an", "identical", "2d", "array", "where", "the", "second", "row", "is", "filled", "with", "value" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/scripts/train_generated.py#L116-L120
train
215,587
MycroftAI/mycroft-precise
precise/scripts/train_generated.py
GeneratedTrainer.generate_wakeword_pieces
def generate_wakeword_pieces(self, volume): """Generates chunks of audio that represent the wakeword stream""" while True: target = 1 if random() > 0.5 else 0 it = self.pos_files_it if target else self.neg_files_it sample_file = next(it) yield self.layer_with(self.normalize_volume_to(load_audio(sample_file), volume), target) yield self.layer_with(np.zeros(int(pr.sample_rate * (0.5 + 2.0 * random()))), 0)
python
def generate_wakeword_pieces(self, volume): """Generates chunks of audio that represent the wakeword stream""" while True: target = 1 if random() > 0.5 else 0 it = self.pos_files_it if target else self.neg_files_it sample_file = next(it) yield self.layer_with(self.normalize_volume_to(load_audio(sample_file), volume), target) yield self.layer_with(np.zeros(int(pr.sample_rate * (0.5 + 2.0 * random()))), 0)
[ "def", "generate_wakeword_pieces", "(", "self", ",", "volume", ")", ":", "while", "True", ":", "target", "=", "1", "if", "random", "(", ")", ">", "0.5", "else", "0", "it", "=", "self", ".", "pos_files_it", "if", "target", "else", "self", ".", "neg_file...
Generates chunks of audio that represent the wakeword stream
[ "Generates", "chunks", "of", "audio", "that", "represent", "the", "wakeword", "stream" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/scripts/train_generated.py#L122-L129
train
215,588
MycroftAI/mycroft-precise
precise/scripts/train_generated.py
GeneratedTrainer.chunk_audio_pieces
def chunk_audio_pieces(self, pieces, chunk_size): """Convert chunks of audio into a series of equally sized pieces""" left_over = np.array([]) for piece in pieces: if left_over.size == 0: combined = piece else: combined = np.concatenate([left_over, piece], axis=-1) for chunk in chunk_audio(combined.T, chunk_size): yield chunk.T left_over = piece[-(len(piece) % chunk_size):]
python
def chunk_audio_pieces(self, pieces, chunk_size): """Convert chunks of audio into a series of equally sized pieces""" left_over = np.array([]) for piece in pieces: if left_over.size == 0: combined = piece else: combined = np.concatenate([left_over, piece], axis=-1) for chunk in chunk_audio(combined.T, chunk_size): yield chunk.T left_over = piece[-(len(piece) % chunk_size):]
[ "def", "chunk_audio_pieces", "(", "self", ",", "pieces", ",", "chunk_size", ")", ":", "left_over", "=", "np", ".", "array", "(", "[", "]", ")", "for", "piece", "in", "pieces", ":", "if", "left_over", ".", "size", "==", "0", ":", "combined", "=", "pie...
Convert chunks of audio into a series of equally sized pieces
[ "Convert", "chunks", "of", "audio", "into", "a", "series", "of", "equally", "sized", "pieces" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/scripts/train_generated.py#L131-L141
train
215,589
MycroftAI/mycroft-precise
precise/scripts/train_generated.py
GeneratedTrainer.calc_volume
def calc_volume(self, sample: np.ndarray): """Find the RMS of the audio""" return sqrt(np.mean(np.square(sample)))
python
def calc_volume(self, sample: np.ndarray): """Find the RMS of the audio""" return sqrt(np.mean(np.square(sample)))
[ "def", "calc_volume", "(", "self", ",", "sample", ":", "np", ".", "ndarray", ")", ":", "return", "sqrt", "(", "np", ".", "mean", "(", "np", ".", "square", "(", "sample", ")", ")", ")" ]
Find the RMS of the audio
[ "Find", "the", "RMS", "of", "the", "audio" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/scripts/train_generated.py#L143-L145
train
215,590
MycroftAI/mycroft-precise
precise/scripts/train_generated.py
GeneratedTrainer.max_run_length
def max_run_length(x: np.ndarray, val: int): """Finds the maximum continuous length of the given value in the sequence""" if x.size == 0: return 0 else: y = np.array(x[1:] != x[:-1]) i = np.append(np.where(y), len(x) - 1) run_lengths = np.diff(np.append(-1, i)) run_length_values = x[i] return max([rl for rl, v in zip(run_lengths, run_length_values) if v == val], default=0)
python
def max_run_length(x: np.ndarray, val: int): """Finds the maximum continuous length of the given value in the sequence""" if x.size == 0: return 0 else: y = np.array(x[1:] != x[:-1]) i = np.append(np.where(y), len(x) - 1) run_lengths = np.diff(np.append(-1, i)) run_length_values = x[i] return max([rl for rl, v in zip(run_lengths, run_length_values) if v == val], default=0)
[ "def", "max_run_length", "(", "x", ":", "np", ".", "ndarray", ",", "val", ":", "int", ")", ":", "if", "x", ".", "size", "==", "0", ":", "return", "0", "else", ":", "y", "=", "np", ".", "array", "(", "x", "[", "1", ":", "]", "!=", "x", "[", ...
Finds the maximum continuous length of the given value in the sequence
[ "Finds", "the", "maximum", "continuous", "length", "of", "the", "given", "value", "in", "the", "sequence" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/scripts/train_generated.py#L156-L165
train
215,591
MycroftAI/mycroft-precise
precise/scripts/train_generated.py
GeneratedTrainer.samples_to_batches
def samples_to_batches(samples: Iterable, batch_size: int): """Chunk a series of network inputs and outputs into larger batches""" it = iter(samples) while True: with suppress(StopIteration): batch_in, batch_out = [], [] for i in range(batch_size): sample_in, sample_out = next(it) batch_in.append(sample_in) batch_out.append(sample_out) if not batch_in: raise StopIteration yield np.array(batch_in), np.array(batch_out)
python
def samples_to_batches(samples: Iterable, batch_size: int): """Chunk a series of network inputs and outputs into larger batches""" it = iter(samples) while True: with suppress(StopIteration): batch_in, batch_out = [], [] for i in range(batch_size): sample_in, sample_out = next(it) batch_in.append(sample_in) batch_out.append(sample_out) if not batch_in: raise StopIteration yield np.array(batch_in), np.array(batch_out)
[ "def", "samples_to_batches", "(", "samples", ":", "Iterable", ",", "batch_size", ":", "int", ")", ":", "it", "=", "iter", "(", "samples", ")", "while", "True", ":", "with", "suppress", "(", "StopIteration", ")", ":", "batch_in", ",", "batch_out", "=", "[...
Chunk a series of network inputs and outputs into larger batches
[ "Chunk", "a", "series", "of", "network", "inputs", "and", "outputs", "into", "larger", "batches" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/scripts/train_generated.py#L203-L215
train
215,592
MycroftAI/mycroft-precise
precise/scripts/train_generated.py
GeneratedTrainer.run
def run(self): """Train the model on randomly generated batches""" _, test_data = self.data.load(train=False, test=True) try: self.model.fit_generator( self.samples_to_batches(self.generate_samples(), self.args.batch_size), steps_per_epoch=self.args.steps_per_epoch, epochs=self.epoch + self.args.epochs, validation_data=test_data, callbacks=self.callbacks, initial_epoch=self.epoch ) finally: self.model.save(self.args.model) save_params(self.args.model)
python
def run(self): """Train the model on randomly generated batches""" _, test_data = self.data.load(train=False, test=True) try: self.model.fit_generator( self.samples_to_batches(self.generate_samples(), self.args.batch_size), steps_per_epoch=self.args.steps_per_epoch, epochs=self.epoch + self.args.epochs, validation_data=test_data, callbacks=self.callbacks, initial_epoch=self.epoch ) finally: self.model.save(self.args.model) save_params(self.args.model)
[ "def", "run", "(", "self", ")", ":", "_", ",", "test_data", "=", "self", ".", "data", ".", "load", "(", "train", "=", "False", ",", "test", "=", "True", ")", "try", ":", "self", ".", "model", ".", "fit_generator", "(", "self", ".", "samples_to_batc...
Train the model on randomly generated batches
[ "Train", "the", "model", "on", "randomly", "generated", "batches" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/scripts/train_generated.py#L226-L237
train
215,593
MycroftAI/mycroft-precise
precise/train_data.py
TrainData.from_both
def from_both(cls, tags_file: str, tags_folder: str, folder: str) -> 'TrainData': """Load data from both a database and a structured folder""" return cls.from_tags(tags_file, tags_folder) + cls.from_folder(folder)
python
def from_both(cls, tags_file: str, tags_folder: str, folder: str) -> 'TrainData': """Load data from both a database and a structured folder""" return cls.from_tags(tags_file, tags_folder) + cls.from_folder(folder)
[ "def", "from_both", "(", "cls", ",", "tags_file", ":", "str", ",", "tags_folder", ":", "str", ",", "folder", ":", "str", ")", "->", "'TrainData'", ":", "return", "cls", ".", "from_tags", "(", "tags_file", ",", "tags_folder", ")", "+", "cls", ".", "from...
Load data from both a database and a structured folder
[ "Load", "data", "from", "both", "a", "database", "and", "a", "structured", "folder" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/train_data.py#L113-L115
train
215,594
MycroftAI/mycroft-precise
precise/train_data.py
TrainData.load_inhibit
def load_inhibit(self, train=True, test=True) -> tuple: """Generate data with inhibitory inputs created from wake word samples""" def loader(kws: list, nkws: list): from precise.params import pr inputs = np.empty((0, pr.n_features, pr.feature_size)) outputs = np.zeros((len(kws), 1)) for f in kws: if not isfile(f): continue new_vec = load_vector(f, vectorize_inhibit) inputs = np.concatenate([inputs, new_vec]) return self.merge((inputs, outputs), self.__load_files(kws, nkws)) return self.__load(loader, train, test)
python
def load_inhibit(self, train=True, test=True) -> tuple: """Generate data with inhibitory inputs created from wake word samples""" def loader(kws: list, nkws: list): from precise.params import pr inputs = np.empty((0, pr.n_features, pr.feature_size)) outputs = np.zeros((len(kws), 1)) for f in kws: if not isfile(f): continue new_vec = load_vector(f, vectorize_inhibit) inputs = np.concatenate([inputs, new_vec]) return self.merge((inputs, outputs), self.__load_files(kws, nkws)) return self.__load(loader, train, test)
[ "def", "load_inhibit", "(", "self", ",", "train", "=", "True", ",", "test", "=", "True", ")", "->", "tuple", ":", "def", "loader", "(", "kws", ":", "list", ",", "nkws", ":", "list", ")", ":", "from", "precise", ".", "params", "import", "pr", "input...
Generate data with inhibitory inputs created from wake word samples
[ "Generate", "data", "with", "inhibitory", "inputs", "created", "from", "wake", "word", "samples" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/train_data.py#L126-L141
train
215,595
MycroftAI/mycroft-precise
precise/train_data.py
TrainData.parse_args
def parse_args(parser: ArgumentParser) -> Any: """Return parsed args from parser, adding options for train data inputs""" extra_usage = ''' :folder str Folder to load wav files from :-tf --tags-folder str {folder} Specify a different folder to load file ids in tags file from :-tg --tags-file str - Text file to load tags from where each line is <file_id> TAB (wake-word|not-wake-word) and {folder}/<file_id>.wav exists ''' add_to_parser(parser, extra_usage) args = parser.parse_args() args.tags_folder = args.tags_folder.format(folder=args.folder) return args
python
def parse_args(parser: ArgumentParser) -> Any: """Return parsed args from parser, adding options for train data inputs""" extra_usage = ''' :folder str Folder to load wav files from :-tf --tags-folder str {folder} Specify a different folder to load file ids in tags file from :-tg --tags-file str - Text file to load tags from where each line is <file_id> TAB (wake-word|not-wake-word) and {folder}/<file_id>.wav exists ''' add_to_parser(parser, extra_usage) args = parser.parse_args() args.tags_folder = args.tags_folder.format(folder=args.folder) return args
[ "def", "parse_args", "(", "parser", ":", "ArgumentParser", ")", "->", "Any", ":", "extra_usage", "=", "'''\n :folder str\n Folder to load wav files from\n \n :-tf --tags-folder str {folder}\n Specify a different folder to load fi...
Return parsed args from parser, adding options for train data inputs
[ "Return", "parsed", "args", "from", "parser", "adding", "options", "for", "train", "data", "inputs" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/train_data.py#L148-L167
train
215,596
MycroftAI/mycroft-precise
precise/vectorization.py
vectorize_raw
def vectorize_raw(audio: np.ndarray) -> np.ndarray: """Turns audio into feature vectors, without clipping for length""" if len(audio) == 0: raise InvalidAudio('Cannot vectorize empty audio!') return vectorizers[pr.vectorizer](audio)
python
def vectorize_raw(audio: np.ndarray) -> np.ndarray: """Turns audio into feature vectors, without clipping for length""" if len(audio) == 0: raise InvalidAudio('Cannot vectorize empty audio!') return vectorizers[pr.vectorizer](audio)
[ "def", "vectorize_raw", "(", "audio", ":", "np", ".", "ndarray", ")", "->", "np", ".", "ndarray", ":", "if", "len", "(", "audio", ")", "==", "0", ":", "raise", "InvalidAudio", "(", "'Cannot vectorize empty audio!'", ")", "return", "vectorizers", "[", "pr",...
Turns audio into feature vectors, without clipping for length
[ "Turns", "audio", "into", "feature", "vectors", "without", "clipping", "for", "length" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/vectorization.py#L42-L46
train
215,597
MycroftAI/mycroft-precise
precise/vectorization.py
vectorize_inhibit
def vectorize_inhibit(audio: np.ndarray) -> np.ndarray: """ Returns an array of inputs generated from the wake word audio that shouldn't cause an activation """ def samp(x): return int(pr.sample_rate * x) inputs = [] for offset in range(samp(inhibit_t), samp(inhibit_dist_t), samp(inhibit_hop_t)): if len(audio) - offset < samp(pr.buffer_t / 2.): break inputs.append(vectorize(audio[:-offset])) return np.array(inputs) if inputs else np.empty((0, pr.n_features, pr.feature_size))
python
def vectorize_inhibit(audio: np.ndarray) -> np.ndarray: """ Returns an array of inputs generated from the wake word audio that shouldn't cause an activation """ def samp(x): return int(pr.sample_rate * x) inputs = [] for offset in range(samp(inhibit_t), samp(inhibit_dist_t), samp(inhibit_hop_t)): if len(audio) - offset < samp(pr.buffer_t / 2.): break inputs.append(vectorize(audio[:-offset])) return np.array(inputs) if inputs else np.empty((0, pr.n_features, pr.feature_size))
[ "def", "vectorize_inhibit", "(", "audio", ":", "np", ".", "ndarray", ")", "->", "np", ".", "ndarray", ":", "def", "samp", "(", "x", ")", ":", "return", "int", "(", "pr", ".", "sample_rate", "*", "x", ")", "inputs", "=", "[", "]", "for", "offset", ...
Returns an array of inputs generated from the wake word audio that shouldn't cause an activation
[ "Returns", "an", "array", "of", "inputs", "generated", "from", "the", "wake", "word", "audio", "that", "shouldn", "t", "cause", "an", "activation" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/vectorization.py#L83-L97
train
215,598
MycroftAI/mycroft-precise
runner/precise_runner/runner.py
TriggerDetector.update
def update(self, prob): # type: (float) -> bool """Returns whether the new prediction caused an activation""" chunk_activated = prob > 1.0 - self.sensitivity if chunk_activated or self.activation < 0: self.activation += 1 has_activated = self.activation > self.trigger_level if has_activated or chunk_activated and self.activation < 0: self.activation = -(8 * 2048) // self.chunk_size if has_activated: return True elif self.activation > 0: self.activation -= 1 return False
python
def update(self, prob): # type: (float) -> bool """Returns whether the new prediction caused an activation""" chunk_activated = prob > 1.0 - self.sensitivity if chunk_activated or self.activation < 0: self.activation += 1 has_activated = self.activation > self.trigger_level if has_activated or chunk_activated and self.activation < 0: self.activation = -(8 * 2048) // self.chunk_size if has_activated: return True elif self.activation > 0: self.activation -= 1 return False
[ "def", "update", "(", "self", ",", "prob", ")", ":", "# type: (float) -> bool", "chunk_activated", "=", "prob", ">", "1.0", "-", "self", ".", "sensitivity", "if", "chunk_activated", "or", "self", ".", "activation", "<", "0", ":", "self", ".", "activation", ...
Returns whether the new prediction caused an activation
[ "Returns", "whether", "the", "new", "prediction", "caused", "an", "activation" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/runner/precise_runner/runner.py#L107-L122
train
215,599