id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
220,700
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...
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...
[ "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
220,701
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 dec...
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 dec...
[ "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
220,702
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: ...
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: ...
[ "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
220,703
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, N...
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, N...
[ "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
220,704
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()) ...
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()) ...
[ "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
220,705
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: se...
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: se...
[ "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
220,706
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.sta...
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.sta...
[ "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
220,707
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.sta...
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.sta...
[ "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
220,708
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
220,709
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 = js...
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 = js...
[ "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
220,710
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: ...
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: ...
[ "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
220,711
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.DIS...
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.DIS...
[ "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
220,712
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
220,713
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['R...
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['R...
[ "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
220,714
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 No...
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 No...
[ "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
220,715
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 ' + ...
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 ' + ...
[ "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
220,716
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
220,717
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 err...
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 err...
[ "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 ...
[ "Create", "generic", "reponse", "objects", "." ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L451-L478
220,718
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...
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...
[ "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
220,719
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") ...
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") ...
[ "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
220,720
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...
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...
[ "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
220,721
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):...
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):...
[ "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
220,722
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('/<...
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('/<...
[ "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
220,723
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....
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....
[ "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
220,724
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 ...
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 ...
[ "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` ...
[ "Creates", "a", "new", "refresh", "token", "." ]
569d3b89eb5d2586d0cff4581a346229c623cefc
https://github.com/vimalloc/flask-jwt-extended/blob/569d3b89eb5d2586d0cff4581a346229c623cefc/flask_jwt_extended/utils.py#L160-L179
220,725
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 = deco...
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 = deco...
[ "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
220,726
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 N...
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 N...
[ "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
220,727
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...
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...
[ "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
220,728
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_...
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_...
[ "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
220,729
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_...
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_...
[ "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
220,730
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 en...
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 en...
[ "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 ...
[ "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
220,731
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
220,732
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): ...
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): ...
[ "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
220,733
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
220,734
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_w...
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_w...
[ "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
220,735
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([le...
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([le...
[ "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
220,736
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
220,737
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.a...
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.a...
[ "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
220,738
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): ...
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): ...
[ "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
220,739
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, ...
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, ...
[ "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
220,740
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
220,741
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.zero...
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.zero...
[ "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
220,742
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 f...
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 f...
[ "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
220,743
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
220,744
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(i...
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(i...
[ "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
220,745
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.tr...
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.tr...
[ "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
220,746
MycroftAI/mycroft-precise
runner/precise_runner/runner.py
PreciseRunner.start
def start(self): """Start listening from stream""" if self.stream is None: from pyaudio import PyAudio, paInt16 self.pa = PyAudio() self.stream = self.pa.open( 16000, 1, paInt16, True, frames_per_buffer=self.chunk_size ) self._wrap...
python
def start(self): """Start listening from stream""" if self.stream is None: from pyaudio import PyAudio, paInt16 self.pa = PyAudio() self.stream = self.pa.open( 16000, 1, paInt16, True, frames_per_buffer=self.chunk_size ) self._wrap...
[ "def", "start", "(", "self", ")", ":", "if", "self", ".", "stream", "is", "None", ":", "from", "pyaudio", "import", "PyAudio", ",", "paInt16", "self", ".", "pa", "=", "PyAudio", "(", ")", "self", ".", "stream", "=", "self", ".", "pa", ".", "open", ...
Start listening from stream
[ "Start", "listening", "from", "stream" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/runner/precise_runner/runner.py#L172-L188
220,747
MycroftAI/mycroft-precise
runner/precise_runner/runner.py
PreciseRunner.stop
def stop(self): """Stop listening and close stream""" if self.thread: self.running = False if isinstance(self.stream, ReadWriteStream): self.stream.write(b'\0' * self.chunk_size) self.thread.join() self.thread = None self.engine.st...
python
def stop(self): """Stop listening and close stream""" if self.thread: self.running = False if isinstance(self.stream, ReadWriteStream): self.stream.write(b'\0' * self.chunk_size) self.thread.join() self.thread = None self.engine.st...
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "thread", ":", "self", ".", "running", "=", "False", "if", "isinstance", "(", "self", ".", "stream", ",", "ReadWriteStream", ")", ":", "self", ".", "stream", ".", "write", "(", "b'\\0'", "*", ...
Stop listening and close stream
[ "Stop", "listening", "and", "close", "stream" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/runner/precise_runner/runner.py#L190-L204
220,748
MycroftAI/mycroft-precise
runner/precise_runner/runner.py
PreciseRunner._handle_predictions
def _handle_predictions(self): """Continuously check Precise process output""" while self.running: chunk = self.stream.read(self.chunk_size) if self.is_paused: continue prob = self.engine.get_prediction(chunk) self.on_prediction(prob) ...
python
def _handle_predictions(self): """Continuously check Precise process output""" while self.running: chunk = self.stream.read(self.chunk_size) if self.is_paused: continue prob = self.engine.get_prediction(chunk) self.on_prediction(prob) ...
[ "def", "_handle_predictions", "(", "self", ")", ":", "while", "self", ".", "running", ":", "chunk", "=", "self", ".", "stream", ".", "read", "(", "self", ".", "chunk_size", ")", "if", "self", ".", "is_paused", ":", "continue", "prob", "=", "self", ".",...
Continuously check Precise process output
[ "Continuously", "check", "Precise", "process", "output" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/runner/precise_runner/runner.py#L212-L223
220,749
MycroftAI/mycroft-precise
precise/stats.py
Stats.calc_filenames
def calc_filenames(self, is_correct: bool, actual_output: bool, threshold=0.5) -> list: """Find a list of files with the given classification""" return [ filename for output, target, filename in zip(self.outputs, self.targets, self.filenames) if ((output > threshold) ...
python
def calc_filenames(self, is_correct: bool, actual_output: bool, threshold=0.5) -> list: """Find a list of files with the given classification""" return [ filename for output, target, filename in zip(self.outputs, self.targets, self.filenames) if ((output > threshold) ...
[ "def", "calc_filenames", "(", "self", ",", "is_correct", ":", "bool", ",", "actual_output", ":", "bool", ",", "threshold", "=", "0.5", ")", "->", "list", ":", "return", "[", "filename", "for", "output", ",", "target", ",", "filename", "in", "zip", "(", ...
Find a list of files with the given classification
[ "Find", "a", "list", "of", "files", "with", "the", "given", "classification" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/stats.py#L90-L96
220,750
MycroftAI/mycroft-precise
precise/scripts/graph.py
get_thresholds
def get_thresholds(points=100, power=3) -> list: """Run a function with a series of thresholds between 0 and 1""" return [(i / (points + 1)) ** power for i in range(1, points + 1)]
python
def get_thresholds(points=100, power=3) -> list: """Run a function with a series of thresholds between 0 and 1""" return [(i / (points + 1)) ** power for i in range(1, points + 1)]
[ "def", "get_thresholds", "(", "points", "=", "100", ",", "power", "=", "3", ")", "->", "list", ":", "return", "[", "(", "i", "/", "(", "points", "+", "1", ")", ")", "**", "power", "for", "i", "in", "range", "(", "1", ",", "points", "+", "1", ...
Run a function with a series of thresholds between 0 and 1
[ "Run", "a", "function", "with", "a", "series", "of", "thresholds", "between", "0", "and", "1" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/scripts/graph.py#L57-L59
220,751
MycroftAI/mycroft-precise
precise/scripts/graph.py
CachedDataLoader.load_for
def load_for(self, model: str) -> Tuple[list, list]: """Injects the model parameters, reloading if they changed, and returning the data""" inject_params(model) if self.prev_cache != pr.vectorization_md5_hash(): self.prev_cache = pr.vectorization_md5_hash() self.data = sel...
python
def load_for(self, model: str) -> Tuple[list, list]: """Injects the model parameters, reloading if they changed, and returning the data""" inject_params(model) if self.prev_cache != pr.vectorization_md5_hash(): self.prev_cache = pr.vectorization_md5_hash() self.data = sel...
[ "def", "load_for", "(", "self", ",", "model", ":", "str", ")", "->", "Tuple", "[", "list", ",", "list", "]", ":", "inject_params", "(", "model", ")", "if", "self", ".", "prev_cache", "!=", "pr", ".", "vectorization_md5_hash", "(", ")", ":", "self", "...
Injects the model parameters, reloading if they changed, and returning the data
[ "Injects", "the", "model", "parameters", "reloading", "if", "they", "changed", "and", "returning", "the", "data" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/scripts/graph.py#L75-L81
220,752
MycroftAI/mycroft-precise
precise/util.py
buffer_to_audio
def buffer_to_audio(buffer: bytes) -> np.ndarray: """Convert a raw mono audio byte string to numpy array of floats""" return np.fromstring(buffer, dtype='<i2').astype(np.float32, order='C') / 32768.0
python
def buffer_to_audio(buffer: bytes) -> np.ndarray: """Convert a raw mono audio byte string to numpy array of floats""" return np.fromstring(buffer, dtype='<i2').astype(np.float32, order='C') / 32768.0
[ "def", "buffer_to_audio", "(", "buffer", ":", "bytes", ")", "->", "np", ".", "ndarray", ":", "return", "np", ".", "fromstring", "(", "buffer", ",", "dtype", "=", "'<i2'", ")", ".", "astype", "(", "np", ".", "float32", ",", "order", "=", "'C'", ")", ...
Convert a raw mono audio byte string to numpy array of floats
[ "Convert", "a", "raw", "mono", "audio", "byte", "string", "to", "numpy", "array", "of", "floats" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/util.py#L31-L33
220,753
MycroftAI/mycroft-precise
precise/util.py
find_wavs
def find_wavs(folder: str) -> Tuple[List[str], List[str]]: """Finds wake-word and not-wake-word wavs in folder""" return (glob_all(join(folder, 'wake-word'), '*.wav'), glob_all(join(folder, 'not-wake-word'), '*.wav'))
python
def find_wavs(folder: str) -> Tuple[List[str], List[str]]: """Finds wake-word and not-wake-word wavs in folder""" return (glob_all(join(folder, 'wake-word'), '*.wav'), glob_all(join(folder, 'not-wake-word'), '*.wav'))
[ "def", "find_wavs", "(", "folder", ":", "str", ")", "->", "Tuple", "[", "List", "[", "str", "]", ",", "List", "[", "str", "]", "]", ":", "return", "(", "glob_all", "(", "join", "(", "folder", ",", "'wake-word'", ")", ",", "'*.wav'", ")", ",", "gl...
Finds wake-word and not-wake-word wavs in folder
[ "Finds", "wake", "-", "word", "and", "not", "-", "wake", "-", "word", "wavs", "in", "folder" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/util.py#L98-L101
220,754
MycroftAI/mycroft-precise
precise/scripts/convert.py
convert
def convert(model_path: str, out_file: str): """ Converts an HD5F file from Keras to a .pb for use with TensorFlow Args: model_path: location of Keras model out_file: location to write protobuf """ print('Converting', model_path, 'to', out_file, '...') import tensorflow as tf ...
python
def convert(model_path: str, out_file: str): """ Converts an HD5F file from Keras to a .pb for use with TensorFlow Args: model_path: location of Keras model out_file: location to write protobuf """ print('Converting', model_path, 'to', out_file, '...') import tensorflow as tf ...
[ "def", "convert", "(", "model_path", ":", "str", ",", "out_file", ":", "str", ")", ":", "print", "(", "'Converting'", ",", "model_path", ",", "'to'", ",", "out_file", ",", "'...'", ")", "import", "tensorflow", "as", "tf", "from", "precise", ".", "model",...
Converts an HD5F file from Keras to a .pb for use with TensorFlow Args: model_path: location of Keras model out_file: location to write protobuf
[ "Converts", "an", "HD5F", "file", "from", "Keras", "to", "a", ".", "pb", "for", "use", "with", "TensorFlow" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/scripts/convert.py#L32-L76
220,755
MycroftAI/mycroft-precise
precise/params.py
inject_params
def inject_params(model_name: str) -> ListenerParams: """Set the global listener params to a saved model""" params_file = model_name + '.params' try: with open(params_file) as f: pr.__dict__.update(compatibility_params, **json.load(f)) except (OSError, ValueError, TypeError): ...
python
def inject_params(model_name: str) -> ListenerParams: """Set the global listener params to a saved model""" params_file = model_name + '.params' try: with open(params_file) as f: pr.__dict__.update(compatibility_params, **json.load(f)) except (OSError, ValueError, TypeError): ...
[ "def", "inject_params", "(", "model_name", ":", "str", ")", "->", "ListenerParams", ":", "params_file", "=", "model_name", "+", "'.params'", "try", ":", "with", "open", "(", "params_file", ")", "as", "f", ":", "pr", ".", "__dict__", ".", "update", "(", "...
Set the global listener params to a saved model
[ "Set", "the", "global", "listener", "params", "to", "a", "saved", "model" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/params.py#L96-L105
220,756
MycroftAI/mycroft-precise
precise/params.py
save_params
def save_params(model_name: str): """Save current global listener params to a file""" with open(model_name + '.params', 'w') as f: json.dump(pr.__dict__, f)
python
def save_params(model_name: str): """Save current global listener params to a file""" with open(model_name + '.params', 'w') as f: json.dump(pr.__dict__, f)
[ "def", "save_params", "(", "model_name", ":", "str", ")", ":", "with", "open", "(", "model_name", "+", "'.params'", ",", "'w'", ")", "as", "f", ":", "json", ".", "dump", "(", "pr", ".", "__dict__", ",", "f", ")" ]
Save current global listener params to a file
[ "Save", "current", "global", "listener", "params", "to", "a", "file" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/params.py#L108-L111
220,757
MycroftAI/mycroft-precise
precise/scripts/train_incremental.py
IncrementalTrainer.retrain
def retrain(self): """Train for a session, pulling in any new data from the filesystem""" folder = TrainData.from_folder(self.args.folder) train_data, test_data = folder.load(True, not self.args.no_validation) train_data = TrainData.merge(train_data, self.sampled_data) test_data...
python
def retrain(self): """Train for a session, pulling in any new data from the filesystem""" folder = TrainData.from_folder(self.args.folder) train_data, test_data = folder.load(True, not self.args.no_validation) train_data = TrainData.merge(train_data, self.sampled_data) test_data...
[ "def", "retrain", "(", "self", ")", ":", "folder", "=", "TrainData", ".", "from_folder", "(", "self", ".", "args", ".", "folder", ")", "train_data", ",", "test_data", "=", "folder", ".", "load", "(", "True", ",", "not", "self", ".", "args", ".", "no_...
Train for a session, pulling in any new data from the filesystem
[ "Train", "for", "a", "session", "pulling", "in", "any", "new", "data", "from", "the", "filesystem" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/scripts/train_incremental.py#L95-L110
220,758
MycroftAI/mycroft-precise
precise/scripts/train_incremental.py
IncrementalTrainer.train_on_audio
def train_on_audio(self, fn: str): """Run through a single audio file""" save_test = random() > 0.8 audio = load_audio(fn) num_chunks = len(audio) // self.args.chunk_size self.listener.clear() for i, chunk in enumerate(chunk_audio(audio, self.args.chunk_size)): ...
python
def train_on_audio(self, fn: str): """Run through a single audio file""" save_test = random() > 0.8 audio = load_audio(fn) num_chunks = len(audio) // self.args.chunk_size self.listener.clear() for i, chunk in enumerate(chunk_audio(audio, self.args.chunk_size)): ...
[ "def", "train_on_audio", "(", "self", ",", "fn", ":", "str", ")", ":", "save_test", "=", "random", "(", ")", ">", "0.8", "audio", "=", "load_audio", "(", "fn", ")", "num_chunks", "=", "len", "(", "audio", ")", "//", "self", ".", "args", ".", "chunk...
Run through a single audio file
[ "Run", "through", "a", "single", "audio", "file" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/scripts/train_incremental.py#L112-L136
220,759
MycroftAI/mycroft-precise
precise/scripts/train_incremental.py
IncrementalTrainer.run
def run(self): """ Begin reading through audio files, saving false activations and retraining when necessary """ for fn in glob_all(self.args.random_data_folder, '*.wav'): if fn in self.trained_fns: print('Skipping ' + fn + '...') conti...
python
def run(self): """ Begin reading through audio files, saving false activations and retraining when necessary """ for fn in glob_all(self.args.random_data_folder, '*.wav'): if fn in self.trained_fns: print('Skipping ' + fn + '...') conti...
[ "def", "run", "(", "self", ")", ":", "for", "fn", "in", "glob_all", "(", "self", ".", "args", ".", "random_data_folder", ",", "'*.wav'", ")", ":", "if", "fn", "in", "self", ".", "trained_fns", ":", "print", "(", "'Skipping '", "+", "fn", "+", "'...'"...
Begin reading through audio files, saving false activations and retraining when necessary
[ "Begin", "reading", "through", "audio", "files", "saving", "false", "activations", "and", "retraining", "when", "necessary" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/scripts/train_incremental.py#L138-L153
220,760
MycroftAI/mycroft-precise
precise/network_runner.py
TensorFlowRunner.predict
def predict(self, inputs: np.ndarray) -> np.ndarray: """Run on multiple inputs""" return self.sess.run(self.out_var, {self.inp_var: inputs})
python
def predict(self, inputs: np.ndarray) -> np.ndarray: """Run on multiple inputs""" return self.sess.run(self.out_var, {self.inp_var: inputs})
[ "def", "predict", "(", "self", ",", "inputs", ":", "np", ".", "ndarray", ")", "->", "np", ".", "ndarray", ":", "return", "self", ".", "sess", ".", "run", "(", "self", ".", "out_var", ",", "{", "self", ".", "inp_var", ":", "inputs", "}", ")" ]
Run on multiple inputs
[ "Run", "on", "multiple", "inputs" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/network_runner.py#L61-L63
220,761
ofek/bit
bit/network/rates.py
satoshi_to_currency
def satoshi_to_currency(num, currency): """Converts a given number of satoshi to another currency as a formatted string rounded down to the proper number of decimal places. :param num: The number of satoshi. :type num: ``int`` :param currency: One of the :ref:`supported currencies`. :type curre...
python
def satoshi_to_currency(num, currency): """Converts a given number of satoshi to another currency as a formatted string rounded down to the proper number of decimal places. :param num: The number of satoshi. :type num: ``int`` :param currency: One of the :ref:`supported currencies`. :type curre...
[ "def", "satoshi_to_currency", "(", "num", ",", "currency", ")", ":", "return", "'{:f}'", ".", "format", "(", "Decimal", "(", "num", "/", "Decimal", "(", "EXCHANGE_RATES", "[", "currency", "]", "(", ")", ")", ")", ".", "quantize", "(", "Decimal", "(", "...
Converts a given number of satoshi to another currency as a formatted string rounded down to the proper number of decimal places. :param num: The number of satoshi. :type num: ``int`` :param currency: One of the :ref:`supported currencies`. :type currency: ``str`` :rtype: ``str``
[ "Converts", "a", "given", "number", "of", "satoshi", "to", "another", "currency", "as", "a", "formatted", "string", "rounded", "down", "to", "the", "proper", "number", "of", "decimal", "places", "." ]
20fc0e7047946c1f28f868008d99d659905c1af6
https://github.com/ofek/bit/blob/20fc0e7047946c1f28f868008d99d659905c1af6/bit/network/rates.py#L645-L662
220,762
ofek/bit
bit/network/services.py
NetworkAPI.get_balance
def get_balance(cls, address): """Gets the balance of an address in satoshi. :param address: The address in question. :type address: ``str`` :raises ConnectionError: If all API services fail. :rtype: ``int`` """ for api_call in cls.GET_BALANCE_MAIN: ...
python
def get_balance(cls, address): """Gets the balance of an address in satoshi. :param address: The address in question. :type address: ``str`` :raises ConnectionError: If all API services fail. :rtype: ``int`` """ for api_call in cls.GET_BALANCE_MAIN: ...
[ "def", "get_balance", "(", "cls", ",", "address", ")", ":", "for", "api_call", "in", "cls", ".", "GET_BALANCE_MAIN", ":", "try", ":", "return", "api_call", "(", "address", ")", "except", "cls", ".", "IGNORED_ERRORS", ":", "pass", "raise", "ConnectionError", ...
Gets the balance of an address in satoshi. :param address: The address in question. :type address: ``str`` :raises ConnectionError: If all API services fail. :rtype: ``int``
[ "Gets", "the", "balance", "of", "an", "address", "in", "satoshi", "." ]
20fc0e7047946c1f28f868008d99d659905c1af6
https://github.com/ofek/bit/blob/20fc0e7047946c1f28f868008d99d659905c1af6/bit/network/services.py#L343-L358
220,763
ofek/bit
bit/network/services.py
NetworkAPI.get_transactions
def get_transactions(cls, address): """Gets the ID of all transactions related to an address. :param address: The address in question. :type address: ``str`` :raises ConnectionError: If all API services fail. :rtype: ``list`` of ``str`` """ for api_call in cls.G...
python
def get_transactions(cls, address): """Gets the ID of all transactions related to an address. :param address: The address in question. :type address: ``str`` :raises ConnectionError: If all API services fail. :rtype: ``list`` of ``str`` """ for api_call in cls.G...
[ "def", "get_transactions", "(", "cls", ",", "address", ")", ":", "for", "api_call", "in", "cls", ".", "GET_TRANSACTIONS_MAIN", ":", "try", ":", "return", "api_call", "(", "address", ")", "except", "cls", ".", "IGNORED_ERRORS", ":", "pass", "raise", "Connecti...
Gets the ID of all transactions related to an address. :param address: The address in question. :type address: ``str`` :raises ConnectionError: If all API services fail. :rtype: ``list`` of ``str``
[ "Gets", "the", "ID", "of", "all", "transactions", "related", "to", "an", "address", "." ]
20fc0e7047946c1f28f868008d99d659905c1af6
https://github.com/ofek/bit/blob/20fc0e7047946c1f28f868008d99d659905c1af6/bit/network/services.py#L379-L394
220,764
ofek/bit
bit/network/services.py
NetworkAPI.get_unspent
def get_unspent(cls, address): """Gets all unspent transaction outputs belonging to an address. :param address: The address in question. :type address: ``str`` :raises ConnectionError: If all API services fail. :rtype: ``list`` of :class:`~bit.network.meta.Unspent` """ ...
python
def get_unspent(cls, address): """Gets all unspent transaction outputs belonging to an address. :param address: The address in question. :type address: ``str`` :raises ConnectionError: If all API services fail. :rtype: ``list`` of :class:`~bit.network.meta.Unspent` """ ...
[ "def", "get_unspent", "(", "cls", ",", "address", ")", ":", "for", "api_call", "in", "cls", ".", "GET_UNSPENT_MAIN", ":", "try", ":", "return", "api_call", "(", "address", ")", "except", "cls", ".", "IGNORED_ERRORS", ":", "pass", "raise", "ConnectionError", ...
Gets all unspent transaction outputs belonging to an address. :param address: The address in question. :type address: ``str`` :raises ConnectionError: If all API services fail. :rtype: ``list`` of :class:`~bit.network.meta.Unspent`
[ "Gets", "all", "unspent", "transaction", "outputs", "belonging", "to", "an", "address", "." ]
20fc0e7047946c1f28f868008d99d659905c1af6
https://github.com/ofek/bit/blob/20fc0e7047946c1f28f868008d99d659905c1af6/bit/network/services.py#L452-L467
220,765
ofek/bit
bit/network/services.py
NetworkAPI.broadcast_tx
def broadcast_tx(cls, tx_hex): # pragma: no cover """Broadcasts a transaction to the blockchain. :param tx_hex: A signed transaction in hex form. :type tx_hex: ``str`` :raises ConnectionError: If all API services fail. """ success = None for api_call in cls.BRO...
python
def broadcast_tx(cls, tx_hex): # pragma: no cover """Broadcasts a transaction to the blockchain. :param tx_hex: A signed transaction in hex form. :type tx_hex: ``str`` :raises ConnectionError: If all API services fail. """ success = None for api_call in cls.BRO...
[ "def", "broadcast_tx", "(", "cls", ",", "tx_hex", ")", ":", "# pragma: no cover", "success", "=", "None", "for", "api_call", "in", "cls", ".", "BROADCAST_TX_MAIN", ":", "try", ":", "success", "=", "api_call", "(", "tx_hex", ")", "if", "not", "success", ":"...
Broadcasts a transaction to the blockchain. :param tx_hex: A signed transaction in hex form. :type tx_hex: ``str`` :raises ConnectionError: If all API services fail.
[ "Broadcasts", "a", "transaction", "to", "the", "blockchain", "." ]
20fc0e7047946c1f28f868008d99d659905c1af6
https://github.com/ofek/bit/blob/20fc0e7047946c1f28f868008d99d659905c1af6/bit/network/services.py#L489-L511
220,766
ofek/bit
bit/transaction.py
calculate_preimages
def calculate_preimages(tx_obj, inputs_parameters): """Calculates preimages for provided transaction structure and input values. :param tx_obj: The transaction object used to calculate preimage from using a transaction digest algorithm, such as BIP-143 for Segwit input...
python
def calculate_preimages(tx_obj, inputs_parameters): """Calculates preimages for provided transaction structure and input values. :param tx_obj: The transaction object used to calculate preimage from using a transaction digest algorithm, such as BIP-143 for Segwit input...
[ "def", "calculate_preimages", "(", "tx_obj", ",", "inputs_parameters", ")", ":", "# Tx object data:", "input_count", "=", "int_to_varint", "(", "len", "(", "tx_obj", ".", "TxIn", ")", ")", "output_count", "=", "int_to_varint", "(", "len", "(", "tx_obj", ".", "...
Calculates preimages for provided transaction structure and input values. :param tx_obj: The transaction object used to calculate preimage from using a transaction digest algorithm, such as BIP-143 for Segwit inputs. This transaction object must hence have scriptCodes ...
[ "Calculates", "preimages", "for", "provided", "transaction", "structure", "and", "input", "values", "." ]
20fc0e7047946c1f28f868008d99d659905c1af6
https://github.com/ofek/bit/blob/20fc0e7047946c1f28f868008d99d659905c1af6/bit/transaction.py#L517-L582
220,767
ofek/bit
bit/wallet.py
BaseKey.verify
def verify(self, signature, data): """Verifies some data was signed by this private key. :param signature: The signature to verify. :type signature: ``bytes`` :param data: The data that was supposedly signed. :type data: ``bytes`` :rtype: ``bool`` """ ret...
python
def verify(self, signature, data): """Verifies some data was signed by this private key. :param signature: The signature to verify. :type signature: ``bytes`` :param data: The data that was supposedly signed. :type data: ``bytes`` :rtype: ``bool`` """ ret...
[ "def", "verify", "(", "self", ",", "signature", ",", "data", ")", ":", "return", "self", ".", "_pk", ".", "public_key", ".", "verify", "(", "signature", ",", "data", ")" ]
Verifies some data was signed by this private key. :param signature: The signature to verify. :type signature: ``bytes`` :param data: The data that was supposedly signed. :type data: ``bytes`` :rtype: ``bool``
[ "Verifies", "some", "data", "was", "signed", "by", "this", "private", "key", "." ]
20fc0e7047946c1f28f868008d99d659905c1af6
https://github.com/ofek/bit/blob/20fc0e7047946c1f28f868008d99d659905c1af6/bit/wallet.py#L89-L98
220,768
ofek/bit
bit/wallet.py
PrivateKey.get_transactions
def get_transactions(self): """Fetches transaction history. :rtype: ``list`` of ``str`` transaction IDs """ self.transactions[:] = NetworkAPI.get_transactions(self.address) if self.segwit_address: self.transactions += NetworkAPI.get_transactions(self.segwit_address) ...
python
def get_transactions(self): """Fetches transaction history. :rtype: ``list`` of ``str`` transaction IDs """ self.transactions[:] = NetworkAPI.get_transactions(self.address) if self.segwit_address: self.transactions += NetworkAPI.get_transactions(self.segwit_address) ...
[ "def", "get_transactions", "(", "self", ")", ":", "self", ".", "transactions", "[", ":", "]", "=", "NetworkAPI", ".", "get_transactions", "(", "self", ".", "address", ")", "if", "self", ".", "segwit_address", ":", "self", ".", "transactions", "+=", "Networ...
Fetches transaction history. :rtype: ``list`` of ``str`` transaction IDs
[ "Fetches", "transaction", "history", "." ]
20fc0e7047946c1f28f868008d99d659905c1af6
https://github.com/ofek/bit/blob/20fc0e7047946c1f28f868008d99d659905c1af6/bit/wallet.py#L246-L254
220,769
ofek/bit
bit/wallet.py
MultiSig.address
def address(self): """The public address you share with others to receive funds.""" if self._address is None: self._address = multisig_to_address(self.public_keys, self.m, version=self.version) return self._address
python
def address(self): """The public address you share with others to receive funds.""" if self._address is None: self._address = multisig_to_address(self.public_keys, self.m, version=self.version) return self._address
[ "def", "address", "(", "self", ")", ":", "if", "self", ".", "_address", "is", "None", ":", "self", ".", "_address", "=", "multisig_to_address", "(", "self", ".", "public_keys", ",", "self", ".", "m", ",", "version", "=", "self", ".", "version", ")", ...
The public address you share with others to receive funds.
[ "The", "public", "address", "you", "share", "with", "others", "to", "receive", "funds", "." ]
20fc0e7047946c1f28f868008d99d659905c1af6
https://github.com/ofek/bit/blob/20fc0e7047946c1f28f868008d99d659905c1af6/bit/wallet.py#L925-L930
220,770
ofek/bit
bit/base32.py
bech32_polymod
def bech32_polymod(values): """Internal function that computes the Bech32 checksum.""" generator = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3] chk = 1 for value in values: top = chk >> 25 chk = (chk & 0x1ffffff) << 5 ^ value for i in range(5): chk ^= ...
python
def bech32_polymod(values): """Internal function that computes the Bech32 checksum.""" generator = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3] chk = 1 for value in values: top = chk >> 25 chk = (chk & 0x1ffffff) << 5 ^ value for i in range(5): chk ^= ...
[ "def", "bech32_polymod", "(", "values", ")", ":", "generator", "=", "[", "0x3b6a57b2", ",", "0x26508e6d", ",", "0x1ea119fa", ",", "0x3d4233dd", ",", "0x2a1462b3", "]", "chk", "=", "1", "for", "value", "in", "values", ":", "top", "=", "chk", ">>", "25", ...
Internal function that computes the Bech32 checksum.
[ "Internal", "function", "that", "computes", "the", "Bech32", "checksum", "." ]
20fc0e7047946c1f28f868008d99d659905c1af6
https://github.com/ofek/bit/blob/20fc0e7047946c1f28f868008d99d659905c1af6/bit/base32.py#L26-L35
220,771
ofek/bit
bit/base32.py
bech32_hrp_expand
def bech32_hrp_expand(hrp): """Expand the HRP into values for checksum computation.""" return [ord(x) >> 5 for x in hrp] + [0] + [ord(x) & 31 for x in hrp]
python
def bech32_hrp_expand(hrp): """Expand the HRP into values for checksum computation.""" return [ord(x) >> 5 for x in hrp] + [0] + [ord(x) & 31 for x in hrp]
[ "def", "bech32_hrp_expand", "(", "hrp", ")", ":", "return", "[", "ord", "(", "x", ")", ">>", "5", "for", "x", "in", "hrp", "]", "+", "[", "0", "]", "+", "[", "ord", "(", "x", ")", "&", "31", "for", "x", "in", "hrp", "]" ]
Expand the HRP into values for checksum computation.
[ "Expand", "the", "HRP", "into", "values", "for", "checksum", "computation", "." ]
20fc0e7047946c1f28f868008d99d659905c1af6
https://github.com/ofek/bit/blob/20fc0e7047946c1f28f868008d99d659905c1af6/bit/base32.py#L38-L40
220,772
ofek/bit
bit/base32.py
bech32_create_checksum
def bech32_create_checksum(hrp, data): """Compute the checksum values given HRP and data.""" values = bech32_hrp_expand(hrp) + data polymod = bech32_polymod(values + [0, 0, 0, 0, 0, 0]) ^ 1 return [(polymod >> 5 * (5 - i)) & 31 for i in range(6)]
python
def bech32_create_checksum(hrp, data): """Compute the checksum values given HRP and data.""" values = bech32_hrp_expand(hrp) + data polymod = bech32_polymod(values + [0, 0, 0, 0, 0, 0]) ^ 1 return [(polymod >> 5 * (5 - i)) & 31 for i in range(6)]
[ "def", "bech32_create_checksum", "(", "hrp", ",", "data", ")", ":", "values", "=", "bech32_hrp_expand", "(", "hrp", ")", "+", "data", "polymod", "=", "bech32_polymod", "(", "values", "+", "[", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ...
Compute the checksum values given HRP and data.
[ "Compute", "the", "checksum", "values", "given", "HRP", "and", "data", "." ]
20fc0e7047946c1f28f868008d99d659905c1af6
https://github.com/ofek/bit/blob/20fc0e7047946c1f28f868008d99d659905c1af6/bit/base32.py#L48-L52
220,773
ofek/bit
bit/base32.py
bech32_encode
def bech32_encode(hrp, data): """Compute a Bech32 string given HRP and data values.""" combined = data + bech32_create_checksum(hrp, data) return hrp + '1' + ''.join([CHARSET[d] for d in combined])
python
def bech32_encode(hrp, data): """Compute a Bech32 string given HRP and data values.""" combined = data + bech32_create_checksum(hrp, data) return hrp + '1' + ''.join([CHARSET[d] for d in combined])
[ "def", "bech32_encode", "(", "hrp", ",", "data", ")", ":", "combined", "=", "data", "+", "bech32_create_checksum", "(", "hrp", ",", "data", ")", "return", "hrp", "+", "'1'", "+", "''", ".", "join", "(", "[", "CHARSET", "[", "d", "]", "for", "d", "i...
Compute a Bech32 string given HRP and data values.
[ "Compute", "a", "Bech32", "string", "given", "HRP", "and", "data", "values", "." ]
20fc0e7047946c1f28f868008d99d659905c1af6
https://github.com/ofek/bit/blob/20fc0e7047946c1f28f868008d99d659905c1af6/bit/base32.py#L55-L58
220,774
ofek/bit
bit/base32.py
convertbits
def convertbits(data, frombits, tobits, pad=True): """General power-of-2 base conversion.""" acc = 0 bits = 0 ret = [] maxv = (1 << tobits) - 1 max_acc = (1 << (frombits + tobits - 1)) - 1 for value in data: if value < 0 or (value >> frombits): return None acc = (...
python
def convertbits(data, frombits, tobits, pad=True): """General power-of-2 base conversion.""" acc = 0 bits = 0 ret = [] maxv = (1 << tobits) - 1 max_acc = (1 << (frombits + tobits - 1)) - 1 for value in data: if value < 0 or (value >> frombits): return None acc = (...
[ "def", "convertbits", "(", "data", ",", "frombits", ",", "tobits", ",", "pad", "=", "True", ")", ":", "acc", "=", "0", "bits", "=", "0", "ret", "=", "[", "]", "maxv", "=", "(", "1", "<<", "tobits", ")", "-", "1", "max_acc", "=", "(", "1", "<<...
General power-of-2 base conversion.
[ "General", "power", "-", "of", "-", "2", "base", "conversion", "." ]
20fc0e7047946c1f28f868008d99d659905c1af6
https://github.com/ofek/bit/blob/20fc0e7047946c1f28f868008d99d659905c1af6/bit/base32.py#L79-L99
220,775
ofek/bit
bit/base32.py
decode
def decode(addr): """Decode a segwit address.""" hrpgot, data = bech32_decode(addr) # if hrpgot != hrp: if hrpgot not in BECH32_VERSION_SET: return (None, None) decoded = convertbits(data[1:], 5, 8, False) if decoded is None or len(decoded) < 2 or len(decoded) > 40: return (None,...
python
def decode(addr): """Decode a segwit address.""" hrpgot, data = bech32_decode(addr) # if hrpgot != hrp: if hrpgot not in BECH32_VERSION_SET: return (None, None) decoded = convertbits(data[1:], 5, 8, False) if decoded is None or len(decoded) < 2 or len(decoded) > 40: return (None,...
[ "def", "decode", "(", "addr", ")", ":", "hrpgot", ",", "data", "=", "bech32_decode", "(", "addr", ")", "# if hrpgot != hrp:", "if", "hrpgot", "not", "in", "BECH32_VERSION_SET", ":", "return", "(", "None", ",", "None", ")", "decoded", "=", "convertbits", "(...
Decode a segwit address.
[ "Decode", "a", "segwit", "address", "." ]
20fc0e7047946c1f28f868008d99d659905c1af6
https://github.com/ofek/bit/blob/20fc0e7047946c1f28f868008d99d659905c1af6/bit/base32.py#L103-L116
220,776
nok/sklearn-porter
sklearn_porter/utils/Shell.py
Shell._run
def _run(method, cmd, cwd=None, shell=True, universal_newlines=True, stderr=STDOUT): """Internal wrapper for `call` amd `check_output`""" if not cmd: error_msg = 'Passed empty text or list' raise AttributeError(error_msg) if isinstance(cmd, six.string_types):...
python
def _run(method, cmd, cwd=None, shell=True, universal_newlines=True, stderr=STDOUT): """Internal wrapper for `call` amd `check_output`""" if not cmd: error_msg = 'Passed empty text or list' raise AttributeError(error_msg) if isinstance(cmd, six.string_types):...
[ "def", "_run", "(", "method", ",", "cmd", ",", "cwd", "=", "None", ",", "shell", "=", "True", ",", "universal_newlines", "=", "True", ",", "stderr", "=", "STDOUT", ")", ":", "if", "not", "cmd", ":", "error_msg", "=", "'Passed empty text or list'", "raise...
Internal wrapper for `call` amd `check_output`
[ "Internal", "wrapper", "for", "call", "amd", "check_output" ]
04673f768310bde31f9747a68a5e070592441ef2
https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/utils/Shell.py#L13-L31
220,777
nok/sklearn-porter
sklearn_porter/utils/Shell.py
Shell.call
def call(cmd, shell=True, cwd=None, universal_newlines=True, stderr=STDOUT): """Just execute a specific command.""" return Shell._run(call, cmd, shell=shell, cwd=cwd, stderr=stderr, universal_newlines=universal_newlines)
python
def call(cmd, shell=True, cwd=None, universal_newlines=True, stderr=STDOUT): """Just execute a specific command.""" return Shell._run(call, cmd, shell=shell, cwd=cwd, stderr=stderr, universal_newlines=universal_newlines)
[ "def", "call", "(", "cmd", ",", "shell", "=", "True", ",", "cwd", "=", "None", ",", "universal_newlines", "=", "True", ",", "stderr", "=", "STDOUT", ")", ":", "return", "Shell", ".", "_run", "(", "call", ",", "cmd", ",", "shell", "=", "shell", ",",...
Just execute a specific command.
[ "Just", "execute", "a", "specific", "command", "." ]
04673f768310bde31f9747a68a5e070592441ef2
https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/utils/Shell.py#L34-L37
220,778
nok/sklearn-porter
sklearn_porter/utils/Logging.py
Logging.get_logger
def get_logger(name, level=0): """Setup a logging instance""" level = 0 if not isinstance(level, int) else level level = 0 if level < 0 else level level = 4 if level > 4 else level console = logging.StreamHandler() level = [logging.NOTSET, logging.ERROR, logging.WARN, log...
python
def get_logger(name, level=0): """Setup a logging instance""" level = 0 if not isinstance(level, int) else level level = 0 if level < 0 else level level = 4 if level > 4 else level console = logging.StreamHandler() level = [logging.NOTSET, logging.ERROR, logging.WARN, log...
[ "def", "get_logger", "(", "name", ",", "level", "=", "0", ")", ":", "level", "=", "0", "if", "not", "isinstance", "(", "level", ",", "int", ")", "else", "level", "level", "=", "0", "if", "level", "<", "0", "else", "level", "level", "=", "4", "if"...
Setup a logging instance
[ "Setup", "a", "logging", "instance" ]
04673f768310bde31f9747a68a5e070592441ef2
https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/utils/Logging.py#L12-L24
220,779
nok/sklearn-porter
sklearn_porter/Template.py
Template.indent
def indent(self, text, n_indents=1, skipping=False): """ Indent text with single spaces. Parameters ---------- :param text : string The text which get a specific indentation. :param n_indents : int, default: 1 The number of indentations. :...
python
def indent(self, text, n_indents=1, skipping=False): """ Indent text with single spaces. Parameters ---------- :param text : string The text which get a specific indentation. :param n_indents : int, default: 1 The number of indentations. :...
[ "def", "indent", "(", "self", ",", "text", ",", "n_indents", "=", "1", ",", "skipping", "=", "False", ")", ":", "lines", "=", "text", ".", "splitlines", "(", ")", "space", "=", "self", ".", "TEMPLATES", ".", "get", "(", "self", ".", "target_language"...
Indent text with single spaces. Parameters ---------- :param text : string The text which get a specific indentation. :param n_indents : int, default: 1 The number of indentations. :param skipping : boolean, default: False Whether to skip the ...
[ "Indent", "text", "with", "single", "spaces", "." ]
04673f768310bde31f9747a68a5e070592441ef2
https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/Template.py#L25-L61
220,780
nok/sklearn-porter
sklearn_porter/Template.py
Template.temp
def temp(self, name, templates=None, n_indents=None, skipping=False): """ Get specific template of chosen programming language. Parameters ---------- :param param name : string The key name of the template. :param param templates : string, default: No...
python
def temp(self, name, templates=None, n_indents=None, skipping=False): """ Get specific template of chosen programming language. Parameters ---------- :param param name : string The key name of the template. :param param templates : string, default: No...
[ "def", "temp", "(", "self", ",", "name", ",", "templates", "=", "None", ",", "n_indents", "=", "None", ",", "skipping", "=", "False", ")", ":", "if", "templates", "is", "None", ":", "templates", "=", "self", ".", "TEMPLATES", ".", "get", "(", "self",...
Get specific template of chosen programming language. Parameters ---------- :param param name : string The key name of the template. :param param templates : string, default: None The template with placeholders. :param param n_indents : int, defau...
[ "Get", "specific", "template", "of", "chosen", "programming", "language", "." ]
04673f768310bde31f9747a68a5e070592441ef2
https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/Template.py#L63-L112
220,781
nok/sklearn-porter
sklearn_porter/utils/Environment.py
Environment.read_sklearn_version
def read_sklearn_version(): """Determine the installed version of sklearn""" from sklearn import __version__ as sklearn_ver sklearn_ver = str(sklearn_ver).split('.') sklearn_ver = [int(v) for v in sklearn_ver] major, minor = sklearn_ver[0], sklearn_ver[1] patch = sklearn_...
python
def read_sklearn_version(): """Determine the installed version of sklearn""" from sklearn import __version__ as sklearn_ver sklearn_ver = str(sklearn_ver).split('.') sklearn_ver = [int(v) for v in sklearn_ver] major, minor = sklearn_ver[0], sklearn_ver[1] patch = sklearn_...
[ "def", "read_sklearn_version", "(", ")", ":", "from", "sklearn", "import", "__version__", "as", "sklearn_ver", "sklearn_ver", "=", "str", "(", "sklearn_ver", ")", ".", "split", "(", "'.'", ")", "sklearn_ver", "=", "[", "int", "(", "v", ")", "for", "v", "...
Determine the installed version of sklearn
[ "Determine", "the", "installed", "version", "of", "sklearn" ]
04673f768310bde31f9747a68a5e070592441ef2
https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/utils/Environment.py#L60-L67
220,782
nok/sklearn-porter
sklearn_porter/utils/Environment.py
Environment._platform_is_windows
def _platform_is_windows(platform=sys.platform): """Is the current OS a Windows?""" matched = platform in ('cygwin', 'win32', 'win64') if matched: error_msg = "Windows isn't supported yet" raise OSError(error_msg) return matched
python
def _platform_is_windows(platform=sys.platform): """Is the current OS a Windows?""" matched = platform in ('cygwin', 'win32', 'win64') if matched: error_msg = "Windows isn't supported yet" raise OSError(error_msg) return matched
[ "def", "_platform_is_windows", "(", "platform", "=", "sys", ".", "platform", ")", ":", "matched", "=", "platform", "in", "(", "'cygwin'", ",", "'win32'", ",", "'win64'", ")", "if", "matched", ":", "error_msg", "=", "\"Windows isn't supported yet\"", "raise", "...
Is the current OS a Windows?
[ "Is", "the", "current", "OS", "a", "Windows?" ]
04673f768310bde31f9747a68a5e070592441ef2
https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/utils/Environment.py#L70-L76
220,783
nok/sklearn-porter
sklearn_porter/utils/Environment.py
Environment.check_deps
def check_deps(deps): """check whether specific requirements are available.""" if not isinstance(deps, list): deps = [deps] checks = list(Environment.has_apps(deps)) if not all(checks): for name, available in list(dict(zip(deps, checks)).items()): ...
python
def check_deps(deps): """check whether specific requirements are available.""" if not isinstance(deps, list): deps = [deps] checks = list(Environment.has_apps(deps)) if not all(checks): for name, available in list(dict(zip(deps, checks)).items()): ...
[ "def", "check_deps", "(", "deps", ")", ":", "if", "not", "isinstance", "(", "deps", ",", "list", ")", ":", "deps", "=", "[", "deps", "]", "checks", "=", "list", "(", "Environment", ".", "has_apps", "(", "deps", ")", ")", "if", "not", "all", "(", ...
check whether specific requirements are available.
[ "check", "whether", "specific", "requirements", "are", "available", "." ]
04673f768310bde31f9747a68a5e070592441ef2
https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/utils/Environment.py#L94-L104
220,784
nok/sklearn-porter
sklearn_porter/estimator/classifier/DecisionTreeClassifier/__init__.py
DecisionTreeClassifier.create_tree
def create_tree(self): """ Parse and build the tree branches. Returns ------- :return : string The tree branches as string. """ feature_indices = [] for i in self.estimator.tree_.feature: n_features = self.n_features if...
python
def create_tree(self): """ Parse and build the tree branches. Returns ------- :return : string The tree branches as string. """ feature_indices = [] for i in self.estimator.tree_.feature: n_features = self.n_features if...
[ "def", "create_tree", "(", "self", ")", ":", "feature_indices", "=", "[", "]", "for", "i", "in", "self", ".", "estimator", ".", "tree_", ".", "feature", ":", "n_features", "=", "self", ".", "n_features", "if", "self", ".", "n_features", ">", "1", "or",...
Parse and build the tree branches. Returns ------- :return : string The tree branches as string.
[ "Parse", "and", "build", "the", "tree", "branches", "." ]
04673f768310bde31f9747a68a5e070592441ef2
https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/estimator/classifier/DecisionTreeClassifier/__init__.py#L331-L352
220,785
nok/sklearn-porter
sklearn_porter/estimator/classifier/MLPClassifier/__init__.py
MLPClassifier._get_intercepts
def _get_intercepts(self): """ Concatenate all intercepts of the classifier. """ temp_arr = self.temp('arr') for layer in self.intercepts: inter = ', '.join([self.repr(b) for b in layer]) yield temp_arr.format(inter)
python
def _get_intercepts(self): """ Concatenate all intercepts of the classifier. """ temp_arr = self.temp('arr') for layer in self.intercepts: inter = ', '.join([self.repr(b) for b in layer]) yield temp_arr.format(inter)
[ "def", "_get_intercepts", "(", "self", ")", ":", "temp_arr", "=", "self", ".", "temp", "(", "'arr'", ")", "for", "layer", "in", "self", ".", "intercepts", ":", "inter", "=", "', '", ".", "join", "(", "[", "self", ".", "repr", "(", "b", ")", "for", ...
Concatenate all intercepts of the classifier.
[ "Concatenate", "all", "intercepts", "of", "the", "classifier", "." ]
04673f768310bde31f9747a68a5e070592441ef2
https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/estimator/classifier/MLPClassifier/__init__.py#L251-L258
220,786
nok/sklearn-porter
sklearn_porter/estimator/classifier/AdaBoostClassifier/__init__.py
AdaBoostClassifier.create_embedded_meth
def create_embedded_meth(self): """ Build the estimator methods or functions. Returns ------- :return : string The built methods as merged string. """ # Generate related trees: fns = [] for idx, estimator in enumerate(self.estimators):...
python
def create_embedded_meth(self): """ Build the estimator methods or functions. Returns ------- :return : string The built methods as merged string. """ # Generate related trees: fns = [] for idx, estimator in enumerate(self.estimators):...
[ "def", "create_embedded_meth", "(", "self", ")", ":", "# Generate related trees:", "fns", "=", "[", "]", "for", "idx", ",", "estimator", "in", "enumerate", "(", "self", ".", "estimators", ")", ":", "tree", "=", "self", ".", "create_single_method", "(", "idx"...
Build the estimator methods or functions. Returns ------- :return : string The built methods as merged string.
[ "Build", "the", "estimator", "methods", "or", "functions", "." ]
04673f768310bde31f9747a68a5e070592441ef2
https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/estimator/classifier/AdaBoostClassifier/__init__.py#L289-L329
220,787
nok/sklearn-porter
sklearn_porter/Porter.py
Porter._classifiers
def _classifiers(self): """ Get a set of supported classifiers. Returns ------- classifiers : {set} The set of supported classifiers. """ # sklearn version < 0.18.0 classifiers = ( AdaBoostClassifier, BernoulliNB, ...
python
def _classifiers(self): """ Get a set of supported classifiers. Returns ------- classifiers : {set} The set of supported classifiers. """ # sklearn version < 0.18.0 classifiers = ( AdaBoostClassifier, BernoulliNB, ...
[ "def", "_classifiers", "(", "self", ")", ":", "# sklearn version < 0.18.0", "classifiers", "=", "(", "AdaBoostClassifier", ",", "BernoulliNB", ",", "DecisionTreeClassifier", ",", "ExtraTreesClassifier", ",", "GaussianNB", ",", "KNeighborsClassifier", ",", "LinearSVC", "...
Get a set of supported classifiers. Returns ------- classifiers : {set} The set of supported classifiers.
[ "Get", "a", "set", "of", "supported", "classifiers", "." ]
04673f768310bde31f9747a68a5e070592441ef2
https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/Porter.py#L241-L271
220,788
nok/sklearn-porter
sklearn_porter/Porter.py
Porter._regressors
def _regressors(self): """ Get a set of supported regressors. Returns ------- regressors : {set} The set of supported regressors. """ # sklearn version < 0.18.0 regressors = () # sklearn version >= 0.18.0 if self.sklearn_ver[...
python
def _regressors(self): """ Get a set of supported regressors. Returns ------- regressors : {set} The set of supported regressors. """ # sklearn version < 0.18.0 regressors = () # sklearn version >= 0.18.0 if self.sklearn_ver[...
[ "def", "_regressors", "(", "self", ")", ":", "# sklearn version < 0.18.0", "regressors", "=", "(", ")", "# sklearn version >= 0.18.0", "if", "self", ".", "sklearn_ver", "[", ":", "2", "]", ">=", "(", "0", ",", "18", ")", ":", "from", "sklearn", ".", "neura...
Get a set of supported regressors. Returns ------- regressors : {set} The set of supported regressors.
[ "Get", "a", "set", "of", "supported", "regressors", "." ]
04673f768310bde31f9747a68a5e070592441ef2
https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/Porter.py#L274-L293
220,789
nok/sklearn-porter
sklearn_porter/Porter.py
Porter.predict
def predict(self, X, class_name=None, method_name=None, tnp_dir='tmp', keep_tmp_dir=False, num_format=lambda x: str(x)): """ Predict using the transpiled model. Parameters ---------- :param X : {array-like}, shape (n_features) or (n_samples, n_features) ...
python
def predict(self, X, class_name=None, method_name=None, tnp_dir='tmp', keep_tmp_dir=False, num_format=lambda x: str(x)): """ Predict using the transpiled model. Parameters ---------- :param X : {array-like}, shape (n_features) or (n_samples, n_features) ...
[ "def", "predict", "(", "self", ",", "X", ",", "class_name", "=", "None", ",", "method_name", "=", "None", ",", "tnp_dir", "=", "'tmp'", ",", "keep_tmp_dir", "=", "False", ",", "num_format", "=", "lambda", "x", ":", "str", "(", "x", ")", ")", ":", "...
Predict using the transpiled model. Parameters ---------- :param X : {array-like}, shape (n_features) or (n_samples, n_features) The input data. :param class_name : string, default: None The name for the ported class. :param method_name : string, defaul...
[ "Predict", "using", "the", "transpiled", "model", "." ]
04673f768310bde31f9747a68a5e070592441ef2
https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/Porter.py#L295-L388
220,790
nok/sklearn-porter
sklearn_porter/Porter.py
Porter.integrity_score
def integrity_score(self, X, method='predict', normalize=True, num_format=lambda x: str(x)): """ Compute the accuracy of the ported classifier. Parameters ---------- :param X : ndarray, shape (n_samples, n_features) Input data. :param...
python
def integrity_score(self, X, method='predict', normalize=True, num_format=lambda x: str(x)): """ Compute the accuracy of the ported classifier. Parameters ---------- :param X : ndarray, shape (n_samples, n_features) Input data. :param...
[ "def", "integrity_score", "(", "self", ",", "X", ",", "method", "=", "'predict'", ",", "normalize", "=", "True", ",", "num_format", "=", "lambda", "x", ":", "str", "(", "x", ")", ")", ":", "X", "=", "np", ".", "array", "(", "X", ")", "if", "not",...
Compute the accuracy of the ported classifier. Parameters ---------- :param X : ndarray, shape (n_samples, n_features) Input data. :param method : string, default: 'predict' The method which should be tested. :param normalize : bool, default: True ...
[ "Compute", "the", "accuracy", "of", "the", "ported", "classifier", "." ]
04673f768310bde31f9747a68a5e070592441ef2
https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/Porter.py#L390-L434
220,791
nok/sklearn-porter
sklearn_porter/Porter.py
Porter._get_filename
def _get_filename(class_name, language): """ Generate the specific filename. Parameters ---------- :param class_name : str The used class name. :param language : {'c', 'go', 'java', 'js', 'php', 'ruby'} The target programming language. R...
python
def _get_filename(class_name, language): """ Generate the specific filename. Parameters ---------- :param class_name : str The used class name. :param language : {'c', 'go', 'java', 'js', 'php', 'ruby'} The target programming language. R...
[ "def", "_get_filename", "(", "class_name", ",", "language", ")", ":", "name", "=", "str", "(", "class_name", ")", ".", "strip", "(", ")", "lang", "=", "str", "(", "language", ")", "# Name:", "if", "language", "in", "[", "'java'", ",", "'php'", "]", "...
Generate the specific filename. Parameters ---------- :param class_name : str The used class name. :param language : {'c', 'go', 'java', 'js', 'php', 'ruby'} The target programming language. Returns ------- filename : str ...
[ "Generate", "the", "specific", "filename", "." ]
04673f768310bde31f9747a68a5e070592441ef2
https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/Porter.py#L456-L488
220,792
nok/sklearn-porter
sklearn_porter/Porter.py
Porter._get_commands
def _get_commands(filename, class_name, language): """ Generate the related compilation and execution commands. Parameters ---------- :param filename : str The used filename. :param class_name : str The used class name. :param la...
python
def _get_commands(filename, class_name, language): """ Generate the related compilation and execution commands. Parameters ---------- :param filename : str The used filename. :param class_name : str The used class name. :param la...
[ "def", "_get_commands", "(", "filename", ",", "class_name", ",", "language", ")", ":", "cname", "=", "str", "(", "class_name", ")", "fname", "=", "str", "(", "filename", ")", "lang", "=", "str", "(", "language", ")", "# Compilation variants:", "comp_vars", ...
Generate the related compilation and execution commands. Parameters ---------- :param filename : str The used filename. :param class_name : str The used class name. :param language : {'c', 'go', 'java', 'js', 'php', 'ruby'} The targe...
[ "Generate", "the", "related", "compilation", "and", "execution", "commands", "." ]
04673f768310bde31f9747a68a5e070592441ef2
https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/Porter.py#L491-L544
220,793
daviddrysdale/python-phonenumbers
python/phonenumbers/asyoutypeformatter.py
_get_metadata_for_region
def _get_metadata_for_region(region_code): """The metadata needed by this class is the same for all regions sharing the same country calling code. Therefore, we return the metadata for "main" region for this country calling code.""" country_calling_code = country_code_for_region(region_code) main_co...
python
def _get_metadata_for_region(region_code): """The metadata needed by this class is the same for all regions sharing the same country calling code. Therefore, we return the metadata for "main" region for this country calling code.""" country_calling_code = country_code_for_region(region_code) main_co...
[ "def", "_get_metadata_for_region", "(", "region_code", ")", ":", "country_calling_code", "=", "country_code_for_region", "(", "region_code", ")", "main_country", "=", "region_code_for_country_code", "(", "country_calling_code", ")", "# Set to a default instance of the metadata. T...
The metadata needed by this class is the same for all regions sharing the same country calling code. Therefore, we return the metadata for "main" region for this country calling code.
[ "The", "metadata", "needed", "by", "this", "class", "is", "the", "same", "for", "all", "regions", "sharing", "the", "same", "country", "calling", "code", ".", "Therefore", "we", "return", "the", "metadata", "for", "main", "region", "for", "this", "country", ...
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/asyoutypeformatter.py#L70-L79
220,794
daviddrysdale/python-phonenumbers
python/phonenumbers/asyoutypeformatter.py
AsYouTypeFormatter._maybe_create_new_template
def _maybe_create_new_template(self): """Returns True if a new template is created as opposed to reusing the existing template. When there are multiple available formats, the formatter uses the first format where a formatting template could be created. """ ii = 0 while i...
python
def _maybe_create_new_template(self): """Returns True if a new template is created as opposed to reusing the existing template. When there are multiple available formats, the formatter uses the first format where a formatting template could be created. """ ii = 0 while i...
[ "def", "_maybe_create_new_template", "(", "self", ")", ":", "ii", "=", "0", "while", "ii", "<", "len", "(", "self", ".", "_possible_formats", ")", ":", "number_format", "=", "self", ".", "_possible_formats", "[", "ii", "]", "pattern", "=", "number_format", ...
Returns True if a new template is created as opposed to reusing the existing template. When there are multiple available formats, the formatter uses the first format where a formatting template could be created.
[ "Returns", "True", "if", "a", "new", "template", "is", "created", "as", "opposed", "to", "reusing", "the", "existing", "template", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/asyoutypeformatter.py#L97-L125
220,795
daviddrysdale/python-phonenumbers
python/phonenumbers/asyoutypeformatter.py
AsYouTypeFormatter._get_formatting_template
def _get_formatting_template(self, number_pattern, number_format): """Gets a formatting template which can be used to efficiently format a partial number where digits are added one by one.""" # Create a phone number consisting only of the digit 9 that matches the # number_pattern by appl...
python
def _get_formatting_template(self, number_pattern, number_format): """Gets a formatting template which can be used to efficiently format a partial number where digits are added one by one.""" # Create a phone number consisting only of the digit 9 that matches the # number_pattern by appl...
[ "def", "_get_formatting_template", "(", "self", ",", "number_pattern", ",", "number_format", ")", ":", "# Create a phone number consisting only of the digit 9 that matches the", "# number_pattern by applying the pattern to the longest_phone_number string.", "longest_phone_number", "=", "...
Gets a formatting template which can be used to efficiently format a partial number where digits are added one by one.
[ "Gets", "a", "formatting", "template", "which", "can", "be", "used", "to", "efficiently", "format", "a", "partial", "number", "where", "digits", "are", "added", "one", "by", "one", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/asyoutypeformatter.py#L185-L203
220,796
daviddrysdale/python-phonenumbers
python/phonenumbers/asyoutypeformatter.py
AsYouTypeFormatter.input_digit
def input_digit(self, next_char, remember_position=False): """Formats a phone number on-the-fly as each digit is entered. If remember_position is set, remembers the position where next_char is inserted, so that it can be retrieved later by using get_remembered_position. The remembered p...
python
def input_digit(self, next_char, remember_position=False): """Formats a phone number on-the-fly as each digit is entered. If remember_position is set, remembers the position where next_char is inserted, so that it can be retrieved later by using get_remembered_position. The remembered p...
[ "def", "input_digit", "(", "self", ",", "next_char", ",", "remember_position", "=", "False", ")", ":", "self", ".", "_accrued_input", "+=", "next_char", "if", "remember_position", ":", "self", ".", "_original_position", "=", "len", "(", "self", ".", "_accrued_...
Formats a phone number on-the-fly as each digit is entered. If remember_position is set, remembers the position where next_char is inserted, so that it can be retrieved later by using get_remembered_position. The remembered position will be automatically adjusted if additional formattin...
[ "Formats", "a", "phone", "number", "on", "-", "the", "-", "fly", "as", "each", "digit", "is", "entered", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/asyoutypeformatter.py#L254-L353
220,797
daviddrysdale/python-phonenumbers
python/phonenumbers/asyoutypeformatter.py
AsYouTypeFormatter._attempt_to_format_accrued_digits
def _attempt_to_format_accrued_digits(self): """Checks to see if there is an exact pattern match for these digits. If so, we should use this instead of any other formatting template whose leadingDigitsPattern also matches the input. """ for number_format in self._possible_formats: ...
python
def _attempt_to_format_accrued_digits(self): """Checks to see if there is an exact pattern match for these digits. If so, we should use this instead of any other formatting template whose leadingDigitsPattern also matches the input. """ for number_format in self._possible_formats: ...
[ "def", "_attempt_to_format_accrued_digits", "(", "self", ")", ":", "for", "number_format", "in", "self", ".", "_possible_formats", ":", "num_re", "=", "re", ".", "compile", "(", "number_format", ".", "pattern", ")", "if", "fullmatch", "(", "num_re", ",", "self...
Checks to see if there is an exact pattern match for these digits. If so, we should use this instead of any other formatting template whose leadingDigitsPattern also matches the input.
[ "Checks", "to", "see", "if", "there", "is", "an", "exact", "pattern", "match", "for", "these", "digits", ".", "If", "so", "we", "should", "use", "this", "instead", "of", "any", "other", "formatting", "template", "whose", "leadingDigitsPattern", "also", "matc...
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/asyoutypeformatter.py#L385-L398
220,798
daviddrysdale/python-phonenumbers
python/phonenumbers/asyoutypeformatter.py
AsYouTypeFormatter._attempt_to_choose_formatting_pattern
def _attempt_to_choose_formatting_pattern(self): """Attempts to set the formatting template and returns a string which contains the formatted version of the digits entered so far.""" # We start to attempt to format only when at least MIN_LEADING_DIGITS_LENGTH digits of national # number ...
python
def _attempt_to_choose_formatting_pattern(self): """Attempts to set the formatting template and returns a string which contains the formatted version of the digits entered so far.""" # We start to attempt to format only when at least MIN_LEADING_DIGITS_LENGTH digits of national # number ...
[ "def", "_attempt_to_choose_formatting_pattern", "(", "self", ")", ":", "# We start to attempt to format only when at least MIN_LEADING_DIGITS_LENGTH digits of national", "# number (excluding national prefix) have been entered.", "if", "len", "(", "self", ".", "_national_number", ")", "...
Attempts to set the formatting template and returns a string which contains the formatted version of the digits entered so far.
[ "Attempts", "to", "set", "the", "formatting", "template", "and", "returns", "a", "string", "which", "contains", "the", "formatted", "version", "of", "the", "digits", "entered", "so", "far", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/asyoutypeformatter.py#L433-L449
220,799
daviddrysdale/python-phonenumbers
python/phonenumbers/asyoutypeformatter.py
AsYouTypeFormatter._input_accrued_national_number
def _input_accrued_national_number(self): """Invokes input_digit_helper on each digit of the national number accrued, and returns a formatted string in the end.""" length_of_national_number = len(self._national_number) if length_of_national_number > 0: temp_national_number = ...
python
def _input_accrued_national_number(self): """Invokes input_digit_helper on each digit of the national number accrued, and returns a formatted string in the end.""" length_of_national_number = len(self._national_number) if length_of_national_number > 0: temp_national_number = ...
[ "def", "_input_accrued_national_number", "(", "self", ")", ":", "length_of_national_number", "=", "len", "(", "self", ".", "_national_number", ")", "if", "length_of_national_number", ">", "0", ":", "temp_national_number", "=", "U_EMPTY_STRING", "for", "ii", "in", "r...
Invokes input_digit_helper on each digit of the national number accrued, and returns a formatted string in the end.
[ "Invokes", "input_digit_helper", "on", "each", "digit", "of", "the", "national", "number", "accrued", "and", "returns", "a", "formatted", "string", "in", "the", "end", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/asyoutypeformatter.py#L451-L464