repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
nerdynick/PySQLPool
src/PySQLPool/connection.py
ConnectionManager.getCursor
def getCursor(self): """ Get a Dictionary Cursor for executing queries """ if self.connection is None: self.Connect() return self.connection.cursor(MySQLdb.cursors.DictCursor)
python
def getCursor(self): """ Get a Dictionary Cursor for executing queries """ if self.connection is None: self.Connect() return self.connection.cursor(MySQLdb.cursors.DictCursor)
[ "def", "getCursor", "(", "self", ")", ":", "if", "self", ".", "connection", "is", "None", ":", "self", ".", "Connect", "(", ")", "return", "self", ".", "connection", ".", "cursor", "(", "MySQLdb", ".", "cursors", ".", "DictCursor", ")" ]
Get a Dictionary Cursor for executing queries
[ "Get", "a", "Dictionary", "Cursor", "for", "executing", "queries" ]
a561275fea091e2667b69ce376c507f541b56e7d
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/connection.py#L138-L145
train
47,000
nerdynick/PySQLPool
src/PySQLPool/connection.py
ConnectionManager.Connect
def Connect(self): """ Creates a new physical connection to the database @author: Nick Verbeck @since: 5/12/2008 """ if self.connection is None: self.connection = MySQLdb.connect(*[], **self.connectionInfo.info) if self.connectionInfo.commitOnEnd is True: self.connection.autocommit() self._updateCheckTime()
python
def Connect(self): """ Creates a new physical connection to the database @author: Nick Verbeck @since: 5/12/2008 """ if self.connection is None: self.connection = MySQLdb.connect(*[], **self.connectionInfo.info) if self.connectionInfo.commitOnEnd is True: self.connection.autocommit() self._updateCheckTime()
[ "def", "Connect", "(", "self", ")", ":", "if", "self", ".", "connection", "is", "None", ":", "self", ".", "connection", "=", "MySQLdb", ".", "connect", "(", "*", "[", "]", ",", "*", "*", "self", ".", "connectionInfo", ".", "info", ")", "if", "self"...
Creates a new physical connection to the database @author: Nick Verbeck @since: 5/12/2008
[ "Creates", "a", "new", "physical", "connection", "to", "the", "database" ]
a561275fea091e2667b69ce376c507f541b56e7d
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/connection.py#L153-L166
train
47,001
nerdynick/PySQLPool
src/PySQLPool/connection.py
ConnectionManager.being
def being(self): """ Being a Transaction @author: Nick Verbeck @since: 5/14/2011 """ try: if self.connection is not None: self.lock() c = self.getCursor() c.execute('BEGIN;') c.close() except Exception, e: pass
python
def being(self): """ Being a Transaction @author: Nick Verbeck @since: 5/14/2011 """ try: if self.connection is not None: self.lock() c = self.getCursor() c.execute('BEGIN;') c.close() except Exception, e: pass
[ "def", "being", "(", "self", ")", ":", "try", ":", "if", "self", ".", "connection", "is", "not", "None", ":", "self", ".", "lock", "(", ")", "c", "=", "self", ".", "getCursor", "(", ")", "c", ".", "execute", "(", "'BEGIN;'", ")", "c", ".", "clo...
Being a Transaction @author: Nick Verbeck @since: 5/14/2011
[ "Being", "a", "Transaction" ]
a561275fea091e2667b69ce376c507f541b56e7d
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/connection.py#L207-L221
train
47,002
nerdynick/PySQLPool
src/PySQLPool/connection.py
ConnectionManager.Close
def Close(self): """ Commits and closes the current connection @author: Nick Verbeck @since: 5/12/2008 """ if self.connection is not None: try: self.connection.commit() self.connection.close() self.connection = None except Exception, e: pass
python
def Close(self): """ Commits and closes the current connection @author: Nick Verbeck @since: 5/12/2008 """ if self.connection is not None: try: self.connection.commit() self.connection.close() self.connection = None except Exception, e: pass
[ "def", "Close", "(", "self", ")", ":", "if", "self", ".", "connection", "is", "not", "None", ":", "try", ":", "self", ".", "connection", ".", "commit", "(", ")", "self", ".", "connection", ".", "close", "(", ")", "self", ".", "connection", "=", "No...
Commits and closes the current connection @author: Nick Verbeck @since: 5/12/2008
[ "Commits", "and", "closes", "the", "current", "connection" ]
a561275fea091e2667b69ce376c507f541b56e7d
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/connection.py#L261-L274
train
47,003
openspending/babbage
babbage/api.py
configure_api
def configure_api(app, manager): """ Configure the current Flask app with an instance of ``CubeManager`` that will be used to load and query data. """ if not hasattr(app, 'extensions'): app.extensions = {} # pragma: nocover app.extensions['babbage'] = manager return blueprint
python
def configure_api(app, manager): """ Configure the current Flask app with an instance of ``CubeManager`` that will be used to load and query data. """ if not hasattr(app, 'extensions'): app.extensions = {} # pragma: nocover app.extensions['babbage'] = manager return blueprint
[ "def", "configure_api", "(", "app", ",", "manager", ")", ":", "if", "not", "hasattr", "(", "app", ",", "'extensions'", ")", ":", "app", ".", "extensions", "=", "{", "}", "# pragma: nocover", "app", ".", "extensions", "[", "'babbage'", "]", "=", "manager"...
Configure the current Flask app with an instance of ``CubeManager`` that will be used to load and query data.
[ "Configure", "the", "current", "Flask", "app", "with", "an", "instance", "of", "CubeManager", "that", "will", "be", "used", "to", "load", "and", "query", "data", "." ]
9e03efe62e0be0cceabafd4de2a09cb8ec794b92
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/api.py#L16-L22
train
47,004
openspending/babbage
babbage/api.py
get_cube
def get_cube(name): """ Load the named cube from the current registered ``CubeManager``. """ manager = get_manager() if not manager.has_cube(name): raise NotFound('No such cube: %r' % name) return manager.get_cube(name)
python
def get_cube(name): """ Load the named cube from the current registered ``CubeManager``. """ manager = get_manager() if not manager.has_cube(name): raise NotFound('No such cube: %r' % name) return manager.get_cube(name)
[ "def", "get_cube", "(", "name", ")", ":", "manager", "=", "get_manager", "(", ")", "if", "not", "manager", ".", "has_cube", "(", "name", ")", ":", "raise", "NotFound", "(", "'No such cube: %r'", "%", "name", ")", "return", "manager", ".", "get_cube", "("...
Load the named cube from the current registered ``CubeManager``.
[ "Load", "the", "named", "cube", "from", "the", "current", "registered", "CubeManager", "." ]
9e03efe62e0be0cceabafd4de2a09cb8ec794b92
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/api.py#L31-L36
train
47,005
openspending/babbage
babbage/api.py
cubes
def cubes(): """ Get a listing of all publicly available cubes. """ cubes = [] for cube in get_manager().list_cubes(): cubes.append({ 'name': cube }) return jsonify({ 'status': 'ok', 'data': cubes })
python
def cubes(): """ Get a listing of all publicly available cubes. """ cubes = [] for cube in get_manager().list_cubes(): cubes.append({ 'name': cube }) return jsonify({ 'status': 'ok', 'data': cubes })
[ "def", "cubes", "(", ")", ":", "cubes", "=", "[", "]", "for", "cube", "in", "get_manager", "(", ")", ".", "list_cubes", "(", ")", ":", "cubes", ".", "append", "(", "{", "'name'", ":", "cube", "}", ")", "return", "jsonify", "(", "{", "'status'", "...
Get a listing of all publicly available cubes.
[ "Get", "a", "listing", "of", "all", "publicly", "available", "cubes", "." ]
9e03efe62e0be0cceabafd4de2a09cb8ec794b92
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/api.py#L120-L130
train
47,006
openspending/babbage
babbage/api.py
aggregate
def aggregate(name): """ Perform an aggregation request. """ cube = get_cube(name) result = cube.aggregate(aggregates=request.args.get('aggregates'), drilldowns=request.args.get('drilldown'), cuts=request.args.get('cut'), order=request.args.get('order'), page=request.args.get('page'), page_size=request.args.get('pagesize')) result['status'] = 'ok' if request.args.get('format', '').lower() == 'csv': return create_csv_response(result['cells']) else: return jsonify(result)
python
def aggregate(name): """ Perform an aggregation request. """ cube = get_cube(name) result = cube.aggregate(aggregates=request.args.get('aggregates'), drilldowns=request.args.get('drilldown'), cuts=request.args.get('cut'), order=request.args.get('order'), page=request.args.get('page'), page_size=request.args.get('pagesize')) result['status'] = 'ok' if request.args.get('format', '').lower() == 'csv': return create_csv_response(result['cells']) else: return jsonify(result)
[ "def", "aggregate", "(", "name", ")", ":", "cube", "=", "get_cube", "(", "name", ")", "result", "=", "cube", ".", "aggregate", "(", "aggregates", "=", "request", ".", "args", ".", "get", "(", "'aggregates'", ")", ",", "drilldowns", "=", "request", ".",...
Perform an aggregation request.
[ "Perform", "an", "aggregation", "request", "." ]
9e03efe62e0be0cceabafd4de2a09cb8ec794b92
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/api.py#L145-L159
train
47,007
openspending/babbage
babbage/api.py
facts
def facts(name): """ List the fact table entries in the current cube. This is the full materialized dataset. """ cube = get_cube(name) result = cube.facts(fields=request.args.get('fields'), cuts=request.args.get('cut'), order=request.args.get('order'), page=request.args.get('page'), page_size=request.args.get('pagesize')) result['status'] = 'ok' return jsonify(result)
python
def facts(name): """ List the fact table entries in the current cube. This is the full materialized dataset. """ cube = get_cube(name) result = cube.facts(fields=request.args.get('fields'), cuts=request.args.get('cut'), order=request.args.get('order'), page=request.args.get('page'), page_size=request.args.get('pagesize')) result['status'] = 'ok' return jsonify(result)
[ "def", "facts", "(", "name", ")", ":", "cube", "=", "get_cube", "(", "name", ")", "result", "=", "cube", ".", "facts", "(", "fields", "=", "request", ".", "args", ".", "get", "(", "'fields'", ")", ",", "cuts", "=", "request", ".", "args", ".", "g...
List the fact table entries in the current cube. This is the full materialized dataset.
[ "List", "the", "fact", "table", "entries", "in", "the", "current", "cube", ".", "This", "is", "the", "full", "materialized", "dataset", "." ]
9e03efe62e0be0cceabafd4de2a09cb8ec794b92
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/api.py#L163-L173
train
47,008
openspending/babbage
babbage/api.py
members
def members(name, ref): """ List the members of a specific dimension or the distinct values of a given attribute. """ cube = get_cube(name) result = cube.members(ref, cuts=request.args.get('cut'), order=request.args.get('order'), page=request.args.get('page'), page_size=request.args.get('pagesize')) result['status'] = 'ok' return jsonify(result)
python
def members(name, ref): """ List the members of a specific dimension or the distinct values of a given attribute. """ cube = get_cube(name) result = cube.members(ref, cuts=request.args.get('cut'), order=request.args.get('order'), page=request.args.get('page'), page_size=request.args.get('pagesize')) result['status'] = 'ok' return jsonify(result)
[ "def", "members", "(", "name", ",", "ref", ")", ":", "cube", "=", "get_cube", "(", "name", ")", "result", "=", "cube", ".", "members", "(", "ref", ",", "cuts", "=", "request", ".", "args", ".", "get", "(", "'cut'", ")", ",", "order", "=", "reques...
List the members of a specific dimension or the distinct values of a given attribute.
[ "List", "the", "members", "of", "a", "specific", "dimension", "or", "the", "distinct", "values", "of", "a", "given", "attribute", "." ]
9e03efe62e0be0cceabafd4de2a09cb8ec794b92
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/api.py#L177-L186
train
47,009
openspending/babbage
babbage/query/drilldowns.py
Drilldowns.apply
def apply(self, q, bindings, drilldowns): """ Apply a set of grouping criteria and project them. """ info = [] for drilldown in self.parse(drilldowns): for attribute in self.cube.model.match(drilldown): info.append(attribute.ref) table, column = attribute.bind(self.cube) bindings.append(Binding(table, attribute.ref)) q = q.column(column) q = q.group_by(column) return info, q, bindings
python
def apply(self, q, bindings, drilldowns): """ Apply a set of grouping criteria and project them. """ info = [] for drilldown in self.parse(drilldowns): for attribute in self.cube.model.match(drilldown): info.append(attribute.ref) table, column = attribute.bind(self.cube) bindings.append(Binding(table, attribute.ref)) q = q.column(column) q = q.group_by(column) return info, q, bindings
[ "def", "apply", "(", "self", ",", "q", ",", "bindings", ",", "drilldowns", ")", ":", "info", "=", "[", "]", "for", "drilldown", "in", "self", ".", "parse", "(", "drilldowns", ")", ":", "for", "attribute", "in", "self", ".", "cube", ".", "model", "....
Apply a set of grouping criteria and project them.
[ "Apply", "a", "set", "of", "grouping", "criteria", "and", "project", "them", "." ]
9e03efe62e0be0cceabafd4de2a09cb8ec794b92
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/query/drilldowns.py#L18-L28
train
47,010
openspending/babbage
babbage/validation.py
check_attribute_exists
def check_attribute_exists(instance): """ Additional check for the dimension model, to ensure that attributes given as the key and label attribute on the dimension exist. """ attributes = instance.get('attributes', {}).keys() if instance.get('key_attribute') not in attributes: return False label_attr = instance.get('label_attribute') if label_attr and label_attr not in attributes: return False return True
python
def check_attribute_exists(instance): """ Additional check for the dimension model, to ensure that attributes given as the key and label attribute on the dimension exist. """ attributes = instance.get('attributes', {}).keys() if instance.get('key_attribute') not in attributes: return False label_attr = instance.get('label_attribute') if label_attr and label_attr not in attributes: return False return True
[ "def", "check_attribute_exists", "(", "instance", ")", ":", "attributes", "=", "instance", ".", "get", "(", "'attributes'", ",", "{", "}", ")", ".", "keys", "(", ")", "if", "instance", ".", "get", "(", "'key_attribute'", ")", "not", "in", "attributes", "...
Additional check for the dimension model, to ensure that attributes given as the key and label attribute on the dimension exist.
[ "Additional", "check", "for", "the", "dimension", "model", "to", "ensure", "that", "attributes", "given", "as", "the", "key", "and", "label", "attribute", "on", "the", "dimension", "exist", "." ]
9e03efe62e0be0cceabafd4de2a09cb8ec794b92
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/validation.py#L11-L20
train
47,011
openspending/babbage
babbage/validation.py
check_valid_hierarchies
def check_valid_hierarchies(instance): """ Additional check for the hierarchies model, to ensure that levels given are pointing to actual dimensions """ hierarchies = instance.get('hierarchies', {}).values() dimensions = set(instance.get('dimensions', {}).keys()) all_levels = set() for hierarcy in hierarchies: levels = set(hierarcy.get('levels', [])) if len(all_levels.intersection(levels)) > 0: # Dimension appears in two different hierarchies return False all_levels = all_levels.union(levels) if not dimensions.issuperset(levels): # Level which is not in a dimension return False return True
python
def check_valid_hierarchies(instance): """ Additional check for the hierarchies model, to ensure that levels given are pointing to actual dimensions """ hierarchies = instance.get('hierarchies', {}).values() dimensions = set(instance.get('dimensions', {}).keys()) all_levels = set() for hierarcy in hierarchies: levels = set(hierarcy.get('levels', [])) if len(all_levels.intersection(levels)) > 0: # Dimension appears in two different hierarchies return False all_levels = all_levels.union(levels) if not dimensions.issuperset(levels): # Level which is not in a dimension return False return True
[ "def", "check_valid_hierarchies", "(", "instance", ")", ":", "hierarchies", "=", "instance", ".", "get", "(", "'hierarchies'", ",", "{", "}", ")", ".", "values", "(", ")", "dimensions", "=", "set", "(", "instance", ".", "get", "(", "'dimensions'", ",", "...
Additional check for the hierarchies model, to ensure that levels given are pointing to actual dimensions
[ "Additional", "check", "for", "the", "hierarchies", "model", "to", "ensure", "that", "levels", "given", "are", "pointing", "to", "actual", "dimensions" ]
9e03efe62e0be0cceabafd4de2a09cb8ec794b92
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/validation.py#L24-L39
train
47,012
openspending/babbage
babbage/validation.py
load_validator
def load_validator(name): """ Load the JSON Schema Draft 4 validator with the given name from the local schema directory. """ with open(os.path.join(SCHEMA_PATH, name)) as fh: schema = json.load(fh) Draft4Validator.check_schema(schema) return Draft4Validator(schema, format_checker=checker)
python
def load_validator(name): """ Load the JSON Schema Draft 4 validator with the given name from the local schema directory. """ with open(os.path.join(SCHEMA_PATH, name)) as fh: schema = json.load(fh) Draft4Validator.check_schema(schema) return Draft4Validator(schema, format_checker=checker)
[ "def", "load_validator", "(", "name", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "SCHEMA_PATH", ",", "name", ")", ")", "as", "fh", ":", "schema", "=", "json", ".", "load", "(", "fh", ")", "Draft4Validator", ".", "check_schema...
Load the JSON Schema Draft 4 validator with the given name from the local schema directory.
[ "Load", "the", "JSON", "Schema", "Draft", "4", "validator", "with", "the", "given", "name", "from", "the", "local", "schema", "directory", "." ]
9e03efe62e0be0cceabafd4de2a09cb8ec794b92
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/validation.py#L42-L48
train
47,013
openspending/babbage
babbage/manager.py
CubeManager.get_cube
def get_cube(self, name): """ Given a cube name, construct that cube and return it. Do not overwrite this method unless you need to. """ return Cube(self.get_engine(), name, self.get_cube_model(name))
python
def get_cube(self, name): """ Given a cube name, construct that cube and return it. Do not overwrite this method unless you need to. """ return Cube(self.get_engine(), name, self.get_cube_model(name))
[ "def", "get_cube", "(", "self", ",", "name", ")", ":", "return", "Cube", "(", "self", ".", "get_engine", "(", ")", ",", "name", ",", "self", ".", "get_cube_model", "(", "name", ")", ")" ]
Given a cube name, construct that cube and return it. Do not overwrite this method unless you need to.
[ "Given", "a", "cube", "name", "construct", "that", "cube", "and", "return", "it", ".", "Do", "not", "overwrite", "this", "method", "unless", "you", "need", "to", "." ]
9e03efe62e0be0cceabafd4de2a09cb8ec794b92
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/manager.py#L41-L44
train
47,014
openspending/babbage
babbage/manager.py
JSONCubeManager.list_cubes
def list_cubes(self): """ List all available JSON files. """ for file_name in os.listdir(self.directory): if '.' in file_name: name, ext = file_name.rsplit('.', 1) if ext.lower() == 'json': yield name
python
def list_cubes(self): """ List all available JSON files. """ for file_name in os.listdir(self.directory): if '.' in file_name: name, ext = file_name.rsplit('.', 1) if ext.lower() == 'json': yield name
[ "def", "list_cubes", "(", "self", ")", ":", "for", "file_name", "in", "os", ".", "listdir", "(", "self", ".", "directory", ")", ":", "if", "'.'", "in", "file_name", ":", "name", ",", "ext", "=", "file_name", ".", "rsplit", "(", "'.'", ",", "1", ")"...
List all available JSON files.
[ "List", "all", "available", "JSON", "files", "." ]
9e03efe62e0be0cceabafd4de2a09cb8ec794b92
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/manager.py#L55-L61
train
47,015
nerdynick/PySQLPool
src/PySQLPool/pool.py
Pool.Terminate
def Terminate(self): """ Close all open connections Loop though all the connections and commit all queries and close all the connections. This should be called at the end of your application. @author: Nick Verbeck @since: 5/12/2008 """ self.lock.acquire() try: for bucket in self.connections.values(): try: for conn in bucket: conn.lock() try: conn.Close() except Exception: #We may throw exceptions due to already closed connections pass conn.release() except Exception: pass self.connections = {} finally: self.lock.release()
python
def Terminate(self): """ Close all open connections Loop though all the connections and commit all queries and close all the connections. This should be called at the end of your application. @author: Nick Verbeck @since: 5/12/2008 """ self.lock.acquire() try: for bucket in self.connections.values(): try: for conn in bucket: conn.lock() try: conn.Close() except Exception: #We may throw exceptions due to already closed connections pass conn.release() except Exception: pass self.connections = {} finally: self.lock.release()
[ "def", "Terminate", "(", "self", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "for", "bucket", "in", "self", ".", "connections", ".", "values", "(", ")", ":", "try", ":", "for", "conn", "in", "bucket", ":", "conn", ".", "l...
Close all open connections Loop though all the connections and commit all queries and close all the connections. This should be called at the end of your application. @author: Nick Verbeck @since: 5/12/2008
[ "Close", "all", "open", "connections", "Loop", "though", "all", "the", "connections", "and", "commit", "all", "queries", "and", "close", "all", "the", "connections", ".", "This", "should", "be", "called", "at", "the", "end", "of", "your", "application", "." ...
a561275fea091e2667b69ce376c507f541b56e7d
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/pool.py#L42-L69
train
47,016
nerdynick/PySQLPool
src/PySQLPool/pool.py
Pool.Cleanup
def Cleanup(self): """ Cleanup Timed out connections Loop though all the connections and test if still active. If inactive close socket. @author: Nick Verbeck @since: 2/20/2009 """ self.lock.acquire() try: for bucket in self.connections.values(): try: for conn in bucket: conn.lock() try: open = conn.TestConnection(forceCheck=True) if open is True: conn.commit() else: #Remove the connection from the pool. Its dead better of recreating it. index = bucket.index(conn) del bucket[index] conn.release() except Exception: conn.release() except Exception: pass finally: self.lock.release()
python
def Cleanup(self): """ Cleanup Timed out connections Loop though all the connections and test if still active. If inactive close socket. @author: Nick Verbeck @since: 2/20/2009 """ self.lock.acquire() try: for bucket in self.connections.values(): try: for conn in bucket: conn.lock() try: open = conn.TestConnection(forceCheck=True) if open is True: conn.commit() else: #Remove the connection from the pool. Its dead better of recreating it. index = bucket.index(conn) del bucket[index] conn.release() except Exception: conn.release() except Exception: pass finally: self.lock.release()
[ "def", "Cleanup", "(", "self", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "for", "bucket", "in", "self", ".", "connections", ".", "values", "(", ")", ":", "try", ":", "for", "conn", "in", "bucket", ":", "conn", ".", "loc...
Cleanup Timed out connections Loop though all the connections and test if still active. If inactive close socket. @author: Nick Verbeck @since: 2/20/2009
[ "Cleanup", "Timed", "out", "connections", "Loop", "though", "all", "the", "connections", "and", "test", "if", "still", "active", ".", "If", "inactive", "close", "socket", "." ]
a561275fea091e2667b69ce376c507f541b56e7d
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/pool.py#L71-L100
train
47,017
nerdynick/PySQLPool
src/PySQLPool/pool.py
Pool.Commit
def Commit(self): """ Commits all currently open connections @author: Nick Verbeck @since: 9/12/2008 """ self.lock.acquire() try: for bucket in self.connections.values(): try: for conn in bucket: conn.lock() try: conn.commit() conn.release() except Exception: conn.release() except Exception: pass finally: self.lock.release()
python
def Commit(self): """ Commits all currently open connections @author: Nick Verbeck @since: 9/12/2008 """ self.lock.acquire() try: for bucket in self.connections.values(): try: for conn in bucket: conn.lock() try: conn.commit() conn.release() except Exception: conn.release() except Exception: pass finally: self.lock.release()
[ "def", "Commit", "(", "self", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "for", "bucket", "in", "self", ".", "connections", ".", "values", "(", ")", ":", "try", ":", "for", "conn", "in", "bucket", ":", "conn", ".", "lock...
Commits all currently open connections @author: Nick Verbeck @since: 9/12/2008
[ "Commits", "all", "currently", "open", "connections" ]
a561275fea091e2667b69ce376c507f541b56e7d
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/pool.py#L102-L123
train
47,018
nerdynick/PySQLPool
src/PySQLPool/pool.py
Pool.GetConnection
def GetConnection(self, ConnectionObj): """ Get a Open and active connection Returns a PySQLConnectionManager if one is open else it will create a new one if the max active connections hasn't been hit. If all possible connections are used. Then None is returned. @param PySQLConnectionObj: PySQLConnection Object representing your connection string @author: Nick Verbeck @since: 5/12/2008 """ key = ConnectionObj.getKey() connection = None if self.connections.has_key(key): connection = self._getConnectionFromPoolSet(key) if connection is None: self.lock.acquire() if len(self.connections[key]) < self.maxActiveConnections: #Create a new connection connection = self._createConnection(ConnectionObj) self.connections[key].append(connection) self.lock.release() else: #Wait for a free connection. We maintain the lock on the pool so we are the 1st to get a connection. while connection is None: connection = self._getConnectionFromPoolSet(key) self.lock.release() #Create new Connection Pool Set else: self.lock.acquire() #We do a double check now that its locked to be sure some other thread didn't create this while we may have been waiting. if not self.connections.has_key(key): self.connections[key] = [] if len(self.connections[key]) < self.maxActiveConnections: #Create a new connection connection = self._createConnection(ConnectionObj) self.connections[key].append(connection) else: #A rare thing happened. So many threads created connections so fast we need to wait for a free one. while connection is None: connection = self._getConnectionFromPoolSet(key) self.lock.release() return connection
python
def GetConnection(self, ConnectionObj): """ Get a Open and active connection Returns a PySQLConnectionManager if one is open else it will create a new one if the max active connections hasn't been hit. If all possible connections are used. Then None is returned. @param PySQLConnectionObj: PySQLConnection Object representing your connection string @author: Nick Verbeck @since: 5/12/2008 """ key = ConnectionObj.getKey() connection = None if self.connections.has_key(key): connection = self._getConnectionFromPoolSet(key) if connection is None: self.lock.acquire() if len(self.connections[key]) < self.maxActiveConnections: #Create a new connection connection = self._createConnection(ConnectionObj) self.connections[key].append(connection) self.lock.release() else: #Wait for a free connection. We maintain the lock on the pool so we are the 1st to get a connection. while connection is None: connection = self._getConnectionFromPoolSet(key) self.lock.release() #Create new Connection Pool Set else: self.lock.acquire() #We do a double check now that its locked to be sure some other thread didn't create this while we may have been waiting. if not self.connections.has_key(key): self.connections[key] = [] if len(self.connections[key]) < self.maxActiveConnections: #Create a new connection connection = self._createConnection(ConnectionObj) self.connections[key].append(connection) else: #A rare thing happened. So many threads created connections so fast we need to wait for a free one. while connection is None: connection = self._getConnectionFromPoolSet(key) self.lock.release() return connection
[ "def", "GetConnection", "(", "self", ",", "ConnectionObj", ")", ":", "key", "=", "ConnectionObj", ".", "getKey", "(", ")", "connection", "=", "None", "if", "self", ".", "connections", ".", "has_key", "(", "key", ")", ":", "connection", "=", "self", ".", ...
Get a Open and active connection Returns a PySQLConnectionManager if one is open else it will create a new one if the max active connections hasn't been hit. If all possible connections are used. Then None is returned. @param PySQLConnectionObj: PySQLConnection Object representing your connection string @author: Nick Verbeck @since: 5/12/2008
[ "Get", "a", "Open", "and", "active", "connection", "Returns", "a", "PySQLConnectionManager", "if", "one", "is", "open", "else", "it", "will", "create", "a", "new", "one", "if", "the", "max", "active", "connections", "hasn", "t", "been", "hit", ".", "If", ...
a561275fea091e2667b69ce376c507f541b56e7d
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/pool.py#L125-L174
train
47,019
bachya/regenmaschine
regenmaschine/stats.py
Stats.on_date
async def on_date(self, date: datetime.date) -> dict: """Get statistics for a certain date.""" return await self._request( 'get', 'dailystats/{0}'.format(date.strftime('%Y-%m-%d')))
python
async def on_date(self, date: datetime.date) -> dict: """Get statistics for a certain date.""" return await self._request( 'get', 'dailystats/{0}'.format(date.strftime('%Y-%m-%d')))
[ "async", "def", "on_date", "(", "self", ",", "date", ":", "datetime", ".", "date", ")", "->", "dict", ":", "return", "await", "self", ".", "_request", "(", "'get'", ",", "'dailystats/{0}'", ".", "format", "(", "date", ".", "strftime", "(", "'%Y-%m-%d'", ...
Get statistics for a certain date.
[ "Get", "statistics", "for", "a", "certain", "date", "." ]
99afb648fe454dc4a7d5db85a02a8b3b5d26f8bc
https://github.com/bachya/regenmaschine/blob/99afb648fe454dc4a7d5db85a02a8b3b5d26f8bc/regenmaschine/stats.py#L13-L16
train
47,020
bachya/regenmaschine
regenmaschine/stats.py
Stats.upcoming
async def upcoming(self, details: bool = False) -> list: """Return watering statistics for the next 6 days.""" endpoint = 'dailystats' key = 'DailyStats' if details: endpoint += '/details' key = 'DailyStatsDetails' data = await self._request('get', endpoint) return data[key]
python
async def upcoming(self, details: bool = False) -> list: """Return watering statistics for the next 6 days.""" endpoint = 'dailystats' key = 'DailyStats' if details: endpoint += '/details' key = 'DailyStatsDetails' data = await self._request('get', endpoint) return data[key]
[ "async", "def", "upcoming", "(", "self", ",", "details", ":", "bool", "=", "False", ")", "->", "list", ":", "endpoint", "=", "'dailystats'", "key", "=", "'DailyStats'", "if", "details", ":", "endpoint", "+=", "'/details'", "key", "=", "'DailyStatsDetails'", ...
Return watering statistics for the next 6 days.
[ "Return", "watering", "statistics", "for", "the", "next", "6", "days", "." ]
99afb648fe454dc4a7d5db85a02a8b3b5d26f8bc
https://github.com/bachya/regenmaschine/blob/99afb648fe454dc4a7d5db85a02a8b3b5d26f8bc/regenmaschine/stats.py#L18-L26
train
47,021
bachya/regenmaschine
regenmaschine/client.py
_raise_for_remote_status
def _raise_for_remote_status(url: str, data: dict) -> None: """Raise an error from the remote API if necessary.""" if data.get('errorType') and data['errorType'] > 0: raise_remote_error(data['errorType']) if data.get('statusCode') and data['statusCode'] != 200: raise RequestError( 'Error requesting data from {0}: {1} {2}'.format( url, data['statusCode'], data['message']))
python
def _raise_for_remote_status(url: str, data: dict) -> None: """Raise an error from the remote API if necessary.""" if data.get('errorType') and data['errorType'] > 0: raise_remote_error(data['errorType']) if data.get('statusCode') and data['statusCode'] != 200: raise RequestError( 'Error requesting data from {0}: {1} {2}'.format( url, data['statusCode'], data['message']))
[ "def", "_raise_for_remote_status", "(", "url", ":", "str", ",", "data", ":", "dict", ")", "->", "None", ":", "if", "data", ".", "get", "(", "'errorType'", ")", "and", "data", "[", "'errorType'", "]", ">", "0", ":", "raise_remote_error", "(", "data", "[...
Raise an error from the remote API if necessary.
[ "Raise", "an", "error", "from", "the", "remote", "API", "if", "necessary", "." ]
99afb648fe454dc4a7d5db85a02a8b3b5d26f8bc
https://github.com/bachya/regenmaschine/blob/99afb648fe454dc4a7d5db85a02a8b3b5d26f8bc/regenmaschine/client.py#L140-L148
train
47,022
bachya/regenmaschine
regenmaschine/client.py
login
async def login( host: str, password: str, websession: ClientSession, *, port: int = 8080, ssl: bool = True, request_timeout: int = DEFAULT_TIMEOUT) -> Controller: """Authenticate against a RainMachine device.""" print('regenmaschine.client.login() is deprecated; see documentation!') client = Client(websession, request_timeout) await client.load_local(host, password, port, ssl) return next(iter(client.controllers.values()))
python
async def login( host: str, password: str, websession: ClientSession, *, port: int = 8080, ssl: bool = True, request_timeout: int = DEFAULT_TIMEOUT) -> Controller: """Authenticate against a RainMachine device.""" print('regenmaschine.client.login() is deprecated; see documentation!') client = Client(websession, request_timeout) await client.load_local(host, password, port, ssl) return next(iter(client.controllers.values()))
[ "async", "def", "login", "(", "host", ":", "str", ",", "password", ":", "str", ",", "websession", ":", "ClientSession", ",", "*", ",", "port", ":", "int", "=", "8080", ",", "ssl", ":", "bool", "=", "True", ",", "request_timeout", ":", "int", "=", "...
Authenticate against a RainMachine device.
[ "Authenticate", "against", "a", "RainMachine", "device", "." ]
99afb648fe454dc4a7d5db85a02a8b3b5d26f8bc
https://github.com/bachya/regenmaschine/blob/99afb648fe454dc4a7d5db85a02a8b3b5d26f8bc/regenmaschine/client.py#L151-L163
train
47,023
bachya/regenmaschine
regenmaschine/errors.py
raise_remote_error
def raise_remote_error(error_code: int) -> None: """Raise the appropriate error with a remote error code.""" try: error = next((v for k, v in ERROR_CODES.items() if k == error_code)) raise RequestError(error) except StopIteration: raise RequestError( 'Unknown remote error code returned: {0}'.format(error_code))
python
def raise_remote_error(error_code: int) -> None: """Raise the appropriate error with a remote error code.""" try: error = next((v for k, v in ERROR_CODES.items() if k == error_code)) raise RequestError(error) except StopIteration: raise RequestError( 'Unknown remote error code returned: {0}'.format(error_code))
[ "def", "raise_remote_error", "(", "error_code", ":", "int", ")", "->", "None", ":", "try", ":", "error", "=", "next", "(", "(", "v", "for", "k", ",", "v", "in", "ERROR_CODES", ".", "items", "(", ")", "if", "k", "==", "error_code", ")", ")", "raise"...
Raise the appropriate error with a remote error code.
[ "Raise", "the", "appropriate", "error", "with", "a", "remote", "error", "code", "." ]
99afb648fe454dc4a7d5db85a02a8b3b5d26f8bc
https://github.com/bachya/regenmaschine/blob/99afb648fe454dc4a7d5db85a02a8b3b5d26f8bc/regenmaschine/errors.py#L27-L34
train
47,024
workforce-data-initiative/skills-utils
skills_utils/metta.py
quarter_boundaries
def quarter_boundaries(quarter): """Returns first and last day of a quarter Args: quarter (str) quarter, in format '2015Q1' Returns: (tuple) datetime.dates for the first and last days of the quarter """ year, quarter = quarter.split('Q') year = int(year) quarter = int(quarter) first_month_of_quarter = 3 * quarter - 2 last_month_of_quarter = 3 * quarter first_day = date(year, first_month_of_quarter, 1) last_day = date(year, last_month_of_quarter, monthrange(year, last_month_of_quarter)[1]) return first_day, last_day
python
def quarter_boundaries(quarter): """Returns first and last day of a quarter Args: quarter (str) quarter, in format '2015Q1' Returns: (tuple) datetime.dates for the first and last days of the quarter """ year, quarter = quarter.split('Q') year = int(year) quarter = int(quarter) first_month_of_quarter = 3 * quarter - 2 last_month_of_quarter = 3 * quarter first_day = date(year, first_month_of_quarter, 1) last_day = date(year, last_month_of_quarter, monthrange(year, last_month_of_quarter)[1]) return first_day, last_day
[ "def", "quarter_boundaries", "(", "quarter", ")", ":", "year", ",", "quarter", "=", "quarter", ".", "split", "(", "'Q'", ")", "year", "=", "int", "(", "year", ")", "quarter", "=", "int", "(", "quarter", ")", "first_month_of_quarter", "=", "3", "*", "qu...
Returns first and last day of a quarter Args: quarter (str) quarter, in format '2015Q1' Returns: (tuple) datetime.dates for the first and last days of the quarter
[ "Returns", "first", "and", "last", "day", "of", "a", "quarter" ]
4cf9b7c2938984f34bbcc33d45482d23c52c7539
https://github.com/workforce-data-initiative/skills-utils/blob/4cf9b7c2938984f34bbcc33d45482d23c52c7539/skills_utils/metta.py#L9-L24
train
47,025
workforce-data-initiative/skills-utils
skills_utils/metta.py
metta_config
def metta_config(quarter, num_dimensions): """Returns metta metadata for a quarter's SOC code classifier matrix Args: quarter (str) quarter, in format '2015Q1' num_dimensions (int) Number of features in matrix Returns: (dict) metadata suitable for metta.archive_train_test """ first_day, last_day = quarter_boundaries(quarter) return { 'start_time': first_day, 'end_time': last_day, 'prediction_window': 3, # ??? 'label_name': 'onet_soc_code', 'label_type': 'categorical', 'matrix_id': 'job_postings_{}'.format(quarter), 'feature_names': ['doc2vec_{}'.format(i) for i in range(num_dimensions)], }
python
def metta_config(quarter, num_dimensions): """Returns metta metadata for a quarter's SOC code classifier matrix Args: quarter (str) quarter, in format '2015Q1' num_dimensions (int) Number of features in matrix Returns: (dict) metadata suitable for metta.archive_train_test """ first_day, last_day = quarter_boundaries(quarter) return { 'start_time': first_day, 'end_time': last_day, 'prediction_window': 3, # ??? 'label_name': 'onet_soc_code', 'label_type': 'categorical', 'matrix_id': 'job_postings_{}'.format(quarter), 'feature_names': ['doc2vec_{}'.format(i) for i in range(num_dimensions)], }
[ "def", "metta_config", "(", "quarter", ",", "num_dimensions", ")", ":", "first_day", ",", "last_day", "=", "quarter_boundaries", "(", "quarter", ")", "return", "{", "'start_time'", ":", "first_day", ",", "'end_time'", ":", "last_day", ",", "'prediction_window'", ...
Returns metta metadata for a quarter's SOC code classifier matrix Args: quarter (str) quarter, in format '2015Q1' num_dimensions (int) Number of features in matrix Returns: (dict) metadata suitable for metta.archive_train_test
[ "Returns", "metta", "metadata", "for", "a", "quarter", "s", "SOC", "code", "classifier", "matrix" ]
4cf9b7c2938984f34bbcc33d45482d23c52c7539
https://github.com/workforce-data-initiative/skills-utils/blob/4cf9b7c2938984f34bbcc33d45482d23c52c7539/skills_utils/metta.py#L27-L45
train
47,026
workforce-data-initiative/skills-utils
skills_utils/metta.py
upload_to_metta
def upload_to_metta(train_features_path, train_labels_path, test_features_path, test_labels_path, train_quarter, test_quarter, num_dimensions): """Store train and test matrices using metta Args: train_features_path (str) Path to matrix with train features train_labels_path (str) Path to matrix with train labels test_features_path (str) Path to matrix with test features test_labels_path (str) Path to matrix with test labels train_quarter (str) Quarter of train matrix test_quarter (str) Quarter of test matrix num_dimensions (int) Number of features """ train_config = metta_config(train_quarter, num_dimensions) test_config = metta_config(test_quarter, num_dimensions) X_train = pd.read_csv(train_features_path, sep=',') X_train.columns = ['doc2vec_'+str(i) for i in range(X_train.shape[1])] #X_train['label'] = pd.Series([randint(0,23) for i in range(len(X_train))]) Y_train = pd.read_csv(train_labels_path) Y_train.columns = ['onet_soc_code'] train = pd.concat([X_train, Y_train], axis=1) X_test = pd.read_csv(test_features_path, sep=',') X_test.columns = ['doc2vec_'+str(i) for i in range(X_test.shape[1])] #X_test['label'] = pd.Series([randint(0,23) for i in range(len(X_test))]) Y_test = pd.read_csv(test_labels_path) Y_test.columns = ['onet_soc_code'] test = pd.concat([X_test, Y_test], axis=1) #print(train.head()) #print(train.shape) #print(test.head()) #print(test.shape) metta.archive_train_test( train_config, X_train, test_config, X_test, directory='wdi' )
python
def upload_to_metta(train_features_path, train_labels_path, test_features_path, test_labels_path, train_quarter, test_quarter, num_dimensions): """Store train and test matrices using metta Args: train_features_path (str) Path to matrix with train features train_labels_path (str) Path to matrix with train labels test_features_path (str) Path to matrix with test features test_labels_path (str) Path to matrix with test labels train_quarter (str) Quarter of train matrix test_quarter (str) Quarter of test matrix num_dimensions (int) Number of features """ train_config = metta_config(train_quarter, num_dimensions) test_config = metta_config(test_quarter, num_dimensions) X_train = pd.read_csv(train_features_path, sep=',') X_train.columns = ['doc2vec_'+str(i) for i in range(X_train.shape[1])] #X_train['label'] = pd.Series([randint(0,23) for i in range(len(X_train))]) Y_train = pd.read_csv(train_labels_path) Y_train.columns = ['onet_soc_code'] train = pd.concat([X_train, Y_train], axis=1) X_test = pd.read_csv(test_features_path, sep=',') X_test.columns = ['doc2vec_'+str(i) for i in range(X_test.shape[1])] #X_test['label'] = pd.Series([randint(0,23) for i in range(len(X_test))]) Y_test = pd.read_csv(test_labels_path) Y_test.columns = ['onet_soc_code'] test = pd.concat([X_test, Y_test], axis=1) #print(train.head()) #print(train.shape) #print(test.head()) #print(test.shape) metta.archive_train_test( train_config, X_train, test_config, X_test, directory='wdi' )
[ "def", "upload_to_metta", "(", "train_features_path", ",", "train_labels_path", ",", "test_features_path", ",", "test_labels_path", ",", "train_quarter", ",", "test_quarter", ",", "num_dimensions", ")", ":", "train_config", "=", "metta_config", "(", "train_quarter", ","...
Store train and test matrices using metta Args: train_features_path (str) Path to matrix with train features train_labels_path (str) Path to matrix with train labels test_features_path (str) Path to matrix with test features test_labels_path (str) Path to matrix with test labels train_quarter (str) Quarter of train matrix test_quarter (str) Quarter of test matrix num_dimensions (int) Number of features
[ "Store", "train", "and", "test", "matrices", "using", "metta" ]
4cf9b7c2938984f34bbcc33d45482d23c52c7539
https://github.com/workforce-data-initiative/skills-utils/blob/4cf9b7c2938984f34bbcc33d45482d23c52c7539/skills_utils/metta.py#L47-L85
train
47,027
workforce-data-initiative/skills-utils
skills_utils/s3.py
upload
def upload(s3_conn, filepath, s3_path): """Uploads the given file to s3 Args: s3_conn: (boto.s3.connection) an s3 connection filepath (str) the local filename s3_path (str) the destination path on s3 """ bucket_name, prefix = split_s3_path(s3_path) bucket = s3_conn.get_bucket(bucket_name) filename = os.path.basename(filepath) key = boto.s3.key.Key( bucket=bucket, name='{}/{}'.format(prefix, filename) ) logging.info('uploading from %s to %s', filepath, key) key.set_contents_from_filename(filepath)
python
def upload(s3_conn, filepath, s3_path): """Uploads the given file to s3 Args: s3_conn: (boto.s3.connection) an s3 connection filepath (str) the local filename s3_path (str) the destination path on s3 """ bucket_name, prefix = split_s3_path(s3_path) bucket = s3_conn.get_bucket(bucket_name) filename = os.path.basename(filepath) key = boto.s3.key.Key( bucket=bucket, name='{}/{}'.format(prefix, filename) ) logging.info('uploading from %s to %s', filepath, key) key.set_contents_from_filename(filepath)
[ "def", "upload", "(", "s3_conn", ",", "filepath", ",", "s3_path", ")", ":", "bucket_name", ",", "prefix", "=", "split_s3_path", "(", "s3_path", ")", "bucket", "=", "s3_conn", ".", "get_bucket", "(", "bucket_name", ")", "filename", "=", "os", ".", "path", ...
Uploads the given file to s3 Args: s3_conn: (boto.s3.connection) an s3 connection filepath (str) the local filename s3_path (str) the destination path on s3
[ "Uploads", "the", "given", "file", "to", "s3" ]
4cf9b7c2938984f34bbcc33d45482d23c52c7539
https://github.com/workforce-data-initiative/skills-utils/blob/4cf9b7c2938984f34bbcc33d45482d23c52c7539/skills_utils/s3.py#L24-L41
train
47,028
workforce-data-initiative/skills-utils
skills_utils/s3.py
upload_dict
def upload_dict(s3_conn, s3_prefix, data_to_sync): """Syncs a dictionary to an S3 bucket, serializing each value in the dictionary as a JSON file with the key as its name. Args: s3_conn: (boto.s3.connection) an s3 connection s3_prefix: (str) the destination prefix data_to_sync: (dict) """ bucket_name, prefix = split_s3_path(s3_prefix) bucket = s3_conn.get_bucket(bucket_name) for key, value in data_to_sync.items(): full_name = '{}/{}.json'.format(prefix, key) s3_key = boto.s3.key.Key( bucket=bucket, name=full_name ) logging.info('uploading key %s', full_name) s3_key.set_contents_from_string(json.dumps(value))
python
def upload_dict(s3_conn, s3_prefix, data_to_sync): """Syncs a dictionary to an S3 bucket, serializing each value in the dictionary as a JSON file with the key as its name. Args: s3_conn: (boto.s3.connection) an s3 connection s3_prefix: (str) the destination prefix data_to_sync: (dict) """ bucket_name, prefix = split_s3_path(s3_prefix) bucket = s3_conn.get_bucket(bucket_name) for key, value in data_to_sync.items(): full_name = '{}/{}.json'.format(prefix, key) s3_key = boto.s3.key.Key( bucket=bucket, name=full_name ) logging.info('uploading key %s', full_name) s3_key.set_contents_from_string(json.dumps(value))
[ "def", "upload_dict", "(", "s3_conn", ",", "s3_prefix", ",", "data_to_sync", ")", ":", "bucket_name", ",", "prefix", "=", "split_s3_path", "(", "s3_prefix", ")", "bucket", "=", "s3_conn", ".", "get_bucket", "(", "bucket_name", ")", "for", "key", ",", "value"...
Syncs a dictionary to an S3 bucket, serializing each value in the dictionary as a JSON file with the key as its name. Args: s3_conn: (boto.s3.connection) an s3 connection s3_prefix: (str) the destination prefix data_to_sync: (dict)
[ "Syncs", "a", "dictionary", "to", "an", "S3", "bucket", "serializing", "each", "value", "in", "the", "dictionary", "as", "a", "JSON", "file", "with", "the", "key", "as", "its", "name", "." ]
4cf9b7c2938984f34bbcc33d45482d23c52c7539
https://github.com/workforce-data-initiative/skills-utils/blob/4cf9b7c2938984f34bbcc33d45482d23c52c7539/skills_utils/s3.py#L44-L63
train
47,029
workforce-data-initiative/skills-utils
skills_utils/s3.py
download
def download(s3_conn, out_filename, s3_path): """Downloads the given s3_path Args: s3_conn (boto.s3.connection) a boto s3 connection out_filename (str) local filename to save the file s3_path (str) the source path on s3 """ bucket_name, prefix = split_s3_path(s3_path) bucket = s3_conn.get_bucket(bucket_name) key = boto.s3.key.Key( bucket=bucket, name=prefix ) logging.info('loading from %s into %s', key, out_filename) key.get_contents_to_filename(out_filename, cb=log_download_progress)
python
def download(s3_conn, out_filename, s3_path): """Downloads the given s3_path Args: s3_conn (boto.s3.connection) a boto s3 connection out_filename (str) local filename to save the file s3_path (str) the source path on s3 """ bucket_name, prefix = split_s3_path(s3_path) bucket = s3_conn.get_bucket(bucket_name) key = boto.s3.key.Key( bucket=bucket, name=prefix ) logging.info('loading from %s into %s', key, out_filename) key.get_contents_to_filename(out_filename, cb=log_download_progress)
[ "def", "download", "(", "s3_conn", ",", "out_filename", ",", "s3_path", ")", ":", "bucket_name", ",", "prefix", "=", "split_s3_path", "(", "s3_path", ")", "bucket", "=", "s3_conn", ".", "get_bucket", "(", "bucket_name", ")", "key", "=", "boto", ".", "s3", ...
Downloads the given s3_path Args: s3_conn (boto.s3.connection) a boto s3 connection out_filename (str) local filename to save the file s3_path (str) the source path on s3
[ "Downloads", "the", "given", "s3_path" ]
4cf9b7c2938984f34bbcc33d45482d23c52c7539
https://github.com/workforce-data-initiative/skills-utils/blob/4cf9b7c2938984f34bbcc33d45482d23c52c7539/skills_utils/s3.py#L66-L81
train
47,030
bachya/regenmaschine
regenmaschine/controller.py
Controller._request
async def _request( self, method: str, endpoint: str, *, headers: dict = None, params: dict = None, json: dict = None, ssl: bool = True) -> dict: """Wrap the generic request method to add access token, etc.""" return await self._client_request( method, '{0}/{1}'.format(self._host, endpoint), access_token=self._access_token, access_token_expiration=self._access_token_expiration, headers=headers, params=params, json=json, ssl=ssl)
python
async def _request( self, method: str, endpoint: str, *, headers: dict = None, params: dict = None, json: dict = None, ssl: bool = True) -> dict: """Wrap the generic request method to add access token, etc.""" return await self._client_request( method, '{0}/{1}'.format(self._host, endpoint), access_token=self._access_token, access_token_expiration=self._access_token_expiration, headers=headers, params=params, json=json, ssl=ssl)
[ "async", "def", "_request", "(", "self", ",", "method", ":", "str", ",", "endpoint", ":", "str", ",", "*", ",", "headers", ":", "dict", "=", "None", ",", "params", ":", "dict", "=", "None", ",", "json", ":", "dict", "=", "None", ",", "ssl", ":", ...
Wrap the generic request method to add access token, etc.
[ "Wrap", "the", "generic", "request", "method", "to", "add", "access", "token", "etc", "." ]
99afb648fe454dc4a7d5db85a02a8b3b5d26f8bc
https://github.com/bachya/regenmaschine/blob/99afb648fe454dc4a7d5db85a02a8b3b5d26f8bc/regenmaschine/controller.py#L52-L70
train
47,031
bachya/regenmaschine
regenmaschine/zone.py
Zone.get
async def get(self, zone_id: int, *, details: bool = False) -> dict: """Return a specific zone.""" endpoint = 'zone/{0}'.format(zone_id) if details: endpoint += '/properties' return await self._request('get', endpoint)
python
async def get(self, zone_id: int, *, details: bool = False) -> dict: """Return a specific zone.""" endpoint = 'zone/{0}'.format(zone_id) if details: endpoint += '/properties' return await self._request('get', endpoint)
[ "async", "def", "get", "(", "self", ",", "zone_id", ":", "int", ",", "*", ",", "details", ":", "bool", "=", "False", ")", "->", "dict", ":", "endpoint", "=", "'zone/{0}'", ".", "format", "(", "zone_id", ")", "if", "details", ":", "endpoint", "+=", ...
Return a specific zone.
[ "Return", "a", "specific", "zone", "." ]
99afb648fe454dc4a7d5db85a02a8b3b5d26f8bc
https://github.com/bachya/regenmaschine/blob/99afb648fe454dc4a7d5db85a02a8b3b5d26f8bc/regenmaschine/zone.py#L35-L40
train
47,032
bachya/regenmaschine
regenmaschine/zone.py
Zone.start
async def start(self, zone_id: int, time: int) -> dict: """Start a program.""" return await self._request( 'post', 'zone/{0}/start'.format(zone_id), json={'time': time})
python
async def start(self, zone_id: int, time: int) -> dict: """Start a program.""" return await self._request( 'post', 'zone/{0}/start'.format(zone_id), json={'time': time})
[ "async", "def", "start", "(", "self", ",", "zone_id", ":", "int", ",", "time", ":", "int", ")", "->", "dict", ":", "return", "await", "self", ".", "_request", "(", "'post'", ",", "'zone/{0}/start'", ".", "format", "(", "zone_id", ")", ",", "json", "=...
Start a program.
[ "Start", "a", "program", "." ]
99afb648fe454dc4a7d5db85a02a8b3b5d26f8bc
https://github.com/bachya/regenmaschine/blob/99afb648fe454dc4a7d5db85a02a8b3b5d26f8bc/regenmaschine/zone.py#L42-L45
train
47,033
DanielSank/observed
observed.py
ObservableFunction.add_observer
def add_observer(self, observer, identify_observed=False): """Register an observer to observe me. Args: observer: The callable to register as an observer. identify_observed: If True, then the observer will get myself passed as an additional first argument whenever it is invoked. See ObserverFunction and ObserverBoundMethod to see how this works. Returns: True if the observer was added, False otherwise. The observing function or method will be called whenever I am called, and with the same arguments and keyword arguments. If a bound method or function has already been registered as an observer, trying to add it again does nothing. In other words, there is no way to sign up an observer to be called back multiple times. This was a conscious design choice which users are invited to complain about if there is a compelling use case where this is inconvenient. """ # If the observer is a bound method, if hasattr(observer, "__self__"): result = self._add_bound_method(observer, identify_observed) # Otherwise, assume observer is a normal function. else: result = self._add_function(observer, identify_observed) return result
python
def add_observer(self, observer, identify_observed=False): """Register an observer to observe me. Args: observer: The callable to register as an observer. identify_observed: If True, then the observer will get myself passed as an additional first argument whenever it is invoked. See ObserverFunction and ObserverBoundMethod to see how this works. Returns: True if the observer was added, False otherwise. The observing function or method will be called whenever I am called, and with the same arguments and keyword arguments. If a bound method or function has already been registered as an observer, trying to add it again does nothing. In other words, there is no way to sign up an observer to be called back multiple times. This was a conscious design choice which users are invited to complain about if there is a compelling use case where this is inconvenient. """ # If the observer is a bound method, if hasattr(observer, "__self__"): result = self._add_bound_method(observer, identify_observed) # Otherwise, assume observer is a normal function. else: result = self._add_function(observer, identify_observed) return result
[ "def", "add_observer", "(", "self", ",", "observer", ",", "identify_observed", "=", "False", ")", ":", "# If the observer is a bound method,", "if", "hasattr", "(", "observer", ",", "\"__self__\"", ")", ":", "result", "=", "self", ".", "_add_bound_method", "(", ...
Register an observer to observe me. Args: observer: The callable to register as an observer. identify_observed: If True, then the observer will get myself passed as an additional first argument whenever it is invoked. See ObserverFunction and ObserverBoundMethod to see how this works. Returns: True if the observer was added, False otherwise. The observing function or method will be called whenever I am called, and with the same arguments and keyword arguments. If a bound method or function has already been registered as an observer, trying to add it again does nothing. In other words, there is no way to sign up an observer to be called back multiple times. This was a conscious design choice which users are invited to complain about if there is a compelling use case where this is inconvenient.
[ "Register", "an", "observer", "to", "observe", "me", "." ]
00b624b90dcff84891d4b5838899f466d884c52e
https://github.com/DanielSank/observed/blob/00b624b90dcff84891d4b5838899f466d884c52e/observed.py#L216-L245
train
47,034
DanielSank/observed
observed.py
ObservableFunction._add_function
def _add_function(self, func, identify_observed): """Add a function as an observer. Args: func: The function to register as an observer. identify_observed: See docstring for add_observer. Returns: True if the function is added, otherwise False. """ key = self.make_key(func) if key not in self.observers: self.observers[key] = ObserverFunction( func, identify_observed, (key, self.observers)) return True else: return False
python
def _add_function(self, func, identify_observed): """Add a function as an observer. Args: func: The function to register as an observer. identify_observed: See docstring for add_observer. Returns: True if the function is added, otherwise False. """ key = self.make_key(func) if key not in self.observers: self.observers[key] = ObserverFunction( func, identify_observed, (key, self.observers)) return True else: return False
[ "def", "_add_function", "(", "self", ",", "func", ",", "identify_observed", ")", ":", "key", "=", "self", ".", "make_key", "(", "func", ")", "if", "key", "not", "in", "self", ".", "observers", ":", "self", ".", "observers", "[", "key", "]", "=", "Obs...
Add a function as an observer. Args: func: The function to register as an observer. identify_observed: See docstring for add_observer. Returns: True if the function is added, otherwise False.
[ "Add", "a", "function", "as", "an", "observer", "." ]
00b624b90dcff84891d4b5838899f466d884c52e
https://github.com/DanielSank/observed/blob/00b624b90dcff84891d4b5838899f466d884c52e/observed.py#L247-L264
train
47,035
DanielSank/observed
observed.py
ObservableFunction._add_bound_method
def _add_bound_method(self, bound_method, identify_observed): """Add an bound method as an observer. Args: bound_method: The bound method to add as an observer. identify_observed: See the docstring for add_observer. Returns: True if the bound method is added, otherwise False. """ inst = bound_method.__self__ method_name = bound_method.__name__ key = self.make_key(bound_method) if key not in self.observers: self.observers[key] = ObserverBoundMethod( inst, method_name, identify_observed, (key, self.observers)) return True else: return False
python
def _add_bound_method(self, bound_method, identify_observed): """Add an bound method as an observer. Args: bound_method: The bound method to add as an observer. identify_observed: See the docstring for add_observer. Returns: True if the bound method is added, otherwise False. """ inst = bound_method.__self__ method_name = bound_method.__name__ key = self.make_key(bound_method) if key not in self.observers: self.observers[key] = ObserverBoundMethod( inst, method_name, identify_observed, (key, self.observers)) return True else: return False
[ "def", "_add_bound_method", "(", "self", ",", "bound_method", ",", "identify_observed", ")", ":", "inst", "=", "bound_method", ".", "__self__", "method_name", "=", "bound_method", ".", "__name__", "key", "=", "self", ".", "make_key", "(", "bound_method", ")", ...
Add an bound method as an observer. Args: bound_method: The bound method to add as an observer. identify_observed: See the docstring for add_observer. Returns: True if the bound method is added, otherwise False.
[ "Add", "an", "bound", "method", "as", "an", "observer", "." ]
00b624b90dcff84891d4b5838899f466d884c52e
https://github.com/DanielSank/observed/blob/00b624b90dcff84891d4b5838899f466d884c52e/observed.py#L266-L285
train
47,036
DanielSank/observed
observed.py
ObservableFunction.discard_observer
def discard_observer(self, observer): """Un-register an observer. Args: observer: The observer to un-register. Returns true if an observer was removed, otherwise False. """ discarded = False key = self.make_key(observer) if key in self.observers: del self.observers[key] discarded = True return discarded
python
def discard_observer(self, observer): """Un-register an observer. Args: observer: The observer to un-register. Returns true if an observer was removed, otherwise False. """ discarded = False key = self.make_key(observer) if key in self.observers: del self.observers[key] discarded = True return discarded
[ "def", "discard_observer", "(", "self", ",", "observer", ")", ":", "discarded", "=", "False", "key", "=", "self", ".", "make_key", "(", "observer", ")", "if", "key", "in", "self", ".", "observers", ":", "del", "self", ".", "observers", "[", "key", "]",...
Un-register an observer. Args: observer: The observer to un-register. Returns true if an observer was removed, otherwise False.
[ "Un", "-", "register", "an", "observer", "." ]
00b624b90dcff84891d4b5838899f466d884c52e
https://github.com/DanielSank/observed/blob/00b624b90dcff84891d4b5838899f466d884c52e/observed.py#L287-L300
train
47,037
DanielSank/observed
observed.py
ObservableFunction.make_key
def make_key(observer): """Construct a unique, hashable, immutable key for an observer.""" if hasattr(observer, "__self__"): inst = observer.__self__ method_name = observer.__name__ key = (id(inst), method_name) else: key = id(observer) return key
python
def make_key(observer): """Construct a unique, hashable, immutable key for an observer.""" if hasattr(observer, "__self__"): inst = observer.__self__ method_name = observer.__name__ key = (id(inst), method_name) else: key = id(observer) return key
[ "def", "make_key", "(", "observer", ")", ":", "if", "hasattr", "(", "observer", ",", "\"__self__\"", ")", ":", "inst", "=", "observer", ".", "__self__", "method_name", "=", "observer", ".", "__name__", "key", "=", "(", "id", "(", "inst", ")", ",", "met...
Construct a unique, hashable, immutable key for an observer.
[ "Construct", "a", "unique", "hashable", "immutable", "key", "for", "an", "observer", "." ]
00b624b90dcff84891d4b5838899f466d884c52e
https://github.com/DanielSank/observed/blob/00b624b90dcff84891d4b5838899f466d884c52e/observed.py#L303-L312
train
47,038
Infinidat/infi.docopt_completion
src/infi/docopt_completion/common.py
build_command_tree
def build_command_tree(pattern, cmd_params): """ Recursively fill in a command tree in cmd_params according to a docopt-parsed "pattern" object. """ from docopt import Either, Optional, OneOrMore, Required, Option, Command, Argument if type(pattern) in [Either, Optional, OneOrMore]: for child in pattern.children: build_command_tree(child, cmd_params) elif type(pattern) in [Required]: for child in pattern.children: cmd_params = build_command_tree(child, cmd_params) elif type(pattern) in [Option]: suffix = "=" if pattern.argcount else "" if pattern.short: cmd_params.options.append(pattern.short + suffix) if pattern.long: cmd_params.options.append(pattern.long + suffix) elif type(pattern) in [Command]: cmd_params = cmd_params.get_subcommand(pattern.name) elif type(pattern) in [Argument]: cmd_params.arguments.append(pattern.name) return cmd_params
python
def build_command_tree(pattern, cmd_params): """ Recursively fill in a command tree in cmd_params according to a docopt-parsed "pattern" object. """ from docopt import Either, Optional, OneOrMore, Required, Option, Command, Argument if type(pattern) in [Either, Optional, OneOrMore]: for child in pattern.children: build_command_tree(child, cmd_params) elif type(pattern) in [Required]: for child in pattern.children: cmd_params = build_command_tree(child, cmd_params) elif type(pattern) in [Option]: suffix = "=" if pattern.argcount else "" if pattern.short: cmd_params.options.append(pattern.short + suffix) if pattern.long: cmd_params.options.append(pattern.long + suffix) elif type(pattern) in [Command]: cmd_params = cmd_params.get_subcommand(pattern.name) elif type(pattern) in [Argument]: cmd_params.arguments.append(pattern.name) return cmd_params
[ "def", "build_command_tree", "(", "pattern", ",", "cmd_params", ")", ":", "from", "docopt", "import", "Either", ",", "Optional", ",", "OneOrMore", ",", "Required", ",", "Option", ",", "Command", ",", "Argument", "if", "type", "(", "pattern", ")", "in", "["...
Recursively fill in a command tree in cmd_params according to a docopt-parsed "pattern" object.
[ "Recursively", "fill", "in", "a", "command", "tree", "in", "cmd_params", "according", "to", "a", "docopt", "-", "parsed", "pattern", "object", "." ]
9e53bc360b903e0a3910adcc379f26e319fef4a4
https://github.com/Infinidat/infi.docopt_completion/blob/9e53bc360b903e0a3910adcc379f26e319fef4a4/src/infi/docopt_completion/common.py#L12-L33
train
47,039
workforce-data-initiative/skills-utils
skills_utils/iteration.py
Batch.group
def group(self): """Yield a group from the iterable""" yield self.current # start enumerate at 1 because we already yielded the last saved item for num, item in enumerate(self.iterator, 1): self.current = item if num == self.limit: break yield item else: self.on_going = False
python
def group(self): """Yield a group from the iterable""" yield self.current # start enumerate at 1 because we already yielded the last saved item for num, item in enumerate(self.iterator, 1): self.current = item if num == self.limit: break yield item else: self.on_going = False
[ "def", "group", "(", "self", ")", ":", "yield", "self", ".", "current", "# start enumerate at 1 because we already yielded the last saved item", "for", "num", ",", "item", "in", "enumerate", "(", "self", ".", "iterator", ",", "1", ")", ":", "self", ".", "current...
Yield a group from the iterable
[ "Yield", "a", "group", "from", "the", "iterable" ]
4cf9b7c2938984f34bbcc33d45482d23c52c7539
https://github.com/workforce-data-initiative/skills-utils/blob/4cf9b7c2938984f34bbcc33d45482d23c52c7539/skills_utils/iteration.py#L23-L33
train
47,040
bachya/regenmaschine
regenmaschine/watering.py
Watering.log
async def log( self, date: datetime.date = None, days: int = None, details: bool = False) -> list: """Get watering information for X days from Y date.""" endpoint = 'watering/log' if details: endpoint += '/details' if date and days: endpoint = '{0}/{1}/{2}'.format( endpoint, date.strftime('%Y-%m-%d'), days) data = await self._request('get', endpoint) return data['waterLog']['days']
python
async def log( self, date: datetime.date = None, days: int = None, details: bool = False) -> list: """Get watering information for X days from Y date.""" endpoint = 'watering/log' if details: endpoint += '/details' if date and days: endpoint = '{0}/{1}/{2}'.format( endpoint, date.strftime('%Y-%m-%d'), days) data = await self._request('get', endpoint) return data['waterLog']['days']
[ "async", "def", "log", "(", "self", ",", "date", ":", "datetime", ".", "date", "=", "None", ",", "days", ":", "int", "=", "None", ",", "details", ":", "bool", "=", "False", ")", "->", "list", ":", "endpoint", "=", "'watering/log'", "if", "details", ...
Get watering information for X days from Y date.
[ "Get", "watering", "information", "for", "X", "days", "from", "Y", "date", "." ]
99afb648fe454dc4a7d5db85a02a8b3b5d26f8bc
https://github.com/bachya/regenmaschine/blob/99afb648fe454dc4a7d5db85a02a8b3b5d26f8bc/regenmaschine/watering.py#L13-L28
train
47,041
bachya/regenmaschine
regenmaschine/watering.py
Watering.runs
async def runs(self, date: datetime.date = None, days: int = None) -> list: """Return all program runs for X days from Y date.""" endpoint = 'watering/past' if date and days: endpoint = '{0}/{1}/{2}'.format( endpoint, date.strftime('%Y-%m-%d'), days) data = await self._request('get', endpoint) return data['pastValues']
python
async def runs(self, date: datetime.date = None, days: int = None) -> list: """Return all program runs for X days from Y date.""" endpoint = 'watering/past' if date and days: endpoint = '{0}/{1}/{2}'.format( endpoint, date.strftime('%Y-%m-%d'), days) data = await self._request('get', endpoint) return data['pastValues']
[ "async", "def", "runs", "(", "self", ",", "date", ":", "datetime", ".", "date", "=", "None", ",", "days", ":", "int", "=", "None", ")", "->", "list", ":", "endpoint", "=", "'watering/past'", "if", "date", "and", "days", ":", "endpoint", "=", "'{0}/{1...
Return all program runs for X days from Y date.
[ "Return", "all", "program", "runs", "for", "X", "days", "from", "Y", "date", "." ]
99afb648fe454dc4a7d5db85a02a8b3b5d26f8bc
https://github.com/bachya/regenmaschine/blob/99afb648fe454dc4a7d5db85a02a8b3b5d26f8bc/regenmaschine/watering.py#L40-L49
train
47,042
bachya/regenmaschine
regenmaschine/program.py
Program.all
async def all(self, include_inactive: bool = False) -> list: """Return all programs.""" data = await self._request('get', 'program') return [p for p in data['programs'] if include_inactive or p['active']]
python
async def all(self, include_inactive: bool = False) -> list: """Return all programs.""" data = await self._request('get', 'program') return [p for p in data['programs'] if include_inactive or p['active']]
[ "async", "def", "all", "(", "self", ",", "include_inactive", ":", "bool", "=", "False", ")", "->", "list", ":", "data", "=", "await", "self", ".", "_request", "(", "'get'", ",", "'program'", ")", "return", "[", "p", "for", "p", "in", "data", "[", "...
Return all programs.
[ "Return", "all", "programs", "." ]
99afb648fe454dc4a7d5db85a02a8b3b5d26f8bc
https://github.com/bachya/regenmaschine/blob/99afb648fe454dc4a7d5db85a02a8b3b5d26f8bc/regenmaschine/program.py#L17-L20
train
47,043
workforce-data-initiative/skills-utils
skills_utils/fs.py
cache_json
def cache_json(filename): """Caches the JSON-serializable output of the function to a given file Args: filename (str) The filename (sans directory) to store the output Returns: decorator, applicable to a function that produces JSON-serializable output """ def cache_decorator(cacheable_function): @wraps(cacheable_function) def cache_wrapper(*args, **kwargs): path = CACHE_DIRECTORY + filename check_create_folder(path) if os.path.exists(path): with open(path) as infile: return json.load(infile) else: function_output = cacheable_function(*args, **kwargs) with open(path, 'w') as outfile: json.dump(function_output, outfile) return function_output return cache_wrapper return cache_decorator
python
def cache_json(filename): """Caches the JSON-serializable output of the function to a given file Args: filename (str) The filename (sans directory) to store the output Returns: decorator, applicable to a function that produces JSON-serializable output """ def cache_decorator(cacheable_function): @wraps(cacheable_function) def cache_wrapper(*args, **kwargs): path = CACHE_DIRECTORY + filename check_create_folder(path) if os.path.exists(path): with open(path) as infile: return json.load(infile) else: function_output = cacheable_function(*args, **kwargs) with open(path, 'w') as outfile: json.dump(function_output, outfile) return function_output return cache_wrapper return cache_decorator
[ "def", "cache_json", "(", "filename", ")", ":", "def", "cache_decorator", "(", "cacheable_function", ")", ":", "@", "wraps", "(", "cacheable_function", ")", "def", "cache_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "path", "=", "CACHE_DI...
Caches the JSON-serializable output of the function to a given file Args: filename (str) The filename (sans directory) to store the output Returns: decorator, applicable to a function that produces JSON-serializable output
[ "Caches", "the", "JSON", "-", "serializable", "output", "of", "the", "function", "to", "a", "given", "file" ]
4cf9b7c2938984f34bbcc33d45482d23c52c7539
https://github.com/workforce-data-initiative/skills-utils/blob/4cf9b7c2938984f34bbcc33d45482d23c52c7539/skills_utils/fs.py#L10-L32
train
47,044
workforce-data-initiative/skills-utils
skills_utils/fs.py
check_create_folder
def check_create_folder(filename): """Check if the folder exisits. If not, create the folder""" os.makedirs(os.path.dirname(filename), exist_ok=True)
python
def check_create_folder(filename): """Check if the folder exisits. If not, create the folder""" os.makedirs(os.path.dirname(filename), exist_ok=True)
[ "def", "check_create_folder", "(", "filename", ")", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "filename", ")", ",", "exist_ok", "=", "True", ")" ]
Check if the folder exisits. If not, create the folder
[ "Check", "if", "the", "folder", "exisits", ".", "If", "not", "create", "the", "folder" ]
4cf9b7c2938984f34bbcc33d45482d23c52c7539
https://github.com/workforce-data-initiative/skills-utils/blob/4cf9b7c2938984f34bbcc33d45482d23c52c7539/skills_utils/fs.py#L35-L37
train
47,045
workforce-data-initiative/skills-utils
skills_utils/job_posting_import.py
JobPostingImportBase.postings
def postings(self, quarter, stats_counter=None): """Yield job postings in common schema format Args: quarter (str) The quarter, in format '2015Q1' stats_counter (object, optional) A counter that can track both input and output documents using a 'track' method. """ logging.info('Finding postings for %s', quarter) for posting in self._iter_postings(quarter): transformed = self._transform(posting) transformed['id'] = '{}_{}'.format( self.partner_id, self._id(posting) ) if stats_counter: stats_counter.track( input_document=posting, output_document=transformed ) yield transformed
python
def postings(self, quarter, stats_counter=None): """Yield job postings in common schema format Args: quarter (str) The quarter, in format '2015Q1' stats_counter (object, optional) A counter that can track both input and output documents using a 'track' method. """ logging.info('Finding postings for %s', quarter) for posting in self._iter_postings(quarter): transformed = self._transform(posting) transformed['id'] = '{}_{}'.format( self.partner_id, self._id(posting) ) if stats_counter: stats_counter.track( input_document=posting, output_document=transformed ) yield transformed
[ "def", "postings", "(", "self", ",", "quarter", ",", "stats_counter", "=", "None", ")", ":", "logging", ".", "info", "(", "'Finding postings for %s'", ",", "quarter", ")", "for", "posting", "in", "self", ".", "_iter_postings", "(", "quarter", ")", ":", "tr...
Yield job postings in common schema format Args: quarter (str) The quarter, in format '2015Q1' stats_counter (object, optional) A counter that can track both input and output documents using a 'track' method.
[ "Yield", "job", "postings", "in", "common", "schema", "format" ]
4cf9b7c2938984f34bbcc33d45482d23c52c7539
https://github.com/workforce-data-initiative/skills-utils/blob/4cf9b7c2938984f34bbcc33d45482d23c52c7539/skills_utils/job_posting_import.py#L21-L41
train
47,046
mgrijalva/nose2-html-report
nose2_html_report/html_report.py
HTMLReporter.afterSummaryReport
def afterSummaryReport(self, event): """ After everything is done, generate the report """ logger.info('Generating HTML report...') sorted_test_results = self._sort_test_results() context = { 'test_report_title': 'Test Report', 'test_summary': self.summary_stats, 'test_results': sorted_test_results, 'autocomplete_terms': json.dumps(self._generate_search_terms()), 'timestamp': datetime.utcnow().strftime('%Y/%m/%d %H:%M:%S UTC') } template = load_template(self._config['template']) rendered_template = render_template(template, context) with open(self._config['report_path'], 'w') as template_file: template_file.write(rendered_template)
python
def afterSummaryReport(self, event): """ After everything is done, generate the report """ logger.info('Generating HTML report...') sorted_test_results = self._sort_test_results() context = { 'test_report_title': 'Test Report', 'test_summary': self.summary_stats, 'test_results': sorted_test_results, 'autocomplete_terms': json.dumps(self._generate_search_terms()), 'timestamp': datetime.utcnow().strftime('%Y/%m/%d %H:%M:%S UTC') } template = load_template(self._config['template']) rendered_template = render_template(template, context) with open(self._config['report_path'], 'w') as template_file: template_file.write(rendered_template)
[ "def", "afterSummaryReport", "(", "self", ",", "event", ")", ":", "logger", ".", "info", "(", "'Generating HTML report...'", ")", "sorted_test_results", "=", "self", ".", "_sort_test_results", "(", ")", "context", "=", "{", "'test_report_title'", ":", "'Test Repor...
After everything is done, generate the report
[ "After", "everything", "is", "done", "generate", "the", "report" ]
e8c89bedec5d5fe085b65d399cf1fe6647a3c179
https://github.com/mgrijalva/nose2-html-report/blob/e8c89bedec5d5fe085b65d399cf1fe6647a3c179/nose2_html_report/html_report.py#L97-L115
train
47,047
workforce-data-initiative/skills-utils
skills_utils/time.py
dates_in_range
def dates_in_range(start_date, end_date): """Returns all dates between two dates. Inclusive of the start date but not the end date. Args: start_date (datetime.date) end_date (datetime.date) Returns: (list) of datetime.date objects """ return [ start_date + timedelta(n) for n in range(int((end_date - start_date).days)) ]
python
def dates_in_range(start_date, end_date): """Returns all dates between two dates. Inclusive of the start date but not the end date. Args: start_date (datetime.date) end_date (datetime.date) Returns: (list) of datetime.date objects """ return [ start_date + timedelta(n) for n in range(int((end_date - start_date).days)) ]
[ "def", "dates_in_range", "(", "start_date", ",", "end_date", ")", ":", "return", "[", "start_date", "+", "timedelta", "(", "n", ")", "for", "n", "in", "range", "(", "int", "(", "(", "end_date", "-", "start_date", ")", ".", "days", ")", ")", "]" ]
Returns all dates between two dates. Inclusive of the start date but not the end date. Args: start_date (datetime.date) end_date (datetime.date) Returns: (list) of datetime.date objects
[ "Returns", "all", "dates", "between", "two", "dates", "." ]
4cf9b7c2938984f34bbcc33d45482d23c52c7539
https://github.com/workforce-data-initiative/skills-utils/blob/4cf9b7c2938984f34bbcc33d45482d23c52c7539/skills_utils/time.py#L53-L68
train
47,048
ColinDuquesnoy/pyqt_distutils
pyqt_distutils/hooks.py
load_hooks
def load_hooks(): """ Load the exposed hooks. Returns a dict of hooks where the keys are the name of the hook and the values are the actual hook functions. """ hooks = {} for entrypoint in pkg_resources.iter_entry_points(ENTRYPOINT): name = str(entrypoint).split('=')[0].strip() try: hook = entrypoint.load() except Exception as e: write_message('failed to load entry-point %r (error="%s")' % (name, e), 'yellow') else: hooks[name] = hook return hooks
python
def load_hooks(): """ Load the exposed hooks. Returns a dict of hooks where the keys are the name of the hook and the values are the actual hook functions. """ hooks = {} for entrypoint in pkg_resources.iter_entry_points(ENTRYPOINT): name = str(entrypoint).split('=')[0].strip() try: hook = entrypoint.load() except Exception as e: write_message('failed to load entry-point %r (error="%s")' % (name, e), 'yellow') else: hooks[name] = hook return hooks
[ "def", "load_hooks", "(", ")", ":", "hooks", "=", "{", "}", "for", "entrypoint", "in", "pkg_resources", ".", "iter_entry_points", "(", "ENTRYPOINT", ")", ":", "name", "=", "str", "(", "entrypoint", ")", ".", "split", "(", "'='", ")", "[", "0", "]", "...
Load the exposed hooks. Returns a dict of hooks where the keys are the name of the hook and the values are the actual hook functions.
[ "Load", "the", "exposed", "hooks", "." ]
7387d64ea2db3b1dafb09d006266cec580131f7d
https://github.com/ColinDuquesnoy/pyqt_distutils/blob/7387d64ea2db3b1dafb09d006266cec580131f7d/pyqt_distutils/hooks.py#L15-L31
train
47,049
ColinDuquesnoy/pyqt_distutils
pyqt_distutils/hooks.py
gettext
def gettext(ui_file_path): """ Let you use gettext instead of the Qt tools for l18n """ with open(ui_file_path, 'r') as fin: content = fin.read() # replace ``_translate("context", `` by ``_(`` content = re.sub(r'_translate\(".*",\s', '_(', content) content = content.replace( ' _translate = QtCore.QCoreApplication.translate', '') with open(ui_file_path, 'w') as fout: fout.write(content)
python
def gettext(ui_file_path): """ Let you use gettext instead of the Qt tools for l18n """ with open(ui_file_path, 'r') as fin: content = fin.read() # replace ``_translate("context", `` by ``_(`` content = re.sub(r'_translate\(".*",\s', '_(', content) content = content.replace( ' _translate = QtCore.QCoreApplication.translate', '') with open(ui_file_path, 'w') as fout: fout.write(content)
[ "def", "gettext", "(", "ui_file_path", ")", ":", "with", "open", "(", "ui_file_path", ",", "'r'", ")", "as", "fin", ":", "content", "=", "fin", ".", "read", "(", ")", "# replace ``_translate(\"context\", `` by ``_(``", "content", "=", "re", ".", "sub", "(", ...
Let you use gettext instead of the Qt tools for l18n
[ "Let", "you", "use", "gettext", "instead", "of", "the", "Qt", "tools", "for", "l18n" ]
7387d64ea2db3b1dafb09d006266cec580131f7d
https://github.com/ColinDuquesnoy/pyqt_distutils/blob/7387d64ea2db3b1dafb09d006266cec580131f7d/pyqt_distutils/hooks.py#L41-L54
train
47,050
workforce-data-initiative/skills-utils
skills_utils/es.py
basic_client
def basic_client(): """Returns an Elasticsearch basic client that is responsive to the environment variable ELASTICSEARCH_ENDPOINT""" es_connected = False while not es_connected: try: ES = Elasticsearch( hosts=[HOSTNAME] ) es_connected = True except TransportError as e: logging.info('Not yet connected: %s, sleeping for 1s', e) time.sleep(1) return ES
python
def basic_client(): """Returns an Elasticsearch basic client that is responsive to the environment variable ELASTICSEARCH_ENDPOINT""" es_connected = False while not es_connected: try: ES = Elasticsearch( hosts=[HOSTNAME] ) es_connected = True except TransportError as e: logging.info('Not yet connected: %s, sleeping for 1s', e) time.sleep(1) return ES
[ "def", "basic_client", "(", ")", ":", "es_connected", "=", "False", "while", "not", "es_connected", ":", "try", ":", "ES", "=", "Elasticsearch", "(", "hosts", "=", "[", "HOSTNAME", "]", ")", "es_connected", "=", "True", "except", "TransportError", "as", "e...
Returns an Elasticsearch basic client that is responsive to the environment variable ELASTICSEARCH_ENDPOINT
[ "Returns", "an", "Elasticsearch", "basic", "client", "that", "is", "responsive", "to", "the", "environment", "variable", "ELASTICSEARCH_ENDPOINT" ]
4cf9b7c2938984f34bbcc33d45482d23c52c7539
https://github.com/workforce-data-initiative/skills-utils/blob/4cf9b7c2938984f34bbcc33d45482d23c52c7539/skills_utils/es.py#L16-L29
train
47,051
workforce-data-initiative/skills-utils
skills_utils/es.py
create_index
def create_index(index_name, index_config, client): """Creates an index with a given configuration Args: index_name (str): Name of the index you want to create index_config (dict) configuration for the index client (Elasticsearch.IndicesClient) the Elasticsearch client """ client.create(index=index_name, body=index_config)
python
def create_index(index_name, index_config, client): """Creates an index with a given configuration Args: index_name (str): Name of the index you want to create index_config (dict) configuration for the index client (Elasticsearch.IndicesClient) the Elasticsearch client """ client.create(index=index_name, body=index_config)
[ "def", "create_index", "(", "index_name", ",", "index_config", ",", "client", ")", ":", "client", ".", "create", "(", "index", "=", "index_name", ",", "body", "=", "index_config", ")" ]
Creates an index with a given configuration Args: index_name (str): Name of the index you want to create index_config (dict) configuration for the index client (Elasticsearch.IndicesClient) the Elasticsearch client
[ "Creates", "an", "index", "with", "a", "given", "configuration" ]
4cf9b7c2938984f34bbcc33d45482d23c52c7539
https://github.com/workforce-data-initiative/skills-utils/blob/4cf9b7c2938984f34bbcc33d45482d23c52c7539/skills_utils/es.py#L48-L56
train
47,052
workforce-data-initiative/skills-utils
skills_utils/es.py
get_index_from_alias
def get_index_from_alias(alias_name, index_client=None): """Retrieve the base index name from an alias Args: alias_name (str) Name of the alias index_client (Elasticsearch.IndicesClient) an Elasticsearch index client. Optional, will create one if not given Returns: (str) Name of index """ index_client = index_client or indices_client() if not index_client.exists_alias(name=alias_name): return None return list(index_client.get_alias(name=alias_name).keys())[0]
python
def get_index_from_alias(alias_name, index_client=None): """Retrieve the base index name from an alias Args: alias_name (str) Name of the alias index_client (Elasticsearch.IndicesClient) an Elasticsearch index client. Optional, will create one if not given Returns: (str) Name of index """ index_client = index_client or indices_client() if not index_client.exists_alias(name=alias_name): return None return list(index_client.get_alias(name=alias_name).keys())[0]
[ "def", "get_index_from_alias", "(", "alias_name", ",", "index_client", "=", "None", ")", ":", "index_client", "=", "index_client", "or", "indices_client", "(", ")", "if", "not", "index_client", ".", "exists_alias", "(", "name", "=", "alias_name", ")", ":", "re...
Retrieve the base index name from an alias Args: alias_name (str) Name of the alias index_client (Elasticsearch.IndicesClient) an Elasticsearch index client. Optional, will create one if not given Returns: (str) Name of index
[ "Retrieve", "the", "base", "index", "name", "from", "an", "alias" ]
4cf9b7c2938984f34bbcc33d45482d23c52c7539
https://github.com/workforce-data-initiative/skills-utils/blob/4cf9b7c2938984f34bbcc33d45482d23c52c7539/skills_utils/es.py#L59-L72
train
47,053
workforce-data-initiative/skills-utils
skills_utils/es.py
atomic_swap
def atomic_swap(alias_name, new_index_name, index_client): """Points an alias to a new index, then delete the old index if needed Uses client.update_aliases to perform this with zero downtime Args: alias_name (str) Name of the alias new_index_name (str) The new index that the alias should point to index_client (Elasticsearch.IndicesClient) Elasticsearch index client """ logging.info('Performing atomic index alias swap') if index_client.exists_alias(name=alias_name): old_index_name = get_index_from_alias(alias_name, index_client) logging.info('Removing old as well as adding new') actions = {'actions': [ {'remove': {'index': old_index_name, 'alias': alias_name}}, {'add': {'index': new_index_name, 'alias': alias_name}} ]} index_client.update_aliases(body=actions) index_client.delete(index=old_index_name) else: logging.info('Old alias not found, only adding new') actions = {'actions': [ {'add': {'index': new_index_name, 'alias': alias_name}} ]} index_client.update_aliases(body=actions)
python
def atomic_swap(alias_name, new_index_name, index_client): """Points an alias to a new index, then delete the old index if needed Uses client.update_aliases to perform this with zero downtime Args: alias_name (str) Name of the alias new_index_name (str) The new index that the alias should point to index_client (Elasticsearch.IndicesClient) Elasticsearch index client """ logging.info('Performing atomic index alias swap') if index_client.exists_alias(name=alias_name): old_index_name = get_index_from_alias(alias_name, index_client) logging.info('Removing old as well as adding new') actions = {'actions': [ {'remove': {'index': old_index_name, 'alias': alias_name}}, {'add': {'index': new_index_name, 'alias': alias_name}} ]} index_client.update_aliases(body=actions) index_client.delete(index=old_index_name) else: logging.info('Old alias not found, only adding new') actions = {'actions': [ {'add': {'index': new_index_name, 'alias': alias_name}} ]} index_client.update_aliases(body=actions)
[ "def", "atomic_swap", "(", "alias_name", ",", "new_index_name", ",", "index_client", ")", ":", "logging", ".", "info", "(", "'Performing atomic index alias swap'", ")", "if", "index_client", ".", "exists_alias", "(", "name", "=", "alias_name", ")", ":", "old_index...
Points an alias to a new index, then delete the old index if needed Uses client.update_aliases to perform this with zero downtime Args: alias_name (str) Name of the alias new_index_name (str) The new index that the alias should point to index_client (Elasticsearch.IndicesClient) Elasticsearch index client
[ "Points", "an", "alias", "to", "a", "new", "index", "then", "delete", "the", "old", "index", "if", "needed" ]
4cf9b7c2938984f34bbcc33d45482d23c52c7539
https://github.com/workforce-data-initiative/skills-utils/blob/4cf9b7c2938984f34bbcc33d45482d23c52c7539/skills_utils/es.py#L75-L100
train
47,054
workforce-data-initiative/skills-utils
skills_utils/es.py
zero_downtime_index
def zero_downtime_index(index_name, index_config): """Context manager to create a new index based on a given alias, allow the caller to index it, and then point the alias to the new index Args: index_name (str) Name of an alias that should point to the new index index_config (dict) Configuration for the new index Yields: (name) The full name of the new index """ client = indices_client() temporary_name = index_name + '_' + str(uuid.uuid4()) logging.info('creating index with config %s', index_config) create_index(temporary_name, index_config, client) try: yield temporary_name atomic_swap(index_name, temporary_name, client) except Exception: logging.error( 'deleting temporary index %s due to error:', temporary_name, exc_info=True ) client.delete(index=temporary_name)
python
def zero_downtime_index(index_name, index_config): """Context manager to create a new index based on a given alias, allow the caller to index it, and then point the alias to the new index Args: index_name (str) Name of an alias that should point to the new index index_config (dict) Configuration for the new index Yields: (name) The full name of the new index """ client = indices_client() temporary_name = index_name + '_' + str(uuid.uuid4()) logging.info('creating index with config %s', index_config) create_index(temporary_name, index_config, client) try: yield temporary_name atomic_swap(index_name, temporary_name, client) except Exception: logging.error( 'deleting temporary index %s due to error:', temporary_name, exc_info=True ) client.delete(index=temporary_name)
[ "def", "zero_downtime_index", "(", "index_name", ",", "index_config", ")", ":", "client", "=", "indices_client", "(", ")", "temporary_name", "=", "index_name", "+", "'_'", "+", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "logging", ".", "info", "(", ...
Context manager to create a new index based on a given alias, allow the caller to index it, and then point the alias to the new index Args: index_name (str) Name of an alias that should point to the new index index_config (dict) Configuration for the new index Yields: (name) The full name of the new index
[ "Context", "manager", "to", "create", "a", "new", "index", "based", "on", "a", "given", "alias", "allow", "the", "caller", "to", "index", "it", "and", "then", "point", "the", "alias", "to", "the", "new", "index" ]
4cf9b7c2938984f34bbcc33d45482d23c52c7539
https://github.com/workforce-data-initiative/skills-utils/blob/4cf9b7c2938984f34bbcc33d45482d23c52c7539/skills_utils/es.py#L104-L127
train
47,055
workforce-data-initiative/skills-utils
skills_utils/es.py
ElasticsearchIndexerBase.replace
def replace(self): """Replace index with a new one zero_downtime_index for safety and rollback """ with zero_downtime_index(self.alias_name, self.index_config()) as target_index: self.index_all(target_index)
python
def replace(self): """Replace index with a new one zero_downtime_index for safety and rollback """ with zero_downtime_index(self.alias_name, self.index_config()) as target_index: self.index_all(target_index)
[ "def", "replace", "(", "self", ")", ":", "with", "zero_downtime_index", "(", "self", ".", "alias_name", ",", "self", ".", "index_config", "(", ")", ")", "as", "target_index", ":", "self", ".", "index_all", "(", "target_index", ")" ]
Replace index with a new one zero_downtime_index for safety and rollback
[ "Replace", "index", "with", "a", "new", "one", "zero_downtime_index", "for", "safety", "and", "rollback" ]
4cf9b7c2938984f34bbcc33d45482d23c52c7539
https://github.com/workforce-data-initiative/skills-utils/blob/4cf9b7c2938984f34bbcc33d45482d23c52c7539/skills_utils/es.py#L154-L159
train
47,056
workforce-data-initiative/skills-utils
skills_utils/es.py
ElasticsearchIndexerBase.append
def append(self): """Index documents onto an existing index""" target_index = get_index_from_alias(self.alias_name) if not target_index: self.replace() else: self.index_all(target_index)
python
def append(self): """Index documents onto an existing index""" target_index = get_index_from_alias(self.alias_name) if not target_index: self.replace() else: self.index_all(target_index)
[ "def", "append", "(", "self", ")", ":", "target_index", "=", "get_index_from_alias", "(", "self", ".", "alias_name", ")", "if", "not", "target_index", ":", "self", ".", "replace", "(", ")", "else", ":", "self", ".", "index_all", "(", "target_index", ")" ]
Index documents onto an existing index
[ "Index", "documents", "onto", "an", "existing", "index" ]
4cf9b7c2938984f34bbcc33d45482d23c52c7539
https://github.com/workforce-data-initiative/skills-utils/blob/4cf9b7c2938984f34bbcc33d45482d23c52c7539/skills_utils/es.py#L161-L167
train
47,057
ColinDuquesnoy/pyqt_distutils
pyqt_distutils/utils.py
build_args
def build_args(cmd, src, dst): """ Build arguments list for passing to subprocess.call_check :param cmd str: Command string to interpolate src and dst filepaths into. Typically the output of `config.Config.uic_command` or `config.Config.rcc_command`. :param src str: Source filepath. :param dst str: Destination filepath. """ cmd = cmd % (quote(src), quote(dst)) args = shlex.split(cmd) return [arg for arg in args if arg]
python
def build_args(cmd, src, dst): """ Build arguments list for passing to subprocess.call_check :param cmd str: Command string to interpolate src and dst filepaths into. Typically the output of `config.Config.uic_command` or `config.Config.rcc_command`. :param src str: Source filepath. :param dst str: Destination filepath. """ cmd = cmd % (quote(src), quote(dst)) args = shlex.split(cmd) return [arg for arg in args if arg]
[ "def", "build_args", "(", "cmd", ",", "src", ",", "dst", ")", ":", "cmd", "=", "cmd", "%", "(", "quote", "(", "src", ")", ",", "quote", "(", "dst", ")", ")", "args", "=", "shlex", ".", "split", "(", "cmd", ")", "return", "[", "arg", "for", "a...
Build arguments list for passing to subprocess.call_check :param cmd str: Command string to interpolate src and dst filepaths into. Typically the output of `config.Config.uic_command` or `config.Config.rcc_command`. :param src str: Source filepath. :param dst str: Destination filepath.
[ "Build", "arguments", "list", "for", "passing", "to", "subprocess", ".", "call_check" ]
7387d64ea2db3b1dafb09d006266cec580131f7d
https://github.com/ColinDuquesnoy/pyqt_distutils/blob/7387d64ea2db3b1dafb09d006266cec580131f7d/pyqt_distutils/utils.py#L17-L29
train
47,058
devopshq/crosspm
crosspm/helpers/output.py
Output.output_format_lock
def output_format_lock(self, packages, **kwargs): """ Text to lock file """ self._output_config['type'] = PLAIN text = '' tmp_packages = OrderedDict() columns = self._config.get_columns() widths = {} for _pkg in packages.values(): _pkg_name = _pkg.package_name _params = _pkg.get_params(columns, merged=True, raw=False) if _pkg_name not in tmp_packages: tmp_packages[_pkg_name] = _params comment = 1 for _col in columns: widths[_col] = max(widths.get(_col, len(_col)), len(str(_params.get(_col, '')))) + comment comment = 0 comment = 1 for _col in columns: text += '{}{} '.format(_col, ' ' * (widths[_col] - len(_col) - comment)) comment = 0 text = '#{}\n'.format(text.strip()) for _pkg_name in sorted(tmp_packages, key=lambda x: str(x).lower()): _pkg = tmp_packages[_pkg_name] line = '' for _col in columns: line += '{}{} '.format(_pkg[_col], ' ' * (widths[_col] - len(str(_pkg[_col])))) text += '{}\n'.format(line.strip()) return text
python
def output_format_lock(self, packages, **kwargs): """ Text to lock file """ self._output_config['type'] = PLAIN text = '' tmp_packages = OrderedDict() columns = self._config.get_columns() widths = {} for _pkg in packages.values(): _pkg_name = _pkg.package_name _params = _pkg.get_params(columns, merged=True, raw=False) if _pkg_name not in tmp_packages: tmp_packages[_pkg_name] = _params comment = 1 for _col in columns: widths[_col] = max(widths.get(_col, len(_col)), len(str(_params.get(_col, '')))) + comment comment = 0 comment = 1 for _col in columns: text += '{}{} '.format(_col, ' ' * (widths[_col] - len(_col) - comment)) comment = 0 text = '#{}\n'.format(text.strip()) for _pkg_name in sorted(tmp_packages, key=lambda x: str(x).lower()): _pkg = tmp_packages[_pkg_name] line = '' for _col in columns: line += '{}{} '.format(_pkg[_col], ' ' * (widths[_col] - len(str(_pkg[_col])))) text += '{}\n'.format(line.strip()) return text
[ "def", "output_format_lock", "(", "self", ",", "packages", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_output_config", "[", "'type'", "]", "=", "PLAIN", "text", "=", "''", "tmp_packages", "=", "OrderedDict", "(", ")", "columns", "=", "self", ".", ...
Text to lock file
[ "Text", "to", "lock", "file" ]
c831442ecfaa1d43c66cb148857096cea292c950
https://github.com/devopshq/crosspm/blob/c831442ecfaa1d43c66cb148857096cea292c950/crosspm/helpers/output.py#L276-L303
train
47,059
devopshq/crosspm
crosspm/helpers/output.py
Output.output_format_module
def output_format_module(self, packages, esc_path=False): """ Create out with child first position """ def create_ordered_list(packages_): """ Recursive for package.packages """ list_ = [] for _pkg_name in packages_: _pkg = packages_[_pkg_name] if _pkg and _pkg.packages: list_.extend(create_ordered_list(_pkg.packages)) if _pkg: _pkg_params = _pkg.get_params(self._columns, True) _res_item = {} for item in self._output_config['columns']: name = item['name'].format(OutFormat(item['column'])) value = _pkg_params.get(item['column'], '') if not isinstance(value, (list, dict, tuple)): try: value = item['value'].format( OutFormat(value, (item['column'] == 'path') if esc_path else False)) except Exception: value = '' # TODO: implement this: # if not value: # try: # value = item['value'].format(OutFormat(_pkg.get_params('', True))) # except Exception as e: # pass _res_item[name] = value list_.append(_res_item) return list_ result_list = create_ordered_list(packages, ) if self._output_config['type'] == LIST: return result_list result = OrderedDict() for item in result_list: # TODO: Error handling name = item[self._output_config['key']] if self._output_config['value']: value = item[self._output_config['value']] else: value = OrderedDict([(k, v) for k, v in item.items() if k != self._output_config['key']]) result[name] = value return result
python
def output_format_module(self, packages, esc_path=False): """ Create out with child first position """ def create_ordered_list(packages_): """ Recursive for package.packages """ list_ = [] for _pkg_name in packages_: _pkg = packages_[_pkg_name] if _pkg and _pkg.packages: list_.extend(create_ordered_list(_pkg.packages)) if _pkg: _pkg_params = _pkg.get_params(self._columns, True) _res_item = {} for item in self._output_config['columns']: name = item['name'].format(OutFormat(item['column'])) value = _pkg_params.get(item['column'], '') if not isinstance(value, (list, dict, tuple)): try: value = item['value'].format( OutFormat(value, (item['column'] == 'path') if esc_path else False)) except Exception: value = '' # TODO: implement this: # if not value: # try: # value = item['value'].format(OutFormat(_pkg.get_params('', True))) # except Exception as e: # pass _res_item[name] = value list_.append(_res_item) return list_ result_list = create_ordered_list(packages, ) if self._output_config['type'] == LIST: return result_list result = OrderedDict() for item in result_list: # TODO: Error handling name = item[self._output_config['key']] if self._output_config['value']: value = item[self._output_config['value']] else: value = OrderedDict([(k, v) for k, v in item.items() if k != self._output_config['key']]) result[name] = value return result
[ "def", "output_format_module", "(", "self", ",", "packages", ",", "esc_path", "=", "False", ")", ":", "def", "create_ordered_list", "(", "packages_", ")", ":", "\"\"\"\n Recursive for package.packages\n \"\"\"", "list_", "=", "[", "]", "for", "_p...
Create out with child first position
[ "Create", "out", "with", "child", "first", "position" ]
c831442ecfaa1d43c66cb148857096cea292c950
https://github.com/devopshq/crosspm/blob/c831442ecfaa1d43c66cb148857096cea292c950/crosspm/helpers/output.py#L305-L357
train
47,060
ebertti/django-admin-easy
easy/admin/decorators.py
smart
def smart(**kwargs): """ Simple decorator to get custom fields on admin class, using this you will use less line codes :param short_description: description of custom field :type str: :param admin_order_field: field to order on click :type str: :param allow_tags: allow html tags :type bool: :param boolean: if field is True, False or None :type bool: :param empty_value_display: Default value when field is null :type str: :return: method decorated :rtype: method """ def decorator(func): for key, value in kwargs.items(): setattr(func, key, value) return func return decorator
python
def smart(**kwargs): """ Simple decorator to get custom fields on admin class, using this you will use less line codes :param short_description: description of custom field :type str: :param admin_order_field: field to order on click :type str: :param allow_tags: allow html tags :type bool: :param boolean: if field is True, False or None :type bool: :param empty_value_display: Default value when field is null :type str: :return: method decorated :rtype: method """ def decorator(func): for key, value in kwargs.items(): setattr(func, key, value) return func return decorator
[ "def", "smart", "(", "*", "*", "kwargs", ")", ":", "def", "decorator", "(", "func", ")", ":", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "setattr", "(", "func", ",", "key", ",", "value", ")", "return", "func", "retur...
Simple decorator to get custom fields on admin class, using this you will use less line codes :param short_description: description of custom field :type str: :param admin_order_field: field to order on click :type str: :param allow_tags: allow html tags :type bool: :param boolean: if field is True, False or None :type bool: :param empty_value_display: Default value when field is null :type str: :return: method decorated :rtype: method
[ "Simple", "decorator", "to", "get", "custom", "fields", "on", "admin", "class", "using", "this", "you", "will", "use", "less", "line", "codes" ]
fff5229d2b5ccee2010df9b37ea423fe96d913f7
https://github.com/ebertti/django-admin-easy/blob/fff5229d2b5ccee2010df9b37ea423fe96d913f7/easy/admin/decorators.py#L9-L37
train
47,061
martinmcbride/pysound
pysound/buffer.py
create_buffer
def create_buffer(params, value): ''' If the value is a float, create a numpy array of the required length, filled with value If the value is a numpy array, check its length Otherwise throw a type error ''' try: fv = float(value) return np.full(params.length, fv, np.float) except TypeError: if isinstance(value, np.ndarray): if (len(value)>=params.length): return value raise TypeError('Value must be a float or a numpy array ofthe required length')
python
def create_buffer(params, value): ''' If the value is a float, create a numpy array of the required length, filled with value If the value is a numpy array, check its length Otherwise throw a type error ''' try: fv = float(value) return np.full(params.length, fv, np.float) except TypeError: if isinstance(value, np.ndarray): if (len(value)>=params.length): return value raise TypeError('Value must be a float or a numpy array ofthe required length')
[ "def", "create_buffer", "(", "params", ",", "value", ")", ":", "try", ":", "fv", "=", "float", "(", "value", ")", "return", "np", ".", "full", "(", "params", ".", "length", ",", "fv", ",", "np", ".", "float", ")", "except", "TypeError", ":", "if", ...
If the value is a float, create a numpy array of the required length, filled with value If the value is a numpy array, check its length Otherwise throw a type error
[ "If", "the", "value", "is", "a", "float", "create", "a", "numpy", "array", "of", "the", "required", "length", "filled", "with", "value", "If", "the", "value", "is", "a", "numpy", "array", "check", "its", "length", "Otherwise", "throw", "a", "type", "erro...
253c8f712ad475318350e5a8ba21f6fefd7a3de2
https://github.com/martinmcbride/pysound/blob/253c8f712ad475318350e5a8ba21f6fefd7a3de2/pysound/buffer.py#L76-L89
train
47,062
wasp/waspy
waspy/client.py
Client.make_request
def make_request(self, method, service, path, body=None, query_params: QueryParams=None, headers: dict=None, correlation_id: str=None, content_type: str='application/json', context: Request=None, timeout=30, **kwargs) -> asyncio.coroutine: """ Make a request to another service. If `context` is provided, then context and correlation will be pulled from the provided request object for you. This includes credentials, correlationid, and service-headers. :param method: GET/PUT/PATCH, etc. :param service: name of service :param path: request object path :param body: body of request :param query_params: :param headers: :param correlation_id: :param content_type: :param context: A request object from which a "child-request" will be made :param timeout: Time in seconds the client will wait befor raising an asyncio.TimeoutError :param kwargs: Just a place holder so transport specific options can be passed through :return: """ if not isinstance(method, Methods): method = Methods(method.upper()) if content_type == 'application/json' and isinstance(body, dict): body = json.dumps(body) if isinstance(query_params, dict): query_string = parse.urlencode(query_params) elif isinstance(query_params, QueryParams): query_string = str(query_params) else: query_string = '' headers = headers or {} ctx = request_context.get() if context: warnings.warn("Passing in a context to waspy client is deprecated. " "Passed in context will be ignored", DeprecationWarning) if not correlation_id: correlation_id = ctx['correlation_id'] headers = {**headers, **ctx['ctx_headers']} exchange = headers.get('ctx-exchange-override', None) if exchange: kwargs['exchange'] = 'amq.headers' if isinstance(body, str): body = body.encode() response = asyncio.wait_for( self.transport.make_request( service, method.name, path, body=body, query=query_string, headers=headers, correlation_id=correlation_id, content_type=content_type, timeout=timeout, **kwargs), timeout=timeout) return response
python
def make_request(self, method, service, path, body=None, query_params: QueryParams=None, headers: dict=None, correlation_id: str=None, content_type: str='application/json', context: Request=None, timeout=30, **kwargs) -> asyncio.coroutine: """ Make a request to another service. If `context` is provided, then context and correlation will be pulled from the provided request object for you. This includes credentials, correlationid, and service-headers. :param method: GET/PUT/PATCH, etc. :param service: name of service :param path: request object path :param body: body of request :param query_params: :param headers: :param correlation_id: :param content_type: :param context: A request object from which a "child-request" will be made :param timeout: Time in seconds the client will wait befor raising an asyncio.TimeoutError :param kwargs: Just a place holder so transport specific options can be passed through :return: """ if not isinstance(method, Methods): method = Methods(method.upper()) if content_type == 'application/json' and isinstance(body, dict): body = json.dumps(body) if isinstance(query_params, dict): query_string = parse.urlencode(query_params) elif isinstance(query_params, QueryParams): query_string = str(query_params) else: query_string = '' headers = headers or {} ctx = request_context.get() if context: warnings.warn("Passing in a context to waspy client is deprecated. " "Passed in context will be ignored", DeprecationWarning) if not correlation_id: correlation_id = ctx['correlation_id'] headers = {**headers, **ctx['ctx_headers']} exchange = headers.get('ctx-exchange-override', None) if exchange: kwargs['exchange'] = 'amq.headers' if isinstance(body, str): body = body.encode() response = asyncio.wait_for( self.transport.make_request( service, method.name, path, body=body, query=query_string, headers=headers, correlation_id=correlation_id, content_type=content_type, timeout=timeout, **kwargs), timeout=timeout) return response
[ "def", "make_request", "(", "self", ",", "method", ",", "service", ",", "path", ",", "body", "=", "None", ",", "query_params", ":", "QueryParams", "=", "None", ",", "headers", ":", "dict", "=", "None", ",", "correlation_id", ":", "str", "=", "None", ",...
Make a request to another service. If `context` is provided, then context and correlation will be pulled from the provided request object for you. This includes credentials, correlationid, and service-headers. :param method: GET/PUT/PATCH, etc. :param service: name of service :param path: request object path :param body: body of request :param query_params: :param headers: :param correlation_id: :param content_type: :param context: A request object from which a "child-request" will be made :param timeout: Time in seconds the client will wait befor raising an asyncio.TimeoutError :param kwargs: Just a place holder so transport specific options can be passed through :return:
[ "Make", "a", "request", "to", "another", "service", ".", "If", "context", "is", "provided", "then", "context", "and", "correlation", "will", "be", "pulled", "from", "the", "provided", "request", "object", "for", "you", ".", "This", "includes", "credentials", ...
31cc352f300a089f9607d7f13d93591d4c69d5ec
https://github.com/wasp/waspy/blob/31cc352f300a089f9607d7f13d93591d4c69d5ec/waspy/client.py#L21-L85
train
47,063
proteanhq/protean
src/protean/core/usecase/generic.py
ShowUseCase.process_request
def process_request(self, request_object): """Fetch Resource and return Entity""" identifier = request_object.identifier # Look for the object by its ID and return it resource = request_object.entity_cls.get(identifier) return ResponseSuccess(Status.SUCCESS, resource)
python
def process_request(self, request_object): """Fetch Resource and return Entity""" identifier = request_object.identifier # Look for the object by its ID and return it resource = request_object.entity_cls.get(identifier) return ResponseSuccess(Status.SUCCESS, resource)
[ "def", "process_request", "(", "self", ",", "request_object", ")", ":", "identifier", "=", "request_object", ".", "identifier", "# Look for the object by its ID and return it", "resource", "=", "request_object", ".", "entity_cls", ".", "get", "(", "identifier", ")", "...
Fetch Resource and return Entity
[ "Fetch", "Resource", "and", "return", "Entity" ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/usecase/generic.py#L26-L33
train
47,064
proteanhq/protean
src/protean/core/usecase/generic.py
ListRequestObject.from_dict
def from_dict(cls, entity_cls, adict): """Initialize a ListRequestObject object from a dictionary.""" invalid_req = InvalidRequestObject() # Extract the pagination parameters from the input page = int(adict.pop('page', 1)) per_page = int(adict.pop( 'per_page', getattr(active_config, 'PER_PAGE', 10))) order_by = adict.pop('order_by', ()) # Check for invalid request conditions if page < 0: invalid_req.add_error('page', 'is invalid') if invalid_req.has_errors: return invalid_req # Do we need to pop out random? # adict.pop('random', None) return cls(entity_cls, page, per_page, order_by, adict)
python
def from_dict(cls, entity_cls, adict): """Initialize a ListRequestObject object from a dictionary.""" invalid_req = InvalidRequestObject() # Extract the pagination parameters from the input page = int(adict.pop('page', 1)) per_page = int(adict.pop( 'per_page', getattr(active_config, 'PER_PAGE', 10))) order_by = adict.pop('order_by', ()) # Check for invalid request conditions if page < 0: invalid_req.add_error('page', 'is invalid') if invalid_req.has_errors: return invalid_req # Do we need to pop out random? # adict.pop('random', None) return cls(entity_cls, page, per_page, order_by, adict)
[ "def", "from_dict", "(", "cls", ",", "entity_cls", ",", "adict", ")", ":", "invalid_req", "=", "InvalidRequestObject", "(", ")", "# Extract the pagination parameters from the input", "page", "=", "int", "(", "adict", ".", "pop", "(", "'page'", ",", "1", ")", "...
Initialize a ListRequestObject object from a dictionary.
[ "Initialize", "a", "ListRequestObject", "object", "from", "a", "dictionary", "." ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/usecase/generic.py#L69-L89
train
47,065
proteanhq/protean
src/protean/core/usecase/generic.py
ListUseCase.process_request
def process_request(self, request_object): """Return a list of resources""" resources = (request_object.entity_cls.query .filter(**request_object.filters) .offset((request_object.page - 1) * request_object.per_page) .limit(request_object.per_page) .order_by(request_object.order_by) .all()) return ResponseSuccess(Status.SUCCESS, resources)
python
def process_request(self, request_object): """Return a list of resources""" resources = (request_object.entity_cls.query .filter(**request_object.filters) .offset((request_object.page - 1) * request_object.per_page) .limit(request_object.per_page) .order_by(request_object.order_by) .all()) return ResponseSuccess(Status.SUCCESS, resources)
[ "def", "process_request", "(", "self", ",", "request_object", ")", ":", "resources", "=", "(", "request_object", ".", "entity_cls", ".", "query", ".", "filter", "(", "*", "*", "request_object", ".", "filters", ")", ".", "offset", "(", "(", "request_object", ...
Return a list of resources
[ "Return", "a", "list", "of", "resources" ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/usecase/generic.py#L97-L105
train
47,066
proteanhq/protean
src/protean/core/usecase/generic.py
CreateUseCase.process_request
def process_request(self, request_object): """Process Create Resource Request""" resource = request_object.entity_cls.create(**request_object.data) return ResponseSuccessCreated(resource)
python
def process_request(self, request_object): """Process Create Resource Request""" resource = request_object.entity_cls.create(**request_object.data) return ResponseSuccessCreated(resource)
[ "def", "process_request", "(", "self", ",", "request_object", ")", ":", "resource", "=", "request_object", ".", "entity_cls", ".", "create", "(", "*", "*", "request_object", ".", "data", ")", "return", "ResponseSuccessCreated", "(", "resource", ")" ]
Process Create Resource Request
[ "Process", "Create", "Resource", "Request" ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/usecase/generic.py#L119-L123
train
47,067
proteanhq/protean
src/protean/core/usecase/generic.py
UpdateUseCase.process_request
def process_request(self, request_object): """Process Update Resource Request""" # Retrieve the object by its identifier entity = request_object.entity_cls.get(request_object.identifier) # Update the object and return the updated data resource = entity.update(request_object.data) return ResponseSuccess(Status.SUCCESS, resource)
python
def process_request(self, request_object): """Process Update Resource Request""" # Retrieve the object by its identifier entity = request_object.entity_cls.get(request_object.identifier) # Update the object and return the updated data resource = entity.update(request_object.data) return ResponseSuccess(Status.SUCCESS, resource)
[ "def", "process_request", "(", "self", ",", "request_object", ")", ":", "# Retrieve the object by its identifier", "entity", "=", "request_object", ".", "entity_cls", ".", "get", "(", "request_object", ".", "identifier", ")", "# Update the object and return the updated data...
Process Update Resource Request
[ "Process", "Update", "Resource", "Request" ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/usecase/generic.py#L138-L146
train
47,068
proteanhq/protean
src/protean/core/usecase/generic.py
DeleteUseCase.process_request
def process_request(self, request_object): """Process the Delete Resource Request""" # Delete the object by its identifier entity = request_object.entity_cls.get(request_object.identifier) entity.delete() # FIXME Check for return value of `delete()` # We have successfully deleted the object. # Sending a 204 Response code. return ResponseSuccessWithNoContent()
python
def process_request(self, request_object): """Process the Delete Resource Request""" # Delete the object by its identifier entity = request_object.entity_cls.get(request_object.identifier) entity.delete() # FIXME Check for return value of `delete()` # We have successfully deleted the object. # Sending a 204 Response code. return ResponseSuccessWithNoContent()
[ "def", "process_request", "(", "self", ",", "request_object", ")", ":", "# Delete the object by its identifier", "entity", "=", "request_object", ".", "entity_cls", ".", "get", "(", "request_object", ".", "identifier", ")", "entity", ".", "delete", "(", ")", "# FI...
Process the Delete Resource Request
[ "Process", "the", "Delete", "Resource", "Request" ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/usecase/generic.py#L157-L168
train
47,069
proteanhq/protean
src/protean/core/field/basic.py
String._cast_to_type
def _cast_to_type(self, value): """ Convert the value to its string representation""" if isinstance(value, str) or value is None: return value return str(value)
python
def _cast_to_type(self, value): """ Convert the value to its string representation""" if isinstance(value, str) or value is None: return value return str(value)
[ "def", "_cast_to_type", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "str", ")", "or", "value", "is", "None", ":", "return", "value", "return", "str", "(", "value", ")" ]
Convert the value to its string representation
[ "Convert", "the", "value", "to", "its", "string", "representation" ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/field/basic.py#L32-L36
train
47,070
proteanhq/protean
src/protean/core/field/basic.py
Integer._cast_to_type
def _cast_to_type(self, value): """ Convert the value to an int and raise error on failures""" try: return int(value) except (ValueError, TypeError): self.fail('invalid', value=value)
python
def _cast_to_type(self, value): """ Convert the value to an int and raise error on failures""" try: return int(value) except (ValueError, TypeError): self.fail('invalid', value=value)
[ "def", "_cast_to_type", "(", "self", ",", "value", ")", ":", "try", ":", "return", "int", "(", "value", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "self", ".", "fail", "(", "'invalid'", ",", "value", "=", "value", ")" ]
Convert the value to an int and raise error on failures
[ "Convert", "the", "value", "to", "an", "int", "and", "raise", "error", "on", "failures" ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/field/basic.py#L73-L78
train
47,071
proteanhq/protean
src/protean/core/field/basic.py
Float._cast_to_type
def _cast_to_type(self, value): """ Convert the value to a float and raise error on failures""" try: return float(value) except (ValueError, TypeError): self.fail('invalid', value=value)
python
def _cast_to_type(self, value): """ Convert the value to a float and raise error on failures""" try: return float(value) except (ValueError, TypeError): self.fail('invalid', value=value)
[ "def", "_cast_to_type", "(", "self", ",", "value", ")", ":", "try", ":", "return", "float", "(", "value", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "self", ".", "fail", "(", "'invalid'", ",", "value", "=", "value", ")" ]
Convert the value to a float and raise error on failures
[ "Convert", "the", "value", "to", "a", "float", "and", "raise", "error", "on", "failures" ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/field/basic.py#L101-L106
train
47,072
proteanhq/protean
src/protean/core/field/basic.py
Boolean._cast_to_type
def _cast_to_type(self, value): """ Convert the value to a boolean and raise error on failures""" if value in (True, False): return bool(value) if value in ('t', 'True', '1'): return True if value in ('f', 'False', '0'): return False self.fail('invalid', value=value)
python
def _cast_to_type(self, value): """ Convert the value to a boolean and raise error on failures""" if value in (True, False): return bool(value) if value in ('t', 'True', '1'): return True if value in ('f', 'False', '0'): return False self.fail('invalid', value=value)
[ "def", "_cast_to_type", "(", "self", ",", "value", ")", ":", "if", "value", "in", "(", "True", ",", "False", ")", ":", "return", "bool", "(", "value", ")", "if", "value", "in", "(", "'t'", ",", "'True'", ",", "'1'", ")", ":", "return", "True", "i...
Convert the value to a boolean and raise error on failures
[ "Convert", "the", "value", "to", "a", "boolean", "and", "raise", "error", "on", "failures" ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/field/basic.py#L116-L124
train
47,073
proteanhq/protean
src/protean/core/field/basic.py
List._cast_to_type
def _cast_to_type(self, value): """ Raise error if the value is not a list """ if not isinstance(value, list): self.fail('invalid', value=value) return value
python
def _cast_to_type(self, value): """ Raise error if the value is not a list """ if not isinstance(value, list): self.fail('invalid', value=value) return value
[ "def", "_cast_to_type", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "list", ")", ":", "self", ".", "fail", "(", "'invalid'", ",", "value", "=", "value", ")", "return", "value" ]
Raise error if the value is not a list
[ "Raise", "error", "if", "the", "value", "is", "not", "a", "list" ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/field/basic.py#L134-L138
train
47,074
proteanhq/protean
src/protean/core/field/basic.py
Dict._cast_to_type
def _cast_to_type(self, value): """ Raise error if the value is not a dict """ if not isinstance(value, dict): self.fail('invalid', value=value) return value
python
def _cast_to_type(self, value): """ Raise error if the value is not a dict """ if not isinstance(value, dict): self.fail('invalid', value=value) return value
[ "def", "_cast_to_type", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "dict", ")", ":", "self", ".", "fail", "(", "'invalid'", ",", "value", "=", "value", ")", "return", "value" ]
Raise error if the value is not a dict
[ "Raise", "error", "if", "the", "value", "is", "not", "a", "dict" ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/field/basic.py#L148-L152
train
47,075
proteanhq/protean
src/protean/core/field/basic.py
Date._cast_to_type
def _cast_to_type(self, value): """ Convert the value to a date and raise error on failures""" if isinstance(value, datetime.datetime): return value.date() if isinstance(value, datetime.date): return value try: value = date_parser(value) return value.date() except ValueError: self.fail('invalid', value=value)
python
def _cast_to_type(self, value): """ Convert the value to a date and raise error on failures""" if isinstance(value, datetime.datetime): return value.date() if isinstance(value, datetime.date): return value try: value = date_parser(value) return value.date() except ValueError: self.fail('invalid', value=value)
[ "def", "_cast_to_type", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "datetime", ".", "datetime", ")", ":", "return", "value", ".", "date", "(", ")", "if", "isinstance", "(", "value", ",", "datetime", ".", "date", ")", ...
Convert the value to a date and raise error on failures
[ "Convert", "the", "value", "to", "a", "date", "and", "raise", "error", "on", "failures" ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/field/basic.py#L176-L186
train
47,076
proteanhq/protean
src/protean/core/field/basic.py
DateTime._cast_to_type
def _cast_to_type(self, value): """ Convert the value to a datetime and raise error on failures""" if isinstance(value, datetime.datetime): return value if isinstance(value, datetime.date): value = datetime.datetime(value.year, value.month, value.day) return value try: value = date_parser(value) return value except ValueError: self.fail('invalid', value=value)
python
def _cast_to_type(self, value): """ Convert the value to a datetime and raise error on failures""" if isinstance(value, datetime.datetime): return value if isinstance(value, datetime.date): value = datetime.datetime(value.year, value.month, value.day) return value try: value = date_parser(value) return value except ValueError: self.fail('invalid', value=value)
[ "def", "_cast_to_type", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "datetime", ".", "datetime", ")", ":", "return", "value", "if", "isinstance", "(", "value", ",", "datetime", ".", "date", ")", ":", "value", "=", "datet...
Convert the value to a datetime and raise error on failures
[ "Convert", "the", "value", "to", "a", "datetime", "and", "raise", "error", "on", "failures" ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/field/basic.py#L193-L204
train
47,077
proteanhq/protean
src/protean/core/usecase/base.py
UseCase.execute
def execute(self, request_object): """Generic executor method of all UseCases""" # If the request object is not valid then return a failure response if not request_object.is_valid: return ResponseFailure.build_from_invalid_request( request_object) # Try to process the request and handle any errors encountered try: return self.process_request(request_object) except ValidationError as err: return ResponseFailure.build_unprocessable_error(err.normalized_messages) except ObjectNotFoundError: return ResponseFailure.build_not_found( [{'identifier': 'Object with this ID does not exist.'}]) except Exception as exc: logger.error( f'{self.__class__.__name__} execution failed due to error {exc}', exc_info=True) return ResponseFailure.build_system_error([{exc.__class__.__name__: exc}])
python
def execute(self, request_object): """Generic executor method of all UseCases""" # If the request object is not valid then return a failure response if not request_object.is_valid: return ResponseFailure.build_from_invalid_request( request_object) # Try to process the request and handle any errors encountered try: return self.process_request(request_object) except ValidationError as err: return ResponseFailure.build_unprocessable_error(err.normalized_messages) except ObjectNotFoundError: return ResponseFailure.build_not_found( [{'identifier': 'Object with this ID does not exist.'}]) except Exception as exc: logger.error( f'{self.__class__.__name__} execution failed due to error {exc}', exc_info=True) return ResponseFailure.build_system_error([{exc.__class__.__name__: exc}])
[ "def", "execute", "(", "self", ",", "request_object", ")", ":", "# If the request object is not valid then return a failure response", "if", "not", "request_object", ".", "is_valid", ":", "return", "ResponseFailure", ".", "build_from_invalid_request", "(", "request_object", ...
Generic executor method of all UseCases
[ "Generic", "executor", "method", "of", "all", "UseCases" ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/usecase/base.py#L17-L40
train
47,078
wasp/waspy
waspy/listeners/rabbitmq_listener.py
RabbitMQTransportListener.exchange_declare
async def exchange_declare(self): """ Override this method to change how a exchange is declared """ await self.channel.exchange_declare( self.exchange, self.exchange_type, durable=self.durable, auto_delete=self.auto_delete, no_wait=self.no_wait, )
python
async def exchange_declare(self): """ Override this method to change how a exchange is declared """ await self.channel.exchange_declare( self.exchange, self.exchange_type, durable=self.durable, auto_delete=self.auto_delete, no_wait=self.no_wait, )
[ "async", "def", "exchange_declare", "(", "self", ")", ":", "await", "self", ".", "channel", ".", "exchange_declare", "(", "self", ".", "exchange", ",", "self", ".", "exchange_type", ",", "durable", "=", "self", ".", "durable", ",", "auto_delete", "=", "sel...
Override this method to change how a exchange is declared
[ "Override", "this", "method", "to", "change", "how", "a", "exchange", "is", "declared" ]
31cc352f300a089f9607d7f13d93591d4c69d5ec
https://github.com/wasp/waspy/blob/31cc352f300a089f9607d7f13d93591d4c69d5ec/waspy/listeners/rabbitmq_listener.py#L77-L85
train
47,079
wasp/waspy
waspy/listeners/rabbitmq_listener.py
RabbitMQTransportListener.queue_declare
async def queue_declare(self): """ Override this method to change how a queue is declared """ await self.channel.queue_declare( self.queue, durable=self.durable, exclusive=self.exclusive, no_wait=self.no_wait )
python
async def queue_declare(self): """ Override this method to change how a queue is declared """ await self.channel.queue_declare( self.queue, durable=self.durable, exclusive=self.exclusive, no_wait=self.no_wait )
[ "async", "def", "queue_declare", "(", "self", ")", ":", "await", "self", ".", "channel", ".", "queue_declare", "(", "self", ".", "queue", ",", "durable", "=", "self", ".", "durable", ",", "exclusive", "=", "self", ".", "exclusive", ",", "no_wait", "=", ...
Override this method to change how a queue is declared
[ "Override", "this", "method", "to", "change", "how", "a", "queue", "is", "declared" ]
31cc352f300a089f9607d7f13d93591d4c69d5ec
https://github.com/wasp/waspy/blob/31cc352f300a089f9607d7f13d93591d4c69d5ec/waspy/listeners/rabbitmq_listener.py#L87-L94
train
47,080
proteanhq/protean
src/protean/impl/repository/dict_repo.py
DictModel.from_entity
def from_entity(cls, entity: Entity) -> 'DictModel': """Convert the entity to a dictionary record """ dict_obj = {} for field_name in entity.meta_.attributes: dict_obj[field_name] = getattr(entity, field_name) return dict_obj
python
def from_entity(cls, entity: Entity) -> 'DictModel': """Convert the entity to a dictionary record """ dict_obj = {} for field_name in entity.meta_.attributes: dict_obj[field_name] = getattr(entity, field_name) return dict_obj
[ "def", "from_entity", "(", "cls", ",", "entity", ":", "Entity", ")", "->", "'DictModel'", ":", "dict_obj", "=", "{", "}", "for", "field_name", "in", "entity", ".", "meta_", ".", "attributes", ":", "dict_obj", "[", "field_name", "]", "=", "getattr", "(", ...
Convert the entity to a dictionary record
[ "Convert", "the", "entity", "to", "a", "dictionary", "record" ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/impl/repository/dict_repo.py#L30-L35
train
47,081
proteanhq/protean
src/protean/impl/repository/dict_repo.py
DictProvider.get_connection
def get_connection(self): """Return the dictionary database object """ database = { 'data': _databases.setdefault(self.identifier, defaultdict(dict)), 'lock': _locks.setdefault(self.identifier, Lock()), 'counters': _counters } return database
python
def get_connection(self): """Return the dictionary database object """ database = { 'data': _databases.setdefault(self.identifier, defaultdict(dict)), 'lock': _locks.setdefault(self.identifier, Lock()), 'counters': _counters } return database
[ "def", "get_connection", "(", "self", ")", ":", "database", "=", "{", "'data'", ":", "_databases", ".", "setdefault", "(", "self", ".", "identifier", ",", "defaultdict", "(", "dict", ")", ")", ",", "'lock'", ":", "_locks", ".", "setdefault", "(", "self",...
Return the dictionary database object
[ "Return", "the", "dictionary", "database", "object" ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/impl/repository/dict_repo.py#L54-L61
train
47,082
proteanhq/protean
src/protean/impl/repository/dict_repo.py
DictProvider.get_repository
def get_repository(self, entity_cls): """Return a repository object configured with a live connection""" model_cls = self.get_model(entity_cls) return DictRepository(self, entity_cls, model_cls)
python
def get_repository(self, entity_cls): """Return a repository object configured with a live connection""" model_cls = self.get_model(entity_cls) return DictRepository(self, entity_cls, model_cls)
[ "def", "get_repository", "(", "self", ",", "entity_cls", ")", ":", "model_cls", "=", "self", ".", "get_model", "(", "entity_cls", ")", "return", "DictRepository", "(", "self", ",", "entity_cls", ",", "model_cls", ")" ]
Return a repository object configured with a live connection
[ "Return", "a", "repository", "object", "configured", "with", "a", "live", "connection" ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/impl/repository/dict_repo.py#L74-L77
train
47,083
proteanhq/protean
src/protean/impl/repository/dict_repo.py
DictProvider._evaluate_lookup
def _evaluate_lookup(self, key, value, negated, db): """Extract values from DB that match the given criteria""" results = {} for record_key, record_value in db.items(): match = True stripped_key, lookup_class = self._extract_lookup(key) lookup = lookup_class(record_value[stripped_key], value) if negated: match &= not eval(lookup.as_expression()) else: match &= eval(lookup.as_expression()) if match: results[record_key] = record_value return results
python
def _evaluate_lookup(self, key, value, negated, db): """Extract values from DB that match the given criteria""" results = {} for record_key, record_value in db.items(): match = True stripped_key, lookup_class = self._extract_lookup(key) lookup = lookup_class(record_value[stripped_key], value) if negated: match &= not eval(lookup.as_expression()) else: match &= eval(lookup.as_expression()) if match: results[record_key] = record_value return results
[ "def", "_evaluate_lookup", "(", "self", ",", "key", ",", "value", ",", "negated", ",", "db", ")", ":", "results", "=", "{", "}", "for", "record_key", ",", "record_value", "in", "db", ".", "items", "(", ")", ":", "match", "=", "True", "stripped_key", ...
Extract values from DB that match the given criteria
[ "Extract", "values", "from", "DB", "that", "match", "the", "given", "criteria" ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/impl/repository/dict_repo.py#L79-L96
train
47,084
proteanhq/protean
src/protean/impl/repository/dict_repo.py
DictProvider.raw
def raw(self, query: Any, data: Any = None): """Run raw queries on the database As an example of running ``raw`` queries on a Dict repository, we will run the query on all possible schemas, and return all results. """ assert isinstance(query, str) conn = self.get_connection() items = [] for schema_name in conn['data']: input_db = conn['data'][schema_name] try: # Ensures that the string contains double quotes around keys and values query = query.replace("'", "\"") criteria = json.loads(query) for key, value in criteria.items(): input_db = self._evaluate_lookup(key, value, False, input_db) items.extend(list(input_db.values())) except json.JSONDecodeError: # FIXME Log Exception raise Exception("Query Malformed") except KeyError: # We encountered a repository where the key was not found pass return items
python
def raw(self, query: Any, data: Any = None): """Run raw queries on the database As an example of running ``raw`` queries on a Dict repository, we will run the query on all possible schemas, and return all results. """ assert isinstance(query, str) conn = self.get_connection() items = [] for schema_name in conn['data']: input_db = conn['data'][schema_name] try: # Ensures that the string contains double quotes around keys and values query = query.replace("'", "\"") criteria = json.loads(query) for key, value in criteria.items(): input_db = self._evaluate_lookup(key, value, False, input_db) items.extend(list(input_db.values())) except json.JSONDecodeError: # FIXME Log Exception raise Exception("Query Malformed") except KeyError: # We encountered a repository where the key was not found pass return items
[ "def", "raw", "(", "self", ",", "query", ":", "Any", ",", "data", ":", "Any", "=", "None", ")", ":", "assert", "isinstance", "(", "query", ",", "str", ")", "conn", "=", "self", ".", "get_connection", "(", ")", "items", "=", "[", "]", "for", "sche...
Run raw queries on the database As an example of running ``raw`` queries on a Dict repository, we will run the query on all possible schemas, and return all results.
[ "Run", "raw", "queries", "on", "the", "database" ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/impl/repository/dict_repo.py#L98-L128
train
47,085
proteanhq/protean
src/protean/impl/repository/dict_repo.py
DictRepository._set_auto_fields
def _set_auto_fields(self, model_obj): """Set the values of the auto field using counter""" for field_name, field_obj in \ self.entity_cls.meta_.auto_fields: counter_key = f'{self.schema_name}_{field_name}' if not (field_name in model_obj and model_obj[field_name] is not None): # Increment the counter and it should start from 1 counter = next(self.conn['counters'][counter_key]) if not counter: counter = next(self.conn['counters'][counter_key]) model_obj[field_name] = counter return model_obj
python
def _set_auto_fields(self, model_obj): """Set the values of the auto field using counter""" for field_name, field_obj in \ self.entity_cls.meta_.auto_fields: counter_key = f'{self.schema_name}_{field_name}' if not (field_name in model_obj and model_obj[field_name] is not None): # Increment the counter and it should start from 1 counter = next(self.conn['counters'][counter_key]) if not counter: counter = next(self.conn['counters'][counter_key]) model_obj[field_name] = counter return model_obj
[ "def", "_set_auto_fields", "(", "self", ",", "model_obj", ")", ":", "for", "field_name", ",", "field_obj", "in", "self", ".", "entity_cls", ".", "meta_", ".", "auto_fields", ":", "counter_key", "=", "f'{self.schema_name}_{field_name}'", "if", "not", "(", "field_...
Set the values of the auto field using counter
[ "Set", "the", "values", "of", "the", "auto", "field", "using", "counter" ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/impl/repository/dict_repo.py#L134-L146
train
47,086
proteanhq/protean
src/protean/impl/repository/dict_repo.py
DictRepository.create
def create(self, model_obj): """Write a record to the dict repository""" # Update the value of the counters model_obj = self._set_auto_fields(model_obj) # Add the entity to the repository identifier = model_obj[self.entity_cls.meta_.id_field.field_name] with self.conn['lock']: self.conn['data'][self.schema_name][identifier] = model_obj return model_obj
python
def create(self, model_obj): """Write a record to the dict repository""" # Update the value of the counters model_obj = self._set_auto_fields(model_obj) # Add the entity to the repository identifier = model_obj[self.entity_cls.meta_.id_field.field_name] with self.conn['lock']: self.conn['data'][self.schema_name][identifier] = model_obj return model_obj
[ "def", "create", "(", "self", ",", "model_obj", ")", ":", "# Update the value of the counters", "model_obj", "=", "self", ".", "_set_auto_fields", "(", "model_obj", ")", "# Add the entity to the repository", "identifier", "=", "model_obj", "[", "self", ".", "entity_cl...
Write a record to the dict repository
[ "Write", "a", "record", "to", "the", "dict", "repository" ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/impl/repository/dict_repo.py#L148-L158
train
47,087
proteanhq/protean
src/protean/impl/repository/dict_repo.py
DictRepository._filter
def _filter(self, criteria: Q, db): """Recursive function to filter items from dictionary""" # Filter the dictionary objects based on the filters negated = criteria.negated input_db = None if criteria.connector == criteria.AND: # Trim database records over successive iterations # Whatever is left at the end satisfy all criteria (AND) input_db = db for child in criteria.children: if isinstance(child, Q): input_db = self._filter(child, input_db) else: input_db = self.provider._evaluate_lookup(child[0], child[1], negated, input_db) else: # Grow database records over successive iterations # Whatever is left at the end satisfy any criteria (OR) input_db = {} for child in criteria.children: if isinstance(child, Q): results = self._filter(child, db) else: results = self.provider._evaluate_lookup(child[0], child[1], negated, db) input_db = {**input_db, **results} return input_db
python
def _filter(self, criteria: Q, db): """Recursive function to filter items from dictionary""" # Filter the dictionary objects based on the filters negated = criteria.negated input_db = None if criteria.connector == criteria.AND: # Trim database records over successive iterations # Whatever is left at the end satisfy all criteria (AND) input_db = db for child in criteria.children: if isinstance(child, Q): input_db = self._filter(child, input_db) else: input_db = self.provider._evaluate_lookup(child[0], child[1], negated, input_db) else: # Grow database records over successive iterations # Whatever is left at the end satisfy any criteria (OR) input_db = {} for child in criteria.children: if isinstance(child, Q): results = self._filter(child, db) else: results = self.provider._evaluate_lookup(child[0], child[1], negated, db) input_db = {**input_db, **results} return input_db
[ "def", "_filter", "(", "self", ",", "criteria", ":", "Q", ",", "db", ")", ":", "# Filter the dictionary objects based on the filters", "negated", "=", "criteria", ".", "negated", "input_db", "=", "None", "if", "criteria", ".", "connector", "==", "criteria", ".",...
Recursive function to filter items from dictionary
[ "Recursive", "function", "to", "filter", "items", "from", "dictionary" ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/impl/repository/dict_repo.py#L160-L188
train
47,088
proteanhq/protean
src/protean/impl/repository/dict_repo.py
DictRepository.filter
def filter(self, criteria: Q, offset: int = 0, limit: int = 10, order_by: list = ()): """Read the repository and return results as per the filer""" if criteria.children: items = list(self._filter(criteria, self.conn['data'][self.schema_name]).values()) else: items = list(self.conn['data'][self.schema_name].values()) # Sort the filtered results based on the order_by clause for o_key in order_by: reverse = False if o_key.startswith('-'): reverse = True o_key = o_key[1:] items = sorted(items, key=itemgetter(o_key), reverse=reverse) result = ResultSet( offset=offset, limit=limit, total=len(items), items=items[offset: offset + limit]) return result
python
def filter(self, criteria: Q, offset: int = 0, limit: int = 10, order_by: list = ()): """Read the repository and return results as per the filer""" if criteria.children: items = list(self._filter(criteria, self.conn['data'][self.schema_name]).values()) else: items = list(self.conn['data'][self.schema_name].values()) # Sort the filtered results based on the order_by clause for o_key in order_by: reverse = False if o_key.startswith('-'): reverse = True o_key = o_key[1:] items = sorted(items, key=itemgetter(o_key), reverse=reverse) result = ResultSet( offset=offset, limit=limit, total=len(items), items=items[offset: offset + limit]) return result
[ "def", "filter", "(", "self", ",", "criteria", ":", "Q", ",", "offset", ":", "int", "=", "0", ",", "limit", ":", "int", "=", "10", ",", "order_by", ":", "list", "=", "(", ")", ")", ":", "if", "criteria", ".", "children", ":", "items", "=", "lis...
Read the repository and return results as per the filer
[ "Read", "the", "repository", "and", "return", "results", "as", "per", "the", "filer" ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/impl/repository/dict_repo.py#L190-L211
train
47,089
proteanhq/protean
src/protean/impl/repository/dict_repo.py
DictRepository.update
def update(self, model_obj): """Update the entity record in the dictionary """ identifier = model_obj[self.entity_cls.meta_.id_field.field_name] with self.conn['lock']: # Check if object is present if identifier not in self.conn['data'][self.schema_name]: raise ObjectNotFoundError( f'`{self.__class__.__name__}` object with identifier {identifier} ' f'does not exist.') self.conn['data'][self.schema_name][identifier] = model_obj return model_obj
python
def update(self, model_obj): """Update the entity record in the dictionary """ identifier = model_obj[self.entity_cls.meta_.id_field.field_name] with self.conn['lock']: # Check if object is present if identifier not in self.conn['data'][self.schema_name]: raise ObjectNotFoundError( f'`{self.__class__.__name__}` object with identifier {identifier} ' f'does not exist.') self.conn['data'][self.schema_name][identifier] = model_obj return model_obj
[ "def", "update", "(", "self", ",", "model_obj", ")", ":", "identifier", "=", "model_obj", "[", "self", ".", "entity_cls", ".", "meta_", ".", "id_field", ".", "field_name", "]", "with", "self", ".", "conn", "[", "'lock'", "]", ":", "# Check if object is pre...
Update the entity record in the dictionary
[ "Update", "the", "entity", "record", "in", "the", "dictionary" ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/impl/repository/dict_repo.py#L213-L224
train
47,090
proteanhq/protean
src/protean/impl/repository/dict_repo.py
DictRepository.update_all
def update_all(self, criteria: Q, *args, **kwargs): """Update all objects satisfying the criteria """ items = self._filter(criteria, self.conn['data'][self.schema_name]) update_count = 0 for key in items: item = items[key] item.update(*args) item.update(kwargs) self.conn['data'][self.schema_name][key] = item update_count += 1 return update_count
python
def update_all(self, criteria: Q, *args, **kwargs): """Update all objects satisfying the criteria """ items = self._filter(criteria, self.conn['data'][self.schema_name]) update_count = 0 for key in items: item = items[key] item.update(*args) item.update(kwargs) self.conn['data'][self.schema_name][key] = item update_count += 1 return update_count
[ "def", "update_all", "(", "self", ",", "criteria", ":", "Q", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "items", "=", "self", ".", "_filter", "(", "criteria", ",", "self", ".", "conn", "[", "'data'", "]", "[", "self", ".", "schema_name", ...
Update all objects satisfying the criteria
[ "Update", "all", "objects", "satisfying", "the", "criteria" ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/impl/repository/dict_repo.py#L226-L239
train
47,091
proteanhq/protean
src/protean/impl/repository/dict_repo.py
DictRepository.delete_all
def delete_all(self, criteria: Q = None): """Delete the dictionary object by its criteria""" if criteria: # Delete the object from the dictionary and return the deletion count items = self._filter(criteria, self.conn['data'][self.schema_name]) # Delete all the matching identifiers with self.conn['lock']: for identifier in items: self.conn['data'][self.schema_name].pop(identifier, None) return len(items) else: with self.conn['lock']: if self.schema_name in self.conn['data']: del self.conn['data'][self.schema_name]
python
def delete_all(self, criteria: Q = None): """Delete the dictionary object by its criteria""" if criteria: # Delete the object from the dictionary and return the deletion count items = self._filter(criteria, self.conn['data'][self.schema_name]) # Delete all the matching identifiers with self.conn['lock']: for identifier in items: self.conn['data'][self.schema_name].pop(identifier, None) return len(items) else: with self.conn['lock']: if self.schema_name in self.conn['data']: del self.conn['data'][self.schema_name]
[ "def", "delete_all", "(", "self", ",", "criteria", ":", "Q", "=", "None", ")", ":", "if", "criteria", ":", "# Delete the object from the dictionary and return the deletion count", "items", "=", "self", ".", "_filter", "(", "criteria", ",", "self", ".", "conn", "...
Delete the dictionary object by its criteria
[ "Delete", "the", "dictionary", "object", "by", "its", "criteria" ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/impl/repository/dict_repo.py#L254-L269
train
47,092
proteanhq/protean
src/protean/impl/repository/dict_repo.py
DictRepository.raw
def raw(self, query: Any, data: Any = None): """Run raw query on Repository. For this stand-in repository, the query string is a json string that contains kwargs criteria with straigh-forward equality checks. Individual criteria are always ANDed and the result is always a subset of the full repository. We will ignore the `data` parameter for this kind of repository. """ # Ensure that we are dealing with a string, for this repository assert isinstance(query, str) input_db = self.conn['data'][self.schema_name] result = None try: # Ensures that the string contains double quotes around keys and values query = query.replace("'", "\"") criteria = json.loads(query) for key, value in criteria.items(): input_db = self.provider._evaluate_lookup(key, value, False, input_db) items = list(input_db.values()) result = ResultSet( offset=1, limit=len(items), total=len(items), items=items) except json.JSONDecodeError: # FIXME Log Exception raise Exception("Query Malformed") return result
python
def raw(self, query: Any, data: Any = None): """Run raw query on Repository. For this stand-in repository, the query string is a json string that contains kwargs criteria with straigh-forward equality checks. Individual criteria are always ANDed and the result is always a subset of the full repository. We will ignore the `data` parameter for this kind of repository. """ # Ensure that we are dealing with a string, for this repository assert isinstance(query, str) input_db = self.conn['data'][self.schema_name] result = None try: # Ensures that the string contains double quotes around keys and values query = query.replace("'", "\"") criteria = json.loads(query) for key, value in criteria.items(): input_db = self.provider._evaluate_lookup(key, value, False, input_db) items = list(input_db.values()) result = ResultSet( offset=1, limit=len(items), total=len(items), items=items) except json.JSONDecodeError: # FIXME Log Exception raise Exception("Query Malformed") return result
[ "def", "raw", "(", "self", ",", "query", ":", "Any", ",", "data", ":", "Any", "=", "None", ")", ":", "# Ensure that we are dealing with a string, for this repository", "assert", "isinstance", "(", "query", ",", "str", ")", "input_db", "=", "self", ".", "conn",...
Run raw query on Repository. For this stand-in repository, the query string is a json string that contains kwargs criteria with straigh-forward equality checks. Individual criteria are always ANDed and the result is always a subset of the full repository. We will ignore the `data` parameter for this kind of repository.
[ "Run", "raw", "query", "on", "Repository", "." ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/impl/repository/dict_repo.py#L271-L305
train
47,093
proteanhq/protean
src/protean/impl/repository/dict_repo.py
DefaultDictLookup.process_source
def process_source(self): """Return source with transformations, if any""" if isinstance(self.source, str): # Replace single and double quotes with escaped single-quote self.source = self.source.replace("'", "\'").replace('"', "\'") return "\"{source}\"".format(source=self.source) return self.source
python
def process_source(self): """Return source with transformations, if any""" if isinstance(self.source, str): # Replace single and double quotes with escaped single-quote self.source = self.source.replace("'", "\'").replace('"', "\'") return "\"{source}\"".format(source=self.source) return self.source
[ "def", "process_source", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "source", ",", "str", ")", ":", "# Replace single and double quotes with escaped single-quote", "self", ".", "source", "=", "self", ".", "source", ".", "replace", "(", "\"'\"",...
Return source with transformations, if any
[ "Return", "source", "with", "transformations", "if", "any" ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/impl/repository/dict_repo.py#L323-L329
train
47,094
proteanhq/protean
src/protean/impl/repository/dict_repo.py
DefaultDictLookup.process_target
def process_target(self): """Return target with transformations, if any""" if isinstance(self.target, str): # Replace single and double quotes with escaped single-quote self.target = self.target.replace("'", "\'").replace('"', "\'") return "\"{target}\"".format(target=self.target) return self.target
python
def process_target(self): """Return target with transformations, if any""" if isinstance(self.target, str): # Replace single and double quotes with escaped single-quote self.target = self.target.replace("'", "\'").replace('"', "\'") return "\"{target}\"".format(target=self.target) return self.target
[ "def", "process_target", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "target", ",", "str", ")", ":", "# Replace single and double quotes with escaped single-quote", "self", ".", "target", "=", "self", ".", "target", ".", "replace", "(", "\"'\"",...
Return target with transformations, if any
[ "Return", "target", "with", "transformations", "if", "any" ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/impl/repository/dict_repo.py#L331-L337
train
47,095
wasp/waspy
waspy/transports/rabbitmqtransport.py
parse_url_to_topic
def parse_url_to_topic(method, route): """ Transforms a URL to a topic. `GET /bar/{id}` -> `get.bar.*` `POST /bar/{id}` -> `post.bar.*` `GET /foo/bar/{id}/baz` -? `get.foo.bar.*.baz` Possible gotchas `GET /foo/{id}` -> `get.foo.*` `GET /foo/{id}:action` -> `get.foo.*` However, once it hits the service the router will be able to distinguish the two requests. """ route = route.replace('.', '?') route = route.replace('/', '.').strip('.') topic = f'{method.value.lower()}.{route}' # need to replace `{id}` and `{id}:some_method` with just `*` return re.sub(r"\.\{[^\}]*\}[:\w\d_-]*", ".*", topic)
python
def parse_url_to_topic(method, route): """ Transforms a URL to a topic. `GET /bar/{id}` -> `get.bar.*` `POST /bar/{id}` -> `post.bar.*` `GET /foo/bar/{id}/baz` -? `get.foo.bar.*.baz` Possible gotchas `GET /foo/{id}` -> `get.foo.*` `GET /foo/{id}:action` -> `get.foo.*` However, once it hits the service the router will be able to distinguish the two requests. """ route = route.replace('.', '?') route = route.replace('/', '.').strip('.') topic = f'{method.value.lower()}.{route}' # need to replace `{id}` and `{id}:some_method` with just `*` return re.sub(r"\.\{[^\}]*\}[:\w\d_-]*", ".*", topic)
[ "def", "parse_url_to_topic", "(", "method", ",", "route", ")", ":", "route", "=", "route", ".", "replace", "(", "'.'", ",", "'?'", ")", "route", "=", "route", ".", "replace", "(", "'/'", ",", "'.'", ")", ".", "strip", "(", "'.'", ")", "topic", "=",...
Transforms a URL to a topic. `GET /bar/{id}` -> `get.bar.*` `POST /bar/{id}` -> `post.bar.*` `GET /foo/bar/{id}/baz` -? `get.foo.bar.*.baz` Possible gotchas `GET /foo/{id}` -> `get.foo.*` `GET /foo/{id}:action` -> `get.foo.*` However, once it hits the service the router will be able to distinguish the two requests.
[ "Transforms", "a", "URL", "to", "a", "topic", "." ]
31cc352f300a089f9607d7f13d93591d4c69d5ec
https://github.com/wasp/waspy/blob/31cc352f300a089f9607d7f13d93591d4c69d5ec/waspy/transports/rabbitmqtransport.py#L500-L519
train
47,096
tadashi-aikawa/jumeaux
jumeaux/addons/res2res/json.py
wrap
def wrap(anything: bytes, encoding: str) -> str: """Use for example of Transformer.function """ return json.dumps({ "wrap": load_json(anything.decode(encoding)) }, ensure_ascii=False)
python
def wrap(anything: bytes, encoding: str) -> str: """Use for example of Transformer.function """ return json.dumps({ "wrap": load_json(anything.decode(encoding)) }, ensure_ascii=False)
[ "def", "wrap", "(", "anything", ":", "bytes", ",", "encoding", ":", "str", ")", "->", "str", ":", "return", "json", ".", "dumps", "(", "{", "\"wrap\"", ":", "load_json", "(", "anything", ".", "decode", "(", "encoding", ")", ")", "}", ",", "ensure_asc...
Use for example of Transformer.function
[ "Use", "for", "example", "of", "Transformer", ".", "function" ]
23389bde3e9b27b3a646d99289f8b5ced411f6f0
https://github.com/tadashi-aikawa/jumeaux/blob/23389bde3e9b27b3a646d99289f8b5ced411f6f0/jumeaux/addons/res2res/json.py#L19-L24
train
47,097
proteanhq/protean
src/protean/core/transport/request.py
RequestObjectFactory.construct
def construct(cls, name: str, declared_fields: typing.List[tuple]): """ Utility method packaged along with the factory to be able to construct Request Object classes on the fly. Example: .. code-block:: python UserShowRequestObject = Factory.create_request_object( 'CreateRequestObject', [('identifier', int, {'required': True}), ('name', str, {'required': True}), ('desc', str, {'default': 'Blah'})]) And then create a request object like so: .. code-block:: python request_object = UserShowRequestObject.from_dict( {'identifier': 112, 'name': 'Jane', 'desc': "Doer is not Doe"}) The third tuple element is a `dict` of the form: {'required': True, 'default': 'John'} * ``required`` is False by default, so ``{required: False, default: 'John'}`` and \ ``{default: 'John'}`` evaluate to the same field definition * ``default`` is a *concrete* value of the correct type """ # FIXME Refactor this method to make it simpler @classmethod def from_dict(cls, adict): """Validate and initialize a Request Object""" invalid_req = InvalidRequestObject() values = {} for item in fields(cls): value = None if item.metadata and 'required' in item.metadata and item.metadata['required']: if item.name not in adict or adict.get(item.name) is None: invalid_req.add_error(item.name, 'is required') else: value = adict[item.name] elif item.name in adict: value = adict[item.name] elif item.default: value = item.default try: if item.type not in [typing.Any, 'typing.Any'] and value is not None: if item.type in [int, float, str, bool, list, dict, tuple, datetime.date, datetime.datetime]: value = item.type(value) else: if not (isinstance(value, item.type) or issubclass(value, item.type)): invalid_req.add_error( item.name, '{} should be of type {}'.format(item.name, item.type)) except Exception: invalid_req.add_error( item.name, 'Value {} for {} is invalid'.format(value, item.name)) values[item.name] = value # Return errors, if any, instead of a request object if invalid_req.has_errors: return invalid_req # Return the initialized Request Object instance return cls(**values) formatted_fields = cls._format_fields(declared_fields) dc = make_dataclass(name, formatted_fields, namespace={'from_dict': from_dict, 'is_valid': True}) return dc
python
def construct(cls, name: str, declared_fields: typing.List[tuple]): """ Utility method packaged along with the factory to be able to construct Request Object classes on the fly. Example: .. code-block:: python UserShowRequestObject = Factory.create_request_object( 'CreateRequestObject', [('identifier', int, {'required': True}), ('name', str, {'required': True}), ('desc', str, {'default': 'Blah'})]) And then create a request object like so: .. code-block:: python request_object = UserShowRequestObject.from_dict( {'identifier': 112, 'name': 'Jane', 'desc': "Doer is not Doe"}) The third tuple element is a `dict` of the form: {'required': True, 'default': 'John'} * ``required`` is False by default, so ``{required: False, default: 'John'}`` and \ ``{default: 'John'}`` evaluate to the same field definition * ``default`` is a *concrete* value of the correct type """ # FIXME Refactor this method to make it simpler @classmethod def from_dict(cls, adict): """Validate and initialize a Request Object""" invalid_req = InvalidRequestObject() values = {} for item in fields(cls): value = None if item.metadata and 'required' in item.metadata and item.metadata['required']: if item.name not in adict or adict.get(item.name) is None: invalid_req.add_error(item.name, 'is required') else: value = adict[item.name] elif item.name in adict: value = adict[item.name] elif item.default: value = item.default try: if item.type not in [typing.Any, 'typing.Any'] and value is not None: if item.type in [int, float, str, bool, list, dict, tuple, datetime.date, datetime.datetime]: value = item.type(value) else: if not (isinstance(value, item.type) or issubclass(value, item.type)): invalid_req.add_error( item.name, '{} should be of type {}'.format(item.name, item.type)) except Exception: invalid_req.add_error( item.name, 'Value {} for {} is invalid'.format(value, item.name)) values[item.name] = value # Return errors, if any, instead of a request object if invalid_req.has_errors: return invalid_req # Return the initialized Request Object instance return cls(**values) formatted_fields = cls._format_fields(declared_fields) dc = make_dataclass(name, formatted_fields, namespace={'from_dict': from_dict, 'is_valid': True}) return dc
[ "def", "construct", "(", "cls", ",", "name", ":", "str", ",", "declared_fields", ":", "typing", ".", "List", "[", "tuple", "]", ")", ":", "# FIXME Refactor this method to make it simpler", "@", "classmethod", "def", "from_dict", "(", "cls", ",", "adict", ")", ...
Utility method packaged along with the factory to be able to construct Request Object classes on the fly. Example: .. code-block:: python UserShowRequestObject = Factory.create_request_object( 'CreateRequestObject', [('identifier', int, {'required': True}), ('name', str, {'required': True}), ('desc', str, {'default': 'Blah'})]) And then create a request object like so: .. code-block:: python request_object = UserShowRequestObject.from_dict( {'identifier': 112, 'name': 'Jane', 'desc': "Doer is not Doe"}) The third tuple element is a `dict` of the form: {'required': True, 'default': 'John'} * ``required`` is False by default, so ``{required: False, default: 'John'}`` and \ ``{default: 'John'}`` evaluate to the same field definition * ``default`` is a *concrete* value of the correct type
[ "Utility", "method", "packaged", "along", "with", "the", "factory", "to", "be", "able", "to", "construct", "Request", "Object", "classes", "on", "the", "fly", "." ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/transport/request.py#L40-L117
train
47,098
proteanhq/protean
src/protean/core/transport/request.py
RequestObjectFactory._format_fields
def _format_fields(cls, declared_fields: typing.List[tuple]): """Process declared fields and construct a list of tuples that can be fed into dataclass constructor factory. """ formatted_fields = [] for declared_field in declared_fields: field_name = field_type = field_defn = None # Case when only (name), or "name", is specified if isinstance(declared_field, str) or len(declared_field) == 1: field_name = declared_field field_type = typing.Any field_defn = field(default=None) # Case when (name, type) are specified elif len(declared_field) == 2: field_name = declared_field[0] field_type = declared_field[1] field_defn = field(default=None) # Case when (name, type, field) are specified elif len(declared_field) == 3: field_name = declared_field[0] field_type = declared_field[1] # Process the definition and create a `field` object # Definition will be of the form `{'required': False, 'default': 'John'}` assert isinstance(declared_field[2], dict) metadata = default = None if 'required' in declared_field[2] and declared_field[2]['required']: metadata = {'required': True} if 'default' in declared_field[2]: default = declared_field[2]['default'] field_defn = field(default=default, metadata=metadata) formatted_fields.append((field_name, field_type, field_defn)) return formatted_fields
python
def _format_fields(cls, declared_fields: typing.List[tuple]): """Process declared fields and construct a list of tuples that can be fed into dataclass constructor factory. """ formatted_fields = [] for declared_field in declared_fields: field_name = field_type = field_defn = None # Case when only (name), or "name", is specified if isinstance(declared_field, str) or len(declared_field) == 1: field_name = declared_field field_type = typing.Any field_defn = field(default=None) # Case when (name, type) are specified elif len(declared_field) == 2: field_name = declared_field[0] field_type = declared_field[1] field_defn = field(default=None) # Case when (name, type, field) are specified elif len(declared_field) == 3: field_name = declared_field[0] field_type = declared_field[1] # Process the definition and create a `field` object # Definition will be of the form `{'required': False, 'default': 'John'}` assert isinstance(declared_field[2], dict) metadata = default = None if 'required' in declared_field[2] and declared_field[2]['required']: metadata = {'required': True} if 'default' in declared_field[2]: default = declared_field[2]['default'] field_defn = field(default=default, metadata=metadata) formatted_fields.append((field_name, field_type, field_defn)) return formatted_fields
[ "def", "_format_fields", "(", "cls", ",", "declared_fields", ":", "typing", ".", "List", "[", "tuple", "]", ")", ":", "formatted_fields", "=", "[", "]", "for", "declared_field", "in", "declared_fields", ":", "field_name", "=", "field_type", "=", "field_defn", ...
Process declared fields and construct a list of tuples that can be fed into dataclass constructor factory.
[ "Process", "declared", "fields", "and", "construct", "a", "list", "of", "tuples", "that", "can", "be", "fed", "into", "dataclass", "constructor", "factory", "." ]
0e29873f4aa634aa93cc08ed675dd749c7ed4b0f
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/transport/request.py#L120-L157
train
47,099