repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
dwwkelly/note | note/mongo_driver.py | mongoDB.getItemType | python | def getItemType(self, itemID):
collections = self.getAllItemTypes()
for coll in collections:
note = self.noteDB[coll].find_one({"ID": itemID})
if note is not None:
return coll | :desc: Given an itemID, return the "type" i.e. the collection
it belongs to.
:param int itemID: The item ID, an integer
:returns: The note type
:rval: str | train | https://github.com/dwwkelly/note/blob/b41d5fe1e4a3b67b50285168dd58f903bf219e6c/note/mongo_driver.py#L178-L192 | [
"def getAllItemTypes(self):\n \"\"\"\n :desc: Fetches a list of item types\n :returns: A list of item types:\n :rval: list\n \"\"\"\n\n collections = self.noteDB.collection_names()\n return collections\n"
] | class mongoDB(dbBaseClass):
def __init__(self, dbName, uri=None):
"""
:desc: Initialize the database driver
:param str dbName: The name of the database in mongo
:param str uri: The Mongo URI to use
"""
self.dbName = dbName
try:
self.c... |
dwwkelly/note | note/mongo_driver.py | mongoDB.searchForItem | python | def searchForItem(self, searchInfo, resultLimit=20, sortBy="relevance"):
searchResults = []
colls = self.get_data_collections()
proj = {"_id": 0}
for coll in colls:
res = self.noteDB.command("text",
coll,
... | :desc: Given a search term returns a list of results that match
that term:
[{u'score': 5.5,
u'obj': {u'note': u'note8',
u'ID': 3.0,
u'timestamps': [1381719620.315899]}}]
:param str searchI... | train | https://github.com/dwwkelly/note/blob/b41d5fe1e4a3b67b50285168dd58f903bf219e6c/note/mongo_driver.py#L194-L230 | [
"def get_data_collections(self):\n collections = self.noteDB.collection_names()\n collections.remove(u'system.indexes')\n collections.remove(u'IDs')\n collections.remove(u'label')\n\n return collections\n"
] | class mongoDB(dbBaseClass):
def __init__(self, dbName, uri=None):
"""
:desc: Initialize the database driver
:param str dbName: The name of the database in mongo
:param str uri: The Mongo URI to use
"""
self.dbName = dbName
try:
self.c... |
dwwkelly/note | note/mongo_driver.py | mongoDB.deleteItem | python | def deleteItem(self, itemID):
collections = self.get_data_collections()
query = {"currentMax": {"$exists": True}}
currentMax = self.noteDB["IDs"].find_one(query)['currentMax']
query = {"unusedIDs": {"$exists": True}}
unusedIDs = self.noteDB['IDs'].find_one(query)['unusedIDs']
... | :desc: Deletes item with ID = itemID, takes care of IDs collection
:param itemID: The item ID to delete
:type itemID: int
:raises: ValueError
:returns ID: The ID of the deleted item
:rval: int | train | https://github.com/dwwkelly/note/blob/b41d5fe1e4a3b67b50285168dd58f903bf219e6c/note/mongo_driver.py#L232-L263 | [
"def get_data_collections(self):\n collections = self.noteDB.collection_names()\n collections.remove(u'system.indexes')\n collections.remove(u'IDs')\n collections.remove(u'label')\n\n return collections\n"
] | class mongoDB(dbBaseClass):
def __init__(self, dbName, uri=None):
"""
:desc: Initialize the database driver
:param str dbName: The name of the database in mongo
:param str uri: The Mongo URI to use
"""
self.dbName = dbName
try:
self.c... |
dwwkelly/note | note/mongo_driver.py | mongoDB.getDone | python | def getDone(self, done):
doneItems = self.noteDB['todo'] \
.find({"done": done}) \
.sort("date", pymongo.DESCENDING)
IDs = [ii['ID'] for ii in doneItems]
return IDs | :desc: Fetches a list of all the done ToDs
:param bool done: done or undone?
:returns: A list of matching IDs
:rval: list | train | https://github.com/dwwkelly/note/blob/b41d5fe1e4a3b67b50285168dd58f903bf219e6c/note/mongo_driver.py#L265-L277 | null | class mongoDB(dbBaseClass):
def __init__(self, dbName, uri=None):
"""
:desc: Initialize the database driver
:param str dbName: The name of the database in mongo
:param str uri: The Mongo URI to use
"""
self.dbName = dbName
try:
self.c... |
dwwkelly/note | note/mongo_driver.py | mongoDB.makeBackupFile | python | def makeBackupFile(self, dstPath, fileName):
with open(os.devnull) as devnull:
SP.call(['mongodump', '--db', self.dbName, '--out', dstPath],
stdout=devnull,
stderr=devnull)
SP.call(['zip',
'-r',
os.path.jo... | :param str dstPath: The destination path of the backup file
:param str fileName: The filename to use | train | https://github.com/dwwkelly/note/blob/b41d5fe1e4a3b67b50285168dd58f903bf219e6c/note/mongo_driver.py#L279-L296 | null | class mongoDB(dbBaseClass):
def __init__(self, dbName, uri=None):
"""
:desc: Initialize the database driver
:param str dbName: The name of the database in mongo
:param str uri: The Mongo URI to use
"""
self.dbName = dbName
try:
self.c... |
dwwkelly/note | note/mongo_driver.py | mongoDB.getByTime | python | def getByTime(self, startTime=None, endTime=None):
collections = self.get_data_collections()
if startTime is not None:
startTime = float(startTime)
if endTime is not None:
endTime = float(endTime)
if startTime is not None and endTime is not None:
tim... | :desc: Get all the notes in the given time window
:param int startTime: The begining of the window
:param int endTime: The end of the window
:returns: A list of IDs
:ravl: list | train | https://github.com/dwwkelly/note/blob/b41d5fe1e4a3b67b50285168dd58f903bf219e6c/note/mongo_driver.py#L298-L328 | [
"def get_data_collections(self):\n collections = self.noteDB.collection_names()\n collections.remove(u'system.indexes')\n collections.remove(u'IDs')\n collections.remove(u'label')\n\n return collections\n"
] | class mongoDB(dbBaseClass):
def __init__(self, dbName, uri=None):
"""
:desc: Initialize the database driver
:param str dbName: The name of the database in mongo
:param str uri: The Mongo URI to use
"""
self.dbName = dbName
try:
self.c... |
dwwkelly/note | note/mongo_driver.py | mongoDB.verify | python | def verify(self):
collections = self.get_data_collections()
allIDs = []
for coll in collections:
IDs = self.noteDB[coll].find({"ID": {"$exists": True}},
{"ID": 1, "_id": 0})
for ID in IDs:
allIDs.append(int(ID["ID"... | :desc: Verifies the integrity of the database, specifically checks
the values for unusedIDs and currentMax
:returns: A boolean indicating whether the database is valid or
not
:rval: bool | train | https://github.com/dwwkelly/note/blob/b41d5fe1e4a3b67b50285168dd58f903bf219e6c/note/mongo_driver.py#L330-L369 | [
"def get_data_collections(self):\n collections = self.noteDB.collection_names()\n collections.remove(u'system.indexes')\n collections.remove(u'IDs')\n collections.remove(u'label')\n\n return collections\n"
] | class mongoDB(dbBaseClass):
def __init__(self, dbName, uri=None):
"""
:desc: Initialize the database driver
:param str dbName: The name of the database in mongo
:param str uri: The Mongo URI to use
"""
self.dbName = dbName
try:
self.c... |
dwwkelly/note | note/client.py | Note_Client.Send | python | def Send(self, msg):
if 'type' not in msg:
return
self.sock.send(json.dumps(msg))
msg = self.sock.recv()
return msg | Add a note to the database on the server
:param msg: The text of the note.
:type msg: str
:param tags: A list of tags to associate with the note.
:type tags: list
:returns: The message from the server
:rtype: str | train | https://github.com/dwwkelly/note/blob/b41d5fe1e4a3b67b50285168dd58f903bf219e6c/note/client.py#L26-L41 | null | class Note_Client(object):
""" This is the client side library to interact with the note server """
def __init__(self):
"""
Initialize the client, mostly ZMQ setup
"""
self.server_addr = "127.0.0.1"
self.server_port = 5500 # FIXME - get from config file
self.s... |
dwwkelly/note | note/server.py | Note_Server.Run | python | def Run(self):
while True:
try:
events = self.poller.poll()
except KeyboardInterrupt:
self.context.destroy()
sys.exit()
self.Handle_Events(events) | Wait for clients to connect and service them
:returns: None | train | https://github.com/dwwkelly/note/blob/b41d5fe1e4a3b67b50285168dd58f903bf219e6c/note/server.py#L31-L46 | [
"def Handle_Events(self, events):\n \"\"\"\n Handle events from poll()\n\n :events: A list of tuples form zmq.poll()\n :type events: list\n :returns: None\n\n \"\"\"\n for e in events:\n\n sock = e[0]\n event_type = e[1]\n\n if event_type == zmq.POLLIN:\n msg = s... | class Note_Server(object):
""" """
def __init__(self, db_name='note'):
"""
"""
self.zmq_threads = 1
self.zmq_addr = "127.0.0.1"
self.zmq_port = 5500 # FIXME - get from config file
self.zmq_uri = "tcp://" + self.zmq_addr + ":" + str(self.zmq_port)
self... |
dwwkelly/note | note/server.py | Note_Server.Handle_Events | python | def Handle_Events(self, events):
for e in events:
sock = e[0]
event_type = e[1]
if event_type == zmq.POLLIN:
msg = sock.recv()
reply = self.Handle_Receive(msg)
sock.send(reply)
elif event_type == zmq.POLLOUT:
... | Handle events from poll()
:events: A list of tuples form zmq.poll()
:type events: list
:returns: None | train | https://github.com/dwwkelly/note/blob/b41d5fe1e4a3b67b50285168dd58f903bf219e6c/note/server.py#L48-L71 | [
"def Handle_Receive(self, msg):\n \"\"\"\n Handle a received message.\n\n :param msg: the received message\n :type msg: str\n :returns: The message to reply with\n :rtype: str\n \"\"\"\n\n msg = self.Check_Message(msg)\n msg_type = msg['type']\n\n f_name = \"Handle_{0}\".format(msg_typ... | class Note_Server(object):
""" """
def __init__(self, db_name='note'):
"""
"""
self.zmq_threads = 1
self.zmq_addr = "127.0.0.1"
self.zmq_port = 5500 # FIXME - get from config file
self.zmq_uri = "tcp://" + self.zmq_addr + ":" + str(self.zmq_port)
self... |
dwwkelly/note | note/server.py | Note_Server.Handle_Receive | python | def Handle_Receive(self, msg):
msg = self.Check_Message(msg)
msg_type = msg['type']
f_name = "Handle_{0}".format(msg_type)
try:
f = getattr(self, f_name)
except AttributeError:
f = self.Handle_ERROR(msg)
reply = f(msg)
return reply | Handle a received message.
:param msg: the received message
:type msg: str
:returns: The message to reply with
:rtype: str | train | https://github.com/dwwkelly/note/blob/b41d5fe1e4a3b67b50285168dd58f903bf219e6c/note/server.py#L73-L93 | [
"def Check_Message(self, msg):\n \"\"\"\n Verifies the message is a valid note message\n \"\"\"\n\n msg = json.loads(msg)\n return msg\n",
"def Handle_ERROR(self, msg):\n reply = {\"status\": \"ERROR\",\n \"object\": {\"msg\": \"unknown command\"},\n \"type\": \"ERROR MSG... | class Note_Server(object):
""" """
def __init__(self, db_name='note'):
"""
"""
self.zmq_threads = 1
self.zmq_addr = "127.0.0.1"
self.zmq_port = 5500 # FIXME - get from config file
self.zmq_uri = "tcp://" + self.zmq_addr + ":" + str(self.zmq_port)
self... |
dwwkelly/note | note/server.py | Note_Server.Handle_Search | python | def Handle_Search(self, msg):
search_term = msg['object']['searchTerm']
results = self.db.searchForItem(search_term)
reply = {"status": "OK",
"type": "search",
"object": {
"received search": msg['object']['searchTerm'],
... | Handle a search.
:param msg: the received search
:type msg: dict
:returns: The message to reply with
:rtype: str | train | https://github.com/dwwkelly/note/blob/b41d5fe1e4a3b67b50285168dd58f903bf219e6c/note/server.py#L103-L123 | null | class Note_Server(object):
""" """
def __init__(self, db_name='note'):
"""
"""
self.zmq_threads = 1
self.zmq_addr = "127.0.0.1"
self.zmq_port = 5500 # FIXME - get from config file
self.zmq_uri = "tcp://" + self.zmq_addr + ":" + str(self.zmq_port)
self... |
dwwkelly/note | note/server.py | Note_Server.Handle_Note | python | def Handle_Note(self, msg):
note_text = msg['object']['note']
note_tags = msg['object']['tags']
if 'ID' in msg['object']:
note_id = msg['object']['ID']
self.db.addItem("note", {"note": note_text,
"tags": note_tags},
... | Handle a new note.
:param msg: the received note
:type msg: dict
:returns: The message to reply with
:rtype: str | train | https://github.com/dwwkelly/note/blob/b41d5fe1e4a3b67b50285168dd58f903bf219e6c/note/server.py#L125-L154 | null | class Note_Server(object):
""" """
def __init__(self, db_name='note'):
"""
"""
self.zmq_threads = 1
self.zmq_addr = "127.0.0.1"
self.zmq_port = 5500 # FIXME - get from config file
self.zmq_uri = "tcp://" + self.zmq_addr + ":" + str(self.zmq_port)
self... |
dwwkelly/note | note/server.py | Note_Server.Handle_Label | python | def Handle_Label(self, msg):
obj = msg['object']
if 'name' not in obj or 'id' not in obj:
r_msg = {'status': 'ERROR',
'type': 'Label',
'object': {'msg': 'improper request'}}
return json.dumps(r_msg)
label_name = obj['name']
... | :desc: Set a label
:param dict msg: The message received from the client
:rval: str
:returns: A status message (JSON serialized to a string) | train | https://github.com/dwwkelly/note/blob/b41d5fe1e4a3b67b50285168dd58f903bf219e6c/note/server.py#L345-L373 | null | class Note_Server(object):
""" """
def __init__(self, db_name='note'):
"""
"""
self.zmq_threads = 1
self.zmq_addr = "127.0.0.1"
self.zmq_port = 5500 # FIXME - get from config file
self.zmq_uri = "tcp://" + self.zmq_addr + ":" + str(self.zmq_port)
self... |
dwwkelly/note | note/server.py | Note_Server.Handle_Delete_Label | python | def Handle_Delete_Label(self, msg):
try:
label_name = msg['object']['label']
except KeyError:
r_msg = {'status': 'ERROR',
'type': 'Delete_Label',
'object': {'msg': 'improper request'}}
return json.dumps(r_msg)
else:
... | :desc: Deletes a label
:param dic msg: The message with the instruction and the label
name to delete
:rval: str
:returns: The message from the database | train | https://github.com/dwwkelly/note/blob/b41d5fe1e4a3b67b50285168dd58f903bf219e6c/note/server.py#L375-L395 | null | class Note_Server(object):
""" """
def __init__(self, db_name='note'):
"""
"""
self.zmq_threads = 1
self.zmq_addr = "127.0.0.1"
self.zmq_port = 5500 # FIXME - get from config file
self.zmq_uri = "tcp://" + self.zmq_addr + ":" + str(self.zmq_port)
self... |
jespino/anillo | anillo/handlers/routing.py | url | python | def url(match, handler=None, methods=None, defaults=None,
redirect_to=None, build_only=False, name=None, **kwargs):
assert isinstance(match, str), "match parameter should be string."
assert handler or redirect_to, "you should specify handler or redirect_to for the url"
if isinstance(methods, str):
... | Simple helper for build a url, and return anillo
url spec hash map (dictionary)
It can be used in this way:
urls = [
url("/<int:year>", index, methods=["get", "post"]),
url("/<int:year>", index, methods=["get", "post"])
]
This is a prefered way to define one url.
:return: The... | train | https://github.com/jespino/anillo/blob/901a84fd2b4fa909bc06e8bd76090457990576a7/anillo/handlers/routing.py#L100-L133 | null | """
Url routing module.
This module provides to anillo nanoframework a handler that manages the
url matching and routing. It is hightly inspired by clojure's compojure
library and other similar ones.
This is a little example on how you can define routes:
urls = [
url("/<int:year>", index, methods=["get", "po... |
jespino/anillo | anillo/handlers/routing.py | _build_rules | python | def _build_rules(specs):
for spec in specs:
if "context" in spec:
yield Context(spec["context"], list(_build_rules(spec.get("routes", []))))
else:
rulespec = spec.copy()
match = rulespec.pop("match")
name = rulespec.pop("name")
yield Rule(m... | Adapts the list of anillo urlmapping specs into
a list of werkzeug rules or rules subclasses.
:param list specs: A list of anillo url mapping specs.
:return: generator | train | https://github.com/jespino/anillo/blob/901a84fd2b4fa909bc06e8bd76090457990576a7/anillo/handlers/routing.py#L158-L172 | [
"def _build_rules(specs):\n \"\"\"Adapts the list of anillo urlmapping specs into\n a list of werkzeug rules or rules subclasses.\n\n :param list specs: A list of anillo url mapping specs.\n :return: generator\n \"\"\"\n for spec in specs:\n if \"context\" in spec:\n yield Contex... | """
Url routing module.
This module provides to anillo nanoframework a handler that manages the
url matching and routing. It is hightly inspired by clojure's compojure
library and other similar ones.
This is a little example on how you can define routes:
urls = [
url("/<int:year>", index, methods=["get", "po... |
jespino/anillo | anillo/handlers/routing.py | _build_urlmapping | python | def _build_urlmapping(urls, strict_slashes=False, **kwargs):
rules = _build_rules(urls)
return Map(rules=list(rules), strict_slashes=strict_slashes, **kwargs) | Convers the anillo urlmappings list into
werkzeug Map instance.
:return: a werkzeug Map instance
:rtype: Map | train | https://github.com/jespino/anillo/blob/901a84fd2b4fa909bc06e8bd76090457990576a7/anillo/handlers/routing.py#L175-L184 | [
"def _build_rules(specs):\n \"\"\"Adapts the list of anillo urlmapping specs into\n a list of werkzeug rules or rules subclasses.\n\n :param list specs: A list of anillo url mapping specs.\n :return: generator\n \"\"\"\n for spec in specs:\n if \"context\" in spec:\n yield Contex... | """
Url routing module.
This module provides to anillo nanoframework a handler that manages the
url matching and routing. It is hightly inspired by clojure's compojure
library and other similar ones.
This is a little example on how you can define routes:
urls = [
url("/<int:year>", index, methods=["get", "po... |
jespino/anillo | anillo/handlers/routing.py | default_match_error_handler | python | def default_match_error_handler(exc):
if isinstance(exc, NotFound):
return http.NotFound()
elif isinstance(exc, MethodNotAllowed):
return http.MethodNotAllowed()
elif isinstance(exc, RequestRedirect):
return redirect(exc.new_url)
else:
raise exc | Default implementation for match error handling. | train | https://github.com/jespino/anillo/blob/901a84fd2b4fa909bc06e8bd76090457990576a7/anillo/handlers/routing.py#L187-L198 | null | """
Url routing module.
This module provides to anillo nanoframework a handler that manages the
url matching and routing. It is hightly inspired by clojure's compojure
library and other similar ones.
This is a little example on how you can define routes:
urls = [
url("/<int:year>", index, methods=["get", "po... |
jespino/anillo | anillo/serving.py | run_simple | python | def run_simple(app, *, host="127.0.0.1", port=500,
debug=True, autoreload=True, **kwargs):
kwargs.setdefault("use_evalex", debug)
return serving.run_simple(host, port, app,
use_debugger=debug,
use_reloader=autoreload,
... | Start a WSGI application.
Optional features include a reloader, multithreading and fork support. | train | https://github.com/jespino/anillo/blob/901a84fd2b4fa909bc06e8bd76090457990576a7/anillo/serving.py#L4-L13 | null | from werkzeug import serving
|
jespino/anillo | anillo/middlewares/session.py | wrap_session | python | def wrap_session(func=None, *, storage=MemoryStorage):
if func is None:
return functools.partial(wrap_session, storage=storage)
# Initialize the storage
storage = storage()
def wrapper(request, *args, **kwargs):
session_key = storage.get_session_key(request)
request.session = ... | A middleware that adds the session management to the
request.
This middleware optionally accepts a `storage` keyword
only parameter for provide own session storage
implementation. If it is not provided, the in memory
session storage will be used.
:param storage: A storage factory/constructor.
... | train | https://github.com/jespino/anillo/blob/901a84fd2b4fa909bc06e8bd76090457990576a7/anillo/middlewares/session.py#L30-L59 | null | import uuid
import functools
class MemoryStorage:
def __init__(self, cookie_name="session-id"):
self.cookie_name = cookie_name
self.data = {}
def get_session_key(self, request):
session_key = request.cookies.get(self.cookie_name, {}).get('value', None)
if session_key is None:
... |
jespino/anillo | anillo/middlewares/params.py | wrap_form_params | python | def wrap_form_params(func):
@functools.wraps(func)
def wrapper(request, *args, **kwargs):
ctype, pdict = parse_header(request.headers.get('Content-Type', ''))
if ctype == "application/x-www-form-urlencoded":
params = {}
for key, value in parse_qs(request.body.decode("utf... | A middleware that parses the url-encoded body and attach
the result to the request `form_params` attribute.
This middleware also merges the parsed value with the existing
`params` attribute in same way as `wrap_query_params` is doing. | train | https://github.com/jespino/anillo/blob/901a84fd2b4fa909bc06e8bd76090457990576a7/anillo/middlewares/params.py#L8-L31 | null | import functools
from anillo.utils.common import merge_dicts
from urllib.parse import parse_qs
from cgi import parse_header
def wrap_query_params(func):
"""
A middleware that parses the urlencoded params from the querystring
and attach it to the request `query_params` attribute.
This middleware als... |
jespino/anillo | anillo/middlewares/params.py | wrap_query_params | python | def wrap_query_params(func):
@functools.wraps(func)
def wrapper(request, *args, **kwargs):
params = {}
for key, value in parse_qs(request.query_string.decode("utf-8")).items():
if len(value) == 1:
params[key] = value[0]
else:
params[key] =... | A middleware that parses the urlencoded params from the querystring
and attach it to the request `query_params` attribute.
This middleware also merges the parsed value with the existing
`params` attribute in same way as `wrap_form_params` is doing. | train | https://github.com/jespino/anillo/blob/901a84fd2b4fa909bc06e8bd76090457990576a7/anillo/middlewares/params.py#L34-L55 | null | import functools
from anillo.utils.common import merge_dicts
from urllib.parse import parse_qs
from cgi import parse_header
def wrap_form_params(func):
"""
A middleware that parses the url-encoded body and attach
the result to the request `form_params` attribute.
This middleware also merges the pars... |
jespino/anillo | anillo/middlewares/multipart_params.py | wrap_multipart_params | python | def wrap_multipart_params(func):
def wrapper(request, *args, **kwargs):
ctype, pdict = parse_header(request.headers.get('Content-Type', ''))
if ctype == "multipart/form-data":
if isinstance(pdict['boundary'], str):
pdict['boundary'] = pdict['boundary'].encode()
... | A middleware that parses the multipart request body and adds the
parsed content to the `multipart_params` attribute.
This middleware also merges the parsed value with the existing
`params` attribute in same way as `wrap_form_params` is doing. | train | https://github.com/jespino/anillo/blob/901a84fd2b4fa909bc06e8bd76090457990576a7/anillo/middlewares/multipart_params.py#L8-L36 | null | from cgi import parse_header
from io import BytesIO
from anillo.utils.common import merge_dicts
from anillo.utils.multipart import MultipartParser
|
jespino/anillo | anillo/middlewares/json.py | wrap_json | python | def wrap_json(func=None, *, encoder=json.JSONEncoder, preserve_raw_body=False):
if func is None:
return functools.partial(
wrap_json,
encoder=encoder,
preserve_raw_body=preserve_raw_body
)
wrapped_func = wrap_json_body(func, preserve_raw_body=preserve_raw_bo... | A middleware that parses the body of json requests and
encodes the json responses.
NOTE: this middleware exists just for backward compatibility,
but it has some limitations in terms of response body encoding
because it only accept list or dictionary outputs and json
specification allows store other... | train | https://github.com/jespino/anillo/blob/901a84fd2b4fa909bc06e8bd76090457990576a7/anillo/middlewares/json.py#L9-L32 | [
"def wrap_json_body(func=None, *, preserve_raw_body=False):\n \"\"\"\n A middleware that parses the body of json requests and\n add it to the request under the `body` attribute (replacing\n the previous value). Can preserve the original value in\n a new attribute `raw_body` if you give preserve_raw_b... | try:
import simplejson as json
except ImportError:
import json
import functools
from cgi import parse_header
def wrap_json_body(func=None, *, preserve_raw_body=False):
"""
A middleware that parses the body of json requests and
add it to the request under the `body` attribute (replacing
the pr... |
jespino/anillo | anillo/middlewares/json.py | wrap_json_body | python | def wrap_json_body(func=None, *, preserve_raw_body=False):
if func is None:
return functools.partial(
wrap_json_body,
preserve_raw_body=preserve_raw_body
)
@functools.wraps(func)
def wrapper(request, *args, **kwargs):
ctype, pdict = parse_header(request.head... | A middleware that parses the body of json requests and
add it to the request under the `body` attribute (replacing
the previous value). Can preserve the original value in
a new attribute `raw_body` if you give preserve_raw_body=True. | train | https://github.com/jespino/anillo/blob/901a84fd2b4fa909bc06e8bd76090457990576a7/anillo/middlewares/json.py#L35-L57 | null | try:
import simplejson as json
except ImportError:
import json
import functools
from cgi import parse_header
def wrap_json(func=None, *, encoder=json.JSONEncoder, preserve_raw_body=False):
"""
A middleware that parses the body of json requests and
encodes the json responses.
NOTE: this middle... |
jespino/anillo | anillo/middlewares/json.py | wrap_json_params | python | def wrap_json_params(func):
@functools.wraps(func)
def wrapper(request, *args, **kwargs):
ctype, pdict = parse_header(request.headers.get('Content-Type', ''))
if ctype == "application/json":
request.params = json.loads(request.body.decode("utf-8")) if request.body else None
... | A middleware that parses the body of json requests and
add it to the request under the `params` key. | train | https://github.com/jespino/anillo/blob/901a84fd2b4fa909bc06e8bd76090457990576a7/anillo/middlewares/json.py#L60-L72 | null | try:
import simplejson as json
except ImportError:
import json
import functools
from cgi import parse_header
def wrap_json(func=None, *, encoder=json.JSONEncoder, preserve_raw_body=False):
"""
A middleware that parses the body of json requests and
encodes the json responses.
NOTE: this middle... |
jespino/anillo | anillo/middlewares/json.py | wrap_json_response | python | def wrap_json_response(func=None, *, encoder=json.JSONEncoder):
if func is None:
return functools.partial(wrap_json_response, encoder=encoder)
@functools.wraps(func)
def wrapper(request, *args, **kwargs):
response = func(request, *args, **kwargs)
if "Content-Type" in response.head... | A middleware that encodes in json the response body in case
of that the "Content-Type" header is "application/json".
This middlware accepts and optional `encoder` parameter, that
allow to the user specify its own json encoder class. | train | https://github.com/jespino/anillo/blob/901a84fd2b4fa909bc06e8bd76090457990576a7/anillo/middlewares/json.py#L75-L97 | null | try:
import simplejson as json
except ImportError:
import json
import functools
from cgi import parse_header
def wrap_json(func=None, *, encoder=json.JSONEncoder, preserve_raw_body=False):
"""
A middleware that parses the body of json requests and
encodes the json responses.
NOTE: this middle... |
jespino/anillo | anillo/middlewares/cors.py | wrap_cors | python | def wrap_cors(func=None, *, allow_origin='*', allow_headers=DEFAULT_HEADERS):
if func is None:
return functools.partial(wrap_cors,
allow_origin=allow_origin,
allow_headers=allow_headers)
_allow_headers = ", ".join(allow_headers)
@f... | A middleware that allow CORS calls, by adding the
headers Access-Control-Allow-Origin and Access-Control-Allow-Headers.
This middlware accepts two optional parameters `allow_origin` and
`allow_headers` for customization of the headers values. By default
will be `*` and a set of `[Origin, X-Requested-Wit... | train | https://github.com/jespino/anillo/blob/901a84fd2b4fa909bc06e8bd76090457990576a7/anillo/middlewares/cors.py#L6-L34 | null | import functools
DEFAULT_HEADERS = frozenset(["origin", "x-requested-with", "content-type", "accept"])
|
jespino/anillo | anillo/app.py | application | python | def application(handler, adapter_cls=WerkzeugAdapter):
adapter = adapter_cls()
def wrapper(environ, start_response):
request = adapter.to_request(environ)
response = handler(request)
response_func = adapter.from_response(response)
return response_func(environ, start_response)
... | Converts an anillo function based handler in a
wsgi compiliant application function.
:param adapter_cls: the wsgi adapter implementation (default: wekrzeug)
:returns: wsgi function
:rtype: callable | train | https://github.com/jespino/anillo/blob/901a84fd2b4fa909bc06e8bd76090457990576a7/anillo/app.py#L4-L20 | null | from anillo.adapters.werkzeug import WerkzeugAdapter
__all__ = ["application"]
|
jespino/anillo | anillo/utils/multipart.py | copy_file | python | def copy_file(stream, target, maxread=-1, buffer_size=2*16):
''' Read from :stream and write to :target until :maxread or EOF. '''
size, read = 0, stream.read
while 1:
to_read = buffer_size if maxread < 0 else min(buffer_size, maxread-size)
part = read(to_read)
if not part:
... | Read from :stream and write to :target until :maxread or EOF. | train | https://github.com/jespino/anillo/blob/901a84fd2b4fa909bc06e8bd76090457990576a7/anillo/utils/multipart.py#L102-L111 | null | # -*- coding: utf-8 -*-
'''
Parser for multipart/form-data
==============================
This module provides a parser for the multipart/form-data format. It can read
from a file, a socket or a WSGI environment. The parser can be used to replace
cgi.FieldStorage (without the bugs) and works with Python 3.x.
Licence ... |
jespino/anillo | anillo/utils/multipart.py | parse_form_data | python | def parse_form_data(environ, charset='utf8', strict=False, **kw):
''' Parse form data from an environ dict and return a (forms, files) tuple.
Both tuple values are dictionaries with the form-field name as a key
(unicode) and lists as values (multiple values per key are possible).
The forms-d... | Parse form data from an environ dict and return a (forms, files) tuple.
Both tuple values are dictionaries with the form-field name as a key
(unicode) and lists as values (multiple values per key are possible).
The forms-dictionary contains form-field values as unicode strings.
The files... | train | https://github.com/jespino/anillo/blob/901a84fd2b4fa909bc06e8bd76090457990576a7/anillo/utils/multipart.py#L381-L433 | null | # -*- coding: utf-8 -*-
'''
Parser for multipart/form-data
==============================
This module provides a parser for the multipart/form-data format. It can read
from a file, a socket or a WSGI environment. The parser can be used to replace
cgi.FieldStorage (without the bugs) and works with Python 3.x.
Licence ... |
jespino/anillo | anillo/utils/multipart.py | MultipartParser.get | python | def get(self, name, default=None):
''' Return the first part with that name or a default value (None). '''
for part in self:
if name == part.name:
return part
return default | Return the first part with that name or a default value (None). | train | https://github.com/jespino/anillo/blob/901a84fd2b4fa909bc06e8bd76090457990576a7/anillo/utils/multipart.py#L201-L206 | null | class MultipartParser(object):
def __init__(self, stream, boundary, content_length=-1,
disk_limit=2**30, mem_limit=2**20, memfile_limit=2**18,
buffer_size=2**16, charset='latin1'):
''' Parse a multipart/form-data byte stream. This object is an iterator
over the... |
jespino/anillo | anillo/utils/multipart.py | MultipartParser._lineiter | python | def _lineiter(self):
''' Iterate over a binary file-like object line by line. Each line is
returned as a (line, line_ending) tuple. If the line does not fit
into self.buffer_size, line_ending is empty and the rest of the line
is returned with the next iteration.
'''
... | Iterate over a binary file-like object line by line. Each line is
returned as a (line, line_ending) tuple. If the line does not fit
into self.buffer_size, line_ending is empty and the rest of the line
is returned with the next iteration. | train | https://github.com/jespino/anillo/blob/901a84fd2b4fa909bc06e8bd76090457990576a7/anillo/utils/multipart.py#L212-L248 | null | class MultipartParser(object):
def __init__(self, stream, boundary, content_length=-1,
disk_limit=2**30, mem_limit=2**20, memfile_limit=2**18,
buffer_size=2**16, charset='latin1'):
''' Parse a multipart/form-data byte stream. This object is an iterator
over the... |
jespino/anillo | anillo/utils/multipart.py | MultipartPart.value | python | def value(self):
''' Data decoded with the specified charset '''
pos = self.file.tell()
self.file.seek(0)
val = self.file.read()
self.file.seek(pos)
return val.decode(self.charset) | Data decoded with the specified charset | train | https://github.com/jespino/anillo/blob/901a84fd2b4fa909bc06e8bd76090457990576a7/anillo/utils/multipart.py#L358-L364 | null | class MultipartPart(object):
def __init__(self, buffer_size=2**16, memfile_limit=2**18, charset='latin1'):
self.headerlist = []
self.headers = None
self.file = False
self.size = 0
self._buf = b''
self.disposition, self.name, self.filename = None, None, None
s... |
vmalloc/dessert | dessert/rewrite.py | _make_rewritten_pyc | python | def _make_rewritten_pyc(state, fn, pyc, co):
if sys.platform.startswith("win"):
# Windows grants exclusive access to open files and doesn't have atomic
# rename, so just write into the final file.
_write_pyc(state, co, fn, pyc)
else:
# When not on windows, assume rename is atomic... | Try to dump rewritten code to *pyc*. | train | https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/rewrite.py#L325-L336 | null | """Rewrite assertion AST to produce nice error messages"""
import ast
import _ast
import errno
import imp
import itertools
import logging
import os
import re
import struct
import sys
import types
from fnmatch import fnmatch
from munch import Munch
import marshal
import py
from . import util
from .util import format_... |
vmalloc/dessert | dessert/rewrite.py | _read_pyc | python | def _read_pyc(source, pyc):
try:
fp = open(pyc, "rb")
except IOError:
return None
try:
try:
mtime = int(os.stat(source).st_mtime)
data = fp.read(8)
except EnvironmentError:
return None
# Check for invalid or out of date pyc file.
... | Possibly read a pytest pyc containing rewritten code.
Return rewritten code if successful or None if not. | train | https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/rewrite.py#L338-L363 | null | """Rewrite assertion AST to produce nice error messages"""
import ast
import _ast
import errno
import imp
import itertools
import logging
import os
import re
import struct
import sys
import types
from fnmatch import fnmatch
from munch import Munch
import marshal
import py
from . import util
from .util import format_... |
vmalloc/dessert | dessert/rewrite.py | _saferepr | python | def _saferepr(obj):
repr = py.io.saferepr(obj)
if py.builtin._istext(repr):
t = py.builtin.text
else:
t = py.builtin.bytes
return repr.replace(t("\n"), t("\\n")) | Get a safe repr of an object for assertion error messages.
The assertion formatting (util.format_explanation()) requires
newlines to be escaped since they are a special character for it.
Normally assertion.util.format_explanation() does this but for a
custom repr it is possible to contain one of the sp... | train | https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/rewrite.py#L371-L387 | null | """Rewrite assertion AST to produce nice error messages"""
import ast
import _ast
import errno
import imp
import itertools
import logging
import os
import re
import struct
import sys
import types
from fnmatch import fnmatch
from munch import Munch
import marshal
import py
from . import util
from .util import format_... |
vmalloc/dessert | dessert/rewrite.py | _format_assertmsg | python | def _format_assertmsg(obj):
# reprlib appears to have a bug which means that if a string
# contains a newline it gets escaped, however if an object has a
# .__repr__() which contains newlines it does not get escaped.
# However in either case we want to preserve the newline.
if py.builtin._istext(obj... | Format the custom assertion message given.
For strings this simply replaces newlines with '\n~' so that
util.format_explanation() will preserve them instead of escaping
newlines. For other objects py.io.saferepr() is used first. | train | https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/rewrite.py#L389-L414 | null | """Rewrite assertion AST to produce nice error messages"""
import ast
import _ast
import errno
import imp
import itertools
import logging
import os
import re
import struct
import sys
import types
from fnmatch import fnmatch
from munch import Munch
import marshal
import py
from . import util
from .util import format_... |
vmalloc/dessert | dessert/rewrite.py | set_location | python | def set_location(node, lineno, col_offset):
def _fix(node, lineno, col_offset):
if "lineno" in node._attributes:
node.lineno = lineno
if "col_offset" in node._attributes:
node.col_offset = col_offset
for child in ast.iter_child_nodes(node):
_fix(child, lin... | Set node location information recursively. | train | https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/rewrite.py#L488-L498 | [
"def _fix(node, lineno, col_offset):\n if \"lineno\" in node._attributes:\n node.lineno = lineno\n if \"col_offset\" in node._attributes:\n node.col_offset = col_offset\n for child in ast.iter_child_nodes(node):\n _fix(child, lineno, col_offset)\n"
] | """Rewrite assertion AST to produce nice error messages"""
import ast
import _ast
import errno
import imp
import itertools
import logging
import os
import re
import struct
import sys
import types
from fnmatch import fnmatch
from munch import Munch
import marshal
import py
from . import util
from .util import format_... |
vmalloc/dessert | dessert/rewrite.py | AssertionRewritingHook.mark_rewrite | python | def mark_rewrite(self, *names):
already_imported = set(names).intersection(set(sys.modules))
if already_imported:
for name in already_imported:
if name not in self._rewritten_names:
self._warn_already_imported(name)
self._must_rewrite.update(names) | Mark import names as needing to be re-written.
The named module or package as well as any nested modules will
be re-written on import. | train | https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/rewrite.py#L163-L174 | [
"def _warn_already_imported(self, name):\n self.config.warn(\n 'P1',\n 'Module already imported so can not be re-written: %s' % name)\n"
] | class AssertionRewritingHook(object):
"""PEP302 Import hook which rewrites asserts."""
def __init__(self):
self.modules = {}
self.session = AssertRewritingSession()
self.state = Munch()
self.fnpats = []
self._rewritten_names = set()
self._register_with_pkg_resour... |
vmalloc/dessert | dessert/rewrite.py | AssertionRewritingHook._register_with_pkg_resources | python | def _register_with_pkg_resources(cls):
try:
import pkg_resources
# access an attribute in case a deferred importer is present
pkg_resources.__name__
except ImportError:
return
# Since pytest tests are always located in the file system, the
... | Ensure package resources can be loaded from this loader. May be called
multiple times, as the operation is idempotent. | train | https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/rewrite.py#L216-L230 | null | class AssertionRewritingHook(object):
"""PEP302 Import hook which rewrites asserts."""
def __init__(self):
self.modules = {}
self.session = AssertRewritingSession()
self.state = Munch()
self.fnpats = []
self._rewritten_names = set()
self._register_with_pkg_resour... |
vmalloc/dessert | dessert/rewrite.py | AssertionRewriter.run | python | def run(self, mod):
if not mod.body:
# Nothing to do.
return
# Insert some special imports at the top of the module but after any
# docstrings and __future__ imports.
aliases = [ast.alias(py.builtin.builtins.__name__, "@py_builtins"),
ast.alias(... | Find all assert statements in *mod* and rewrite them. | train | https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/rewrite.py#L508-L557 | null | class AssertionRewriter(ast.NodeVisitor):
def __init__(self, module_path, config):
super(AssertionRewriter, self).__init__()
self.module_path = module_path
self.config = config
def variable(self):
"""Get a new variable."""
# Use a character invalid in python identifier... |
vmalloc/dessert | dessert/rewrite.py | AssertionRewriter.variable | python | def variable(self):
# Use a character invalid in python identifiers to avoid clashing.
name = "@py_assert" + str(next(self.variable_counter))
self.variables.append(name)
return name | Get a new variable. | train | https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/rewrite.py#L559-L564 | null | class AssertionRewriter(ast.NodeVisitor):
def __init__(self, module_path, config):
super(AssertionRewriter, self).__init__()
self.module_path = module_path
self.config = config
def run(self, mod):
"""Find all assert statements in *mod* and rewrite them."""
if not mod.bo... |
vmalloc/dessert | dessert/rewrite.py | AssertionRewriter.assign | python | def assign(self, expr):
name = self.variable()
self.statements.append(ast.Assign([ast.Name(name, ast.Store())], expr))
return ast.Name(name, ast.Load()) | Give *expr* a name. | train | https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/rewrite.py#L566-L570 | [
"def variable(self):\n \"\"\"Get a new variable.\"\"\"\n # Use a character invalid in python identifiers to avoid clashing.\n name = \"@py_assert\" + str(next(self.variable_counter))\n self.variables.append(name)\n return name\n"
] | class AssertionRewriter(ast.NodeVisitor):
def __init__(self, module_path, config):
super(AssertionRewriter, self).__init__()
self.module_path = module_path
self.config = config
def run(self, mod):
"""Find all assert statements in *mod* and rewrite them."""
if not mod.bo... |
vmalloc/dessert | dessert/rewrite.py | AssertionRewriter.helper | python | def helper(self, name, *args):
py_name = ast.Name("@dessert_ar", ast.Load())
attr = ast.Attribute(py_name, "_" + name, ast.Load())
return ast_Call(attr, list(args), []) | Call a helper in this module. | train | https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/rewrite.py#L576-L580 | null | class AssertionRewriter(ast.NodeVisitor):
def __init__(self, module_path, config):
super(AssertionRewriter, self).__init__()
self.module_path = module_path
self.config = config
def run(self, mod):
"""Find all assert statements in *mod* and rewrite them."""
if not mod.bo... |
vmalloc/dessert | dessert/rewrite.py | AssertionRewriter.builtin | python | def builtin(self, name):
builtin_name = ast.Name("@py_builtins", ast.Load())
return ast.Attribute(builtin_name, name, ast.Load()) | Return the builtin called *name*. | train | https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/rewrite.py#L582-L585 | null | class AssertionRewriter(ast.NodeVisitor):
def __init__(self, module_path, config):
super(AssertionRewriter, self).__init__()
self.module_path = module_path
self.config = config
def run(self, mod):
"""Find all assert statements in *mod* and rewrite them."""
if not mod.bo... |
vmalloc/dessert | dessert/rewrite.py | AssertionRewriter.generic_visit | python | def generic_visit(self, node):
assert isinstance(node, ast.expr)
res = self.assign(node)
return res, self.explanation_param(self.display(res)) | Handle expressions we don't have custom code for. | train | https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/rewrite.py#L607-L611 | [
"def assign(self, expr):\n \"\"\"Give *expr* a name.\"\"\"\n name = self.variable()\n self.statements.append(ast.Assign([ast.Name(name, ast.Store())], expr))\n return ast.Name(name, ast.Load())\n",
"def display(self, expr):\n \"\"\"Call py.io.saferepr on the expression.\"\"\"\n return self.helpe... | class AssertionRewriter(ast.NodeVisitor):
def __init__(self, module_path, config):
super(AssertionRewriter, self).__init__()
self.module_path = module_path
self.config = config
def run(self, mod):
"""Find all assert statements in *mod* and rewrite them."""
if not mod.bo... |
vmalloc/dessert | dessert/rewrite.py | AssertionRewriter.visit_Assert | python | def visit_Assert(self, assert_):
if isinstance(assert_.test, ast.Tuple) and self.config is not None:
fslocation = (self.module_path, assert_.lineno)
self.config.warn('R1', 'assertion is always true, perhaps '
'remove parentheses?', fslocation=fslocation)
... | Return the AST statements to replace the ast.Assert instance.
This re-writes the test of an assertion to provide
intermediate values and replace it with an if statement which
raises an assertion error with a detailed explanation in case
the expression is false. | train | https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/rewrite.py#L613-L667 | [
"def _NameConstant(c):\n return ast.Name(str(c), ast.Load())\n",
"def set_location(node, lineno, col_offset):\n \"\"\"Set node location information recursively.\"\"\"\n def _fix(node, lineno, col_offset):\n if \"lineno\" in node._attributes:\n node.lineno = lineno\n if \"col_offs... | class AssertionRewriter(ast.NodeVisitor):
def __init__(self, module_path, config):
super(AssertionRewriter, self).__init__()
self.module_path = module_path
self.config = config
def run(self, mod):
"""Find all assert statements in *mod* and rewrite them."""
if not mod.bo... |
vmalloc/dessert | dessert/rewrite.py | AssertionRewriter.visit_Call_35 | python | def visit_Call_35(self, call):
new_func, func_expl = self.visit(call.func)
arg_expls = []
new_args = []
new_kwargs = []
for arg in call.args:
res, expl = self.visit(arg)
arg_expls.append(expl)
new_args.append(res)
for keyword in call.ke... | visit `ast.Call` nodes on Python3.5 and after | train | https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/rewrite.py#L728-L753 | [
"def assign(self, expr):\n \"\"\"Give *expr* a name.\"\"\"\n name = self.variable()\n self.statements.append(ast.Assign([ast.Name(name, ast.Store())], expr))\n return ast.Name(name, ast.Load())\n",
"def display(self, expr):\n \"\"\"Call py.io.saferepr on the expression.\"\"\"\n return self.helpe... | class AssertionRewriter(ast.NodeVisitor):
def __init__(self, module_path, config):
super(AssertionRewriter, self).__init__()
self.module_path = module_path
self.config = config
def run(self, mod):
"""Find all assert statements in *mod* and rewrite them."""
if not mod.bo... |
vmalloc/dessert | dessert/util.py | format_explanation | python | def format_explanation(explanation, original_msg=None):
if not conf.is_message_introspection_enabled() and original_msg:
return original_msg
explanation = ecu(explanation)
lines = _split_explanation(explanation)
result = _format_lines(lines)
return u('\n').join(result) | This formats an explanation
Normally all embedded newlines are escaped, however there are
three exceptions: \n{, \n} and \n~. The first two are intended
cover nested explanations, see function and attribute explanations
for examples (.visit_Call(), visit_Attribute()). The last one is
for when one... | train | https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/util.py#L33-L48 | [
"def ecu(s):\n try:\n return u(s, 'utf-8', 'replace')\n except TypeError:\n return s\n",
"def _split_explanation(explanation):\n \"\"\"Return a list of individual lines in the explanation\n\n This will return a list of lines split on '\\n{', '\\n}' and '\\n~'.\n Any other newlines wil... | """Utilities for assertion debugging"""
import pprint
import logging
_logger = logging.getLogger(__name__)
import py
from .conf import conf
try:
from collections import Sequence
except ImportError:
Sequence = list
BuiltinAssertionError = py.builtin.builtins.AssertionError
u = py.builtin._totext
# The _reprc... |
vmalloc/dessert | dessert/util.py | _split_explanation | python | def _split_explanation(explanation):
raw_lines = (explanation or u('')).split('\n')
lines = [raw_lines[0]]
for l in raw_lines[1:]:
if l and l[0] in ['{', '}', '~', '>']:
lines.append(l)
else:
lines[-1] += '\\n' + l
return lines | Return a list of individual lines in the explanation
This will return a list of lines split on '\n{', '\n}' and '\n~'.
Any other newlines will be escaped and appear in the line as the
literal '\n' characters. | train | https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/util.py#L51-L65 | null | """Utilities for assertion debugging"""
import pprint
import logging
_logger = logging.getLogger(__name__)
import py
from .conf import conf
try:
from collections import Sequence
except ImportError:
Sequence = list
BuiltinAssertionError = py.builtin.builtins.AssertionError
u = py.builtin._totext
# The _reprc... |
vmalloc/dessert | dessert/util.py | _format_lines | python | def _format_lines(lines):
result = lines[:1]
stack = [0]
stackcnt = [0]
for line in lines[1:]:
if line.startswith('{'):
if stackcnt[-1]:
s = u('and ')
else:
s = u('where ')
stack.append(len(result))
stackcnt[-1] +=... | Format the individual lines
This will replace the '{', '}' and '~' characters of our mini
formatting language with the proper 'where ...', 'and ...' and ' +
...' text, taking care of indentation along the way.
Return a list of formatted lines. | train | https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/util.py#L68-L100 | null | """Utilities for assertion debugging"""
import pprint
import logging
_logger = logging.getLogger(__name__)
import py
from .conf import conf
try:
from collections import Sequence
except ImportError:
Sequence = list
BuiltinAssertionError = py.builtin.builtins.AssertionError
u = py.builtin._totext
# The _reprc... |
vmalloc/dessert | dessert/util.py | assertrepr_compare | python | def assertrepr_compare(config, op, left, right):
width = 80 - 15 - len(op) - 2 # 15 chars indentation, 1 space around op
left_repr = py.io.saferepr(left, maxsize=int(width//2))
right_repr = py.io.saferepr(right, maxsize=width-len(left_repr))
summary = u('%s %s %s') % (ecu(left_repr), op, ecu(right_rep... | Return specialised explanations for some operators/operands | train | https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/util.py#L110-L160 | [
"def ecu(s):\n try:\n return u(s, 'utf-8', 'replace')\n except TypeError:\n return s\n",
"issequence = lambda x: (isinstance(x, (list, tuple, Sequence)) and\n not isinstance(x, basestring))\n",
"istext = lambda x: isinstance(x, basestring)\n"
] | """Utilities for assertion debugging"""
import pprint
import logging
_logger = logging.getLogger(__name__)
import py
from .conf import conf
try:
from collections import Sequence
except ImportError:
Sequence = list
BuiltinAssertionError = py.builtin.builtins.AssertionError
u = py.builtin._totext
# The _reprc... |
vmalloc/dessert | dessert/util.py | _diff_text | python | def _diff_text(left, right, verbose=False):
from difflib import ndiff
explanation = []
if isinstance(left, py.builtin.bytes):
left = u(repr(left)[1:-1]).replace(r'\n', '\n')
if isinstance(right, py.builtin.bytes):
right = u(repr(right)[1:-1]).replace(r'\n', '\n')
if not verbose:
... | Return the explanation for the diff between text or bytes
Unless --verbose is used this will skip leading and trailing
characters which are identical to keep the diff minimal.
If the input are bytes they will be safely converted to text. | train | https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/util.py#L163-L202 | null | """Utilities for assertion debugging"""
import pprint
import logging
_logger = logging.getLogger(__name__)
import py
from .conf import conf
try:
from collections import Sequence
except ImportError:
Sequence = list
BuiltinAssertionError = py.builtin.builtins.AssertionError
u = py.builtin._totext
# The _reprc... |
klmitch/appathy | appathy/types.py | _translators | python | def _translators(attr, kwargs):
# Add translators to a function or class
def decorator(func):
# Make sure we have the attribute
try:
xlators = getattr(func, attr)
except AttributeError:
xlators = {}
setattr(func, attr, xlators)
xlators.update... | Decorator which associates a set of translators (serializers or
deserializers) with a given method. The `attr` parameter
identifies which attribute is being updated. | train | https://github.com/klmitch/appathy/blob/a10aa7d21d38622e984a8fe106ab37114af90dc2/appathy/types.py#L72-L90 | null | # Copyright (C) 2012 by Kevin L. Mitchell <klmitch@mit.edu>
#
# This program is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This p... |
klmitch/appathy | appathy/types.py | register_types | python | def register_types(name, *types):
type_names.setdefault(name, set())
for t in types:
# Redirecting the type
if t in media_types:
type_names[media_types[t]].discard(t)
# Save the mapping
media_types[t] = name
type_names[name].add(t) | Register a short name for one or more content types. | train | https://github.com/klmitch/appathy/blob/a10aa7d21d38622e984a8fe106ab37114af90dc2/appathy/types.py#L141-L154 | null | # Copyright (C) 2012 by Kevin L. Mitchell <klmitch@mit.edu>
#
# This program is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This p... |
klmitch/appathy | appathy/types.py | Translators.get_types | python | def get_types(self):
# Convert translators into a set of content types
content_types = set()
for name in self.translators:
content_types |= type_names[name]
return content_types | Retrieve a set of all recognized content types for this
translator object. | train | https://github.com/klmitch/appathy/blob/a10aa7d21d38622e984a8fe106ab37114af90dc2/appathy/types.py#L58-L69 | null | class Translators(object):
"""
Represent a set of translators. A translator is a serializer or
deserializer, corresponding to a particular return type.
"""
def __init__(self, method, attr_name):
"""
Initialize a set of translators. The translators for a given
method are de... |
klmitch/appathy | appathy/controller.py | action | python | def action(*methods, **kwargs):
# Convert methods to a list, so it can be mutated if needed
methods = list(methods)
# Build up the function attributes
attrs = dict(_wsgi_action=True)
# Get the path...
if methods and methods[0][0] == '/':
# Normalize the path and set the attr
a... | Decorator which marks a method as an action. The first positional
argument identifies a Routes-compatible path for the action
method, which must begin with a '/'. If specified, the remaining
positional arguments identify permitted HTTP methods. The
following keyword arguments are also recognized:
... | train | https://github.com/klmitch/appathy/blob/a10aa7d21d38622e984a8fe106ab37114af90dc2/appathy/controller.py#L318-L395 | [
"def norm_path(path, allow_trailing=True):\n \"\"\"\n Normalize a route path. Ensures that the path begins with a '/'.\n If `allow_trailing` is False, strips off any trailing '/'. Any\n repeated '/' characters in the path will be collapsed into a\n single one.\n \"\"\"\n\n # Collapse slashes\... | # Copyright (C) 2012 by Kevin L. Mitchell <klmitch@mit.edu>
#
# This program is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This p... |
klmitch/appathy | appathy/controller.py | _extends_preproc | python | def _extends_preproc(prefunc):
# Set up the set of functions
functions = dict(preproc=prefunc)
# Set up the wrapper which implements the behavior
@functools.wraps(prefunc)
def wrapper(self, req, **params):
# Run the preprocessor and yield its response
resp = yield functions['prepro... | Decorator which marks a method as a preprocessing extension. The
method must have the same name as the method it is extending.
Extension methods marked with this decorator are called before
calling the action method. They may perform any desired
preprocessing of the request. Note that if an actual va... | train | https://github.com/klmitch/appathy/blob/a10aa7d21d38622e984a8fe106ab37114af90dc2/appathy/controller.py#L434-L506 | null | # Copyright (C) 2012 by Kevin L. Mitchell <klmitch@mit.edu>
#
# This program is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This p... |
klmitch/appathy | appathy/controller.py | Controller._get_action | python | def _get_action(self, action):
# If we don't have an action named that, bail out
if action not in self.wsgi_actions:
return None
# Generate an ActionDescriptor if necessary
if action not in self.wsgi_descriptors:
self.wsgi_descriptors[action] = actions.ActionDes... | Retrieve a descriptor for the named action. Caches
descriptors for efficiency. | train | https://github.com/klmitch/appathy/blob/a10aa7d21d38622e984a8fe106ab37114af90dc2/appathy/controller.py#L221-L239 | null | class Controller(object):
"""
Identifies a resource. All controllers must specify the attribute
`wsgi_name`, which must be unique across all controllers; this
name is used to formulate route names. In addition, controllers
may specify `wsgi_path_prefix`, which is used to prefix all action
meth... |
klmitch/appathy | appathy/controller.py | Controller._route | python | def _route(self, action, method):
# First thing, determine the path for the method
path = method._wsgi_path
methods = None
if path is None:
map_rule = self.wsgi_method_map.get(method.__name__)
if map_rule is None:
# Can't connect this method
... | Given an action method, generates a route for it. | train | https://github.com/klmitch/appathy/blob/a10aa7d21d38622e984a8fe106ab37114af90dc2/appathy/controller.py#L241-L279 | [
"def norm_path(path, allow_trailing=True):\n \"\"\"\n Normalize a route path. Ensures that the path begins with a '/'.\n If `allow_trailing` is False, strips off any trailing '/'. Any\n repeated '/' characters in the path will be collapsed into a\n single one.\n \"\"\"\n\n # Collapse slashes\... | class Controller(object):
"""
Identifies a resource. All controllers must specify the attribute
`wsgi_name`, which must be unique across all controllers; this
name is used to formulate route names. In addition, controllers
may specify `wsgi_path_prefix`, which is used to prefix all action
meth... |
klmitch/appathy | appathy/controller.py | Controller.wsgi_extend | python | def wsgi_extend(self, controller):
# Add/override actions
for key, action in controller.wsgi_actions.items():
# If it's a new action, we'll need to route
if self.wsgi_mapper and key not in self.wsgi_actions:
self._route(key, action)
self.wsgi_actions... | Extends a controller by registering another controller as an
extension of it. All actions defined on the extension
controller have routes generated for them (only if none
already exist) and are made actions of this controller; all
extensions defined on the extension controller are added... | train | https://github.com/klmitch/appathy/blob/a10aa7d21d38622e984a8fe106ab37114af90dc2/appathy/controller.py#L281-L315 | [
"def _route(self, action, method):\n \"\"\"\n Given an action method, generates a route for it.\n \"\"\"\n\n # First thing, determine the path for the method\n path = method._wsgi_path\n methods = None\n if path is None:\n map_rule = self.wsgi_method_map.get(method.__name__)\n if ... | class Controller(object):
"""
Identifies a resource. All controllers must specify the attribute
`wsgi_name`, which must be unique across all controllers; this
name is used to formulate route names. In addition, controllers
may specify `wsgi_path_prefix`, which is used to prefix all action
meth... |
klmitch/appathy | appathy/response.py | ResponseObject._bind | python | def _bind(self, _descriptor):
# If the method has a default code, use it
self._defcode = getattr(_descriptor.method, '_wsgi_code', 200)
# Set up content type and serializer
self.content_type, self.serializer = _descriptor.serializer(self.req) | Bind a ResponseObject to a given action descriptor. This
updates the default HTTP response code and selects the
appropriate content type and serializer for the response. | train | https://github.com/klmitch/appathy/blob/a10aa7d21d38622e984a8fe106ab37114af90dc2/appathy/response.py#L122-L133 | null | class ResponseObject(collections.MutableMapping):
"""
Represent a response object.
"""
response_class = webob.Response
def __init__(self, req, result=None, code=None, headers=None, **kwargs):
"""
Initialize a ResponseObject.
:param req: The request associated with the resp... |
klmitch/appathy | appathy/response.py | ResponseObject._serialize | python | def _serialize(self):
# Do something appropriate if the response object is unbound
if self._defcode is None:
raise exceptions.UnboundResponse()
# Build the response
resp = self.response_class(request=self.req, status=self.code,
headerlist=... | Serialize the ResponseObject. Returns a webob `Response`
object. | train | https://github.com/klmitch/appathy/blob/a10aa7d21d38622e984a8fe106ab37114af90dc2/appathy/response.py#L135-L155 | null | class ResponseObject(collections.MutableMapping):
"""
Represent a response object.
"""
response_class = webob.Response
def __init__(self, req, result=None, code=None, headers=None, **kwargs):
"""
Initialize a ResponseObject.
:param req: The request associated with the resp... |
klmitch/appathy | appathy/response.py | ResponseObject.code | python | def code(self):
if self._code is not None:
return self._code
elif self._defcode is not None:
return self._defcode
return 200 | The HTTP response code associated with this ResponseObject.
If instantiated directly without overriding the code, returns
200 even if the default for the method is some other value.
Can be set or deleted; in the latter case, the default will be
restored. | train | https://github.com/klmitch/appathy/blob/a10aa7d21d38622e984a8fe106ab37114af90dc2/appathy/response.py#L158-L171 | null | class ResponseObject(collections.MutableMapping):
"""
Represent a response object.
"""
response_class = webob.Response
def __init__(self, req, result=None, code=None, headers=None, **kwargs):
"""
Initialize a ResponseObject.
:param req: The request associated with the resp... |
klmitch/appathy | appathy/utils.py | norm_path | python | def norm_path(path, allow_trailing=True):
# Collapse slashes
path = _path_re.sub('/', path)
# Force a leading slash
if path[0] != '/':
path = '/' + path
# Trim a trailing slash
if not allow_trailing and path[-1] == '/':
path = path[:-1]
return path | Normalize a route path. Ensures that the path begins with a '/'.
If `allow_trailing` is False, strips off any trailing '/'. Any
repeated '/' characters in the path will be collapsed into a
single one. | train | https://github.com/klmitch/appathy/blob/a10aa7d21d38622e984a8fe106ab37114af90dc2/appathy/utils.py#L27-L46 | null | # Copyright (C) 2012 by Kevin L. Mitchell <klmitch@mit.edu>
#
# This program is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This p... |
klmitch/appathy | appathy/utils.py | import_egg | python | def import_egg(string):
# Split the string into a distribution and a name
dist, _sep, name = string.partition('#')
return pkg_resources.load_entry_point(dist, 'appathy.controller', name) | Import a controller class from an egg. Uses the entry point group
"appathy.controller". | train | https://github.com/klmitch/appathy/blob/a10aa7d21d38622e984a8fe106ab37114af90dc2/appathy/utils.py#L57-L66 | null | # Copyright (C) 2012 by Kevin L. Mitchell <klmitch@mit.edu>
#
# This program is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This p... |
klmitch/appathy | appathy/utils.py | import_controller | python | def import_controller(string):
# Split out the scheme and the controller descriptor
scheme, sep, controller = string.partition(':')
if sep != ':':
raise ImportError("No loader scheme specified by %r" % string)
# Look up a loader for that scheme
for ep in pkg_resources.iter_entry_points('ap... | Imports the requested controller. Controllers are specified in a
URI-like manner; the scheme is looked up using the entry point
group "appathy.loader". Appathy supports the "call:" and "egg:"
schemes by default. | train | https://github.com/klmitch/appathy/blob/a10aa7d21d38622e984a8fe106ab37114af90dc2/appathy/utils.py#L69-L93 | null | # Copyright (C) 2012 by Kevin L. Mitchell <klmitch@mit.edu>
#
# This program is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This p... |
klmitch/appathy | appathy/application.py | Application.dispatch | python | def dispatch(self, req):
# Grab the request parameters
params = req.environ['wsgiorg.routing_args'][1]
# What controller is authoritative?
controller = params.pop('controller')
# Determine its name
cont_class = controller.__class__
cont_name = "%s:%s" % (cont_c... | Called by the Routes middleware to dispatch the request to the
appropriate controller. If a webob exception is raised, it is
returned; if some other exception is raised, the webob
`HTTPInternalServerError` exception is raised. Otherwise, the
return value of the controller is returned. | train | https://github.com/klmitch/appathy/blob/a10aa7d21d38622e984a8fe106ab37114af90dc2/appathy/application.py#L110-L154 | null | class Application(middleware.RoutesMiddleware):
"""
Provides a PasteDeploy-compatible application class. Resources
and extensions are computed from the configuration; keys beginning
with 'resource.' identify resources, and keys beginning with
'extend.' identify space-separated lists of extensions t... |
klmitch/appathy | appathy/actions.py | ActionDescriptor.deserialize_request | python | def deserialize_request(self, req):
# See if we have a body
if req.content_length == 0:
return None
# Get the primary deserializer
try:
deserializer = self.method.deserializers(req.content_type)
except KeyError:
raise webob.exc.HTTPUnsupporte... | Uses the deserializers declared on the action method and its
extensions to deserialize the request. Returns the result of
the deserialization. Raises `webob.HTTPUnsupportedMediaType`
if the media type of the request is unsupported. | train | https://github.com/klmitch/appathy/blob/a10aa7d21d38622e984a8fe106ab37114af90dc2/appathy/actions.py#L99-L127 | null | class ActionDescriptor(object):
"""
Describes an action on a controller. Binds together the method
which performs the action, along with all the registered
extensions and the desired ResponseObject type.
"""
def __init__(self, method, extensions, resp_type):
"""
Initialize an A... |
klmitch/appathy | appathy/actions.py | ActionDescriptor.serializer | python | def serializer(self, req):
# Select the best match serializer
content_types = self.method.serializers.get_types()
content_type = req.accept.best_match(content_types)
if content_type is None:
raise webob.exc.HTTPNotAcceptable()
# Select the serializer to use
... | Selects and returns the serializer to use, based on the
serializers declared on the action method and its extensions.
The returned content type is selected based on the types
available and the best match generated from the HTTP `Accept`
header. Raises `HTTPNotAcceptable` if the request ... | train | https://github.com/klmitch/appathy/blob/a10aa7d21d38622e984a8fe106ab37114af90dc2/appathy/actions.py#L129-L162 | [
"def get_types(self):\n \"\"\"\n Retrieve a set of all recognized content types for this\n translator object.\n \"\"\"\n\n # Convert translators into a set of content types\n content_types = set()\n for name in self.translators:\n content_types |= type_names[name]\n\n return content_t... | class ActionDescriptor(object):
"""
Describes an action on a controller. Binds together the method
which performs the action, along with all the registered
extensions and the desired ResponseObject type.
"""
def __init__(self, method, extensions, resp_type):
"""
Initialize an A... |
klmitch/appathy | appathy/actions.py | ActionDescriptor.pre_process | python | def pre_process(self, req, params):
post_list = []
# Walk through the list of extensions
for ext in self.extensions:
if ext.isgenerator:
gen = ext(req, **params)
try:
# Perform the preprocessing stage
result = ... | Pre-process the extensions for the action. If any
pre-processing extension yields a value which tests as True,
extension pre-processing aborts and that value is returned;
otherwise, None is returned. Return value is always a tuple,
with the second element of the tuple being a list to f... | train | https://github.com/klmitch/appathy/blob/a10aa7d21d38622e984a8fe106ab37114af90dc2/appathy/actions.py#L164-L196 | [
"def wrap(self, req, result):\n \"\"\"\n Wrap method return results. The return value of the action\n method and of the action extensions is passed through this\n method before being returned to the caller. Instances of\n `webob.Response` are thrown, to abort the rest of action and\n extension p... | class ActionDescriptor(object):
"""
Describes an action on a controller. Binds together the method
which performs the action, along with all the registered
extensions and the desired ResponseObject type.
"""
def __init__(self, method, extensions, resp_type):
"""
Initialize an A... |
klmitch/appathy | appathy/actions.py | ActionDescriptor.post_process | python | def post_process(self, post_list, req, resp, params):
# Walk through the post-processing extensions
for ext in post_list:
if inspect.isgenerator(ext):
try:
result = ext.send(resp)
except StopIteration:
# Expected, but n... | Post-process the extensions for the action. If any
post-processing extension (specified by `post_list`, which
should be generated by the pre_process() method) yields a
value which tests as True, the response being considered by
post-processing extensions is updated to be that value.
... | train | https://github.com/klmitch/appathy/blob/a10aa7d21d38622e984a8fe106ab37114af90dc2/appathy/actions.py#L198-L229 | null | class ActionDescriptor(object):
"""
Describes an action on a controller. Binds together the method
which performs the action, along with all the registered
extensions and the desired ResponseObject type.
"""
def __init__(self, method, extensions, resp_type):
"""
Initialize an A... |
klmitch/appathy | appathy/actions.py | ActionDescriptor.wrap | python | def wrap(self, req, result):
if isinstance(result, webob.exc.HTTPException):
# It's a webob HTTP exception; use raise to bail out
# immediately and pass it upstream
raise result
elif isinstance(result, webob.Response):
# Straight-up webob Response object;... | Wrap method return results. The return value of the action
method and of the action extensions is passed through this
method before being returned to the caller. Instances of
`webob.Response` are thrown, to abort the rest of action and
extension processing; otherwise, objects which are... | train | https://github.com/klmitch/appathy/blob/a10aa7d21d38622e984a8fe106ab37114af90dc2/appathy/actions.py#L231-L255 | null | class ActionDescriptor(object):
"""
Describes an action on a controller. Binds together the method
which performs the action, along with all the registered
extensions and the desired ResponseObject type.
"""
def __init__(self, method, extensions, resp_type):
"""
Initialize an A... |
biocore/mustached-octo-ironman | moi/websocket.py | MOIMessageHandler.on_message | python | def on_message(self, msg):
if self not in clients:
return
try:
payload = json_decode(msg)
except ValueError:
# unable to decode so we cannot handle the message
return
if 'close' in payload:
self.close()
return
... | Accept a message that was published, process and forward
Parameters
----------
msg : str
The message sent over the line
Notes
-----
This method only handles messages where `message_type` is "message". | train | https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/websocket.py#L40-L66 | null | class MOIMessageHandler(WebSocketHandler):
def __init__(self, *args, **kwargs):
super(MOIMessageHandler, self).__init__(*args, **kwargs)
self.group = Group(self.get_current_user(), forwarder=self.forward)
def get_current_user(self):
user = self.get_secure_cookie("user")
if user ... |
biocore/mustached-octo-ironman | moi/job.py | system_call | python | def system_call(cmd, **kwargs):
proc = Popen(cmd,
universal_newlines=True,
shell=True,
stdout=PIPE,
stderr=PIPE)
# communicate pulls all stdout/stderr from the PIPEs to
# avoid blocking -- don't remove this line!
stdout, stderr = proc.c... | Call cmd and return (stdout, stderr, return_value).
Parameters
----------
cmd: str
Can be either a string containing the command to be run, or a sequence
of strings that are the tokens of the command.
kwargs : dict, optional
Ignored. Available so that this function is compatible... | train | https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/job.py#L21-L54 | null | # -----------------------------------------------------------------------------
# Copyright (c) 2014--, The qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
biocore/mustached-octo-ironman | moi/job.py | _status_change | python | def _status_change(id, new_status):
job_info = json.loads(r_client.get(id))
old_status = job_info['status']
job_info['status'] = new_status
_deposit_payload(job_info)
return old_status | Update the status of a job
The status associated with the id is updated, an update command is
issued to the job's pubsub, and and the old status is returned.
Parameters
----------
id : str
The job ID
new_status : str
The status change
Returns
-------
str
Th... | train | https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/job.py#L57-L80 | [
"def _deposit_payload(to_deposit):\n \"\"\"Store job info, and publish an update\n\n Parameters\n ----------\n to_deposit : dict\n The job info\n\n \"\"\"\n pubsub = to_deposit['pubsub']\n id = to_deposit['id']\n\n with r_client.pipeline() as pipe:\n pipe.set(id, json.dumps(to_... | # -----------------------------------------------------------------------------
# Copyright (c) 2014--, The qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
biocore/mustached-octo-ironman | moi/job.py | _deposit_payload | python | def _deposit_payload(to_deposit):
pubsub = to_deposit['pubsub']
id = to_deposit['id']
with r_client.pipeline() as pipe:
pipe.set(id, json.dumps(to_deposit), ex=REDIS_KEY_TIMEOUT)
pipe.publish(pubsub, json.dumps({"update": [id]}))
pipe.execute() | Store job info, and publish an update
Parameters
----------
to_deposit : dict
The job info | train | https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/job.py#L83-L98 | null | # -----------------------------------------------------------------------------
# Copyright (c) 2014--, The qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
biocore/mustached-octo-ironman | moi/job.py | _redis_wrap | python | def _redis_wrap(job_info, func, *args, **kwargs):
status_changer = partial(_status_change, job_info['id'])
kwargs['moi_update_status'] = status_changer
kwargs['moi_context'] = job_info['context']
kwargs['moi_parent_id'] = job_info['parent']
job_info['status'] = 'Running'
job_info['date_start'] ... | Wrap something to compute
The function that will have available, via kwargs['moi_update_status'], a
method to modify the job status. This method can be used within the
executing function by:
old_status = kwargs['moi_update_status']('my new status')
Parameters
----------
job_info : dic... | train | https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/job.py#L101-L154 | [
"def _deposit_payload(to_deposit):\n \"\"\"Store job info, and publish an update\n\n Parameters\n ----------\n to_deposit : dict\n The job info\n\n \"\"\"\n pubsub = to_deposit['pubsub']\n id = to_deposit['id']\n\n with r_client.pipeline() as pipe:\n pipe.set(id, json.dumps(to_... | # -----------------------------------------------------------------------------
# Copyright (c) 2014--, The qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
biocore/mustached-octo-ironman | moi/job.py | submit | python | def submit(ctx_name, parent_id, name, url, func, *args, **kwargs):
if isinstance(ctx_name, Context):
ctx = ctx_name
else:
ctx = ctxs.get(ctx_name, ctxs[ctx_default])
return _submit(ctx, parent_id, name, url, func, *args, **kwargs) | Submit through a context
Parameters
----------
ctx_name : str
The name of the context to submit through
parent_id : str
The ID of the group that the job is a part of.
name : str
The name of the job
url : str
The handler that can take the results (e.g., /beta_dive... | train | https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/job.py#L157-L188 | [
"def _submit(ctx, parent_id, name, url, func, *args, **kwargs):\n \"\"\"Submit a function to a cluster\n\n Parameters\n ----------\n parent_id : str\n The ID of the group that the job is a part of.\n name : str\n The name of the job\n url : str\n The handler that can take the ... | # -----------------------------------------------------------------------------
# Copyright (c) 2014--, The qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
biocore/mustached-octo-ironman | moi/job.py | _submit | python | def _submit(ctx, parent_id, name, url, func, *args, **kwargs):
parent_info = r_client.get(parent_id)
if parent_info is None:
parent_info = create_info('unnamed', 'group', id=parent_id)
parent_id = parent_info['id']
r_client.set(parent_id, json.dumps(parent_info))
parent_pubsub_key =... | Submit a function to a cluster
Parameters
----------
parent_id : str
The ID of the group that the job is a part of.
name : str
The name of the job
url : str
The handler that can take the results (e.g., /beta_diversity/)
func : function
The function to execute. An... | train | https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/job.py#L191-L235 | [
"def create_info(name, info_type, url=None, parent=None, id=None,\n context=ctx_default, store=False):\n \"\"\"Return a group object\"\"\"\n id = str(uuid4()) if id is None else id\n pubsub = _pubsub_key(id)\n\n info = {'id': id,\n 'type': info_type,\n 'pubsub': pubs... | # -----------------------------------------------------------------------------
# Copyright (c) 2014--, The qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
biocore/mustached-octo-ironman | moi/group.py | create_info | python | def create_info(name, info_type, url=None, parent=None, id=None,
context=ctx_default, store=False):
id = str(uuid4()) if id is None else id
pubsub = _pubsub_key(id)
info = {'id': id,
'type': info_type,
'pubsub': pubsub,
'url': url,
'parent': p... | Return a group object | train | https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/group.py#L351-L376 | [
"def _children_key(key):\n \"\"\"Create a key that corresponds to the group's children\n\n Parameters\n ----------\n key : str\n The group key\n\n Returns\n -------\n str\n The augmented key\n \"\"\"\n return key + ':children'\n",
"def _pubsub_key(key):\n \"\"\"Create a... | r"""Redis group communication"""
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# --------------... |
biocore/mustached-octo-ironman | moi/group.py | get_id_from_user | python | def get_id_from_user(user):
id = r_client.hget('user-id-map', user)
if id is None:
id = str(uuid4())
r_client.hset('user-id-map', user, id)
r_client.hset('user-id-map', id, user)
return id | Get an ID from a user, creates if necessary | train | https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/group.py#L384-L391 | null | r"""Redis group communication"""
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# --------------... |
biocore/mustached-octo-ironman | moi/group.py | Group.traverse | python | def traverse(self, id_=None):
if id_ is None:
id_ = self.group
nodes = r_client.smembers(_children_key(id_))
while nodes:
current_id = nodes.pop()
details = r_client.get(current_id)
if details is None:
# child has expired or been ... | Traverse groups and yield info dicts for jobs | train | https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/group.py#L83-L104 | [
"def _children_key(key):\n \"\"\"Create a key that corresponds to the group's children\n\n Parameters\n ----------\n key : str\n The group key\n\n Returns\n -------\n str\n The augmented key\n \"\"\"\n return key + ':children'\n",
"def _decode(self, data):\n try:\n ... | class Group(object):
"""A object-relational mapper against a Redis job group
Parameters
----------
group : str
A group, this name subscribed to for "group" state changes.
forwarder : function
A function to forward on state changes to. This function must accept a
`dict`. Any ... |
biocore/mustached-octo-ironman | moi/group.py | Group.close | python | def close(self):
for channel in self._listening_to:
self.toredis.unsubscribe(channel)
self.toredis.unsubscribe(self.group_pubsub) | Unsubscribe the group and all jobs being listened too | train | https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/group.py#L109-L113 | null | class Group(object):
"""A object-relational mapper against a Redis job group
Parameters
----------
group : str
A group, this name subscribed to for "group" state changes.
forwarder : function
A function to forward on state changes to. This function must accept a
`dict`. Any ... |
biocore/mustached-octo-ironman | moi/group.py | Group.listen_for_updates | python | def listen_for_updates(self):
self.toredis.subscribe(self.group_pubsub, callback=self.callback) | Attach a callback on the group pubsub | train | https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/group.py#L126-L128 | null | class Group(object):
"""A object-relational mapper against a Redis job group
Parameters
----------
group : str
A group, this name subscribed to for "group" state changes.
forwarder : function
A function to forward on state changes to. This function must accept a
`dict`. Any ... |
biocore/mustached-octo-ironman | moi/group.py | Group.listen_to_node | python | def listen_to_node(self, id_):
if r_client.get(id_) is None:
return
else:
self.toredis.subscribe(_pubsub_key(id_), callback=self.callback)
self._listening_to[_pubsub_key(id_)] = id_
return id_ | Attach a callback on the job pubsub if it exists | train | https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/group.py#L130-L137 | [
"def _pubsub_key(key):\n \"\"\"Create a pubsub key that corresponds to the group's pubsub\n\n Parameters\n ----------\n key : str\n The group key\n\n Returns\n -------\n str\n The augmented key\n \"\"\"\n return key + ':pubsub'\n"
] | class Group(object):
"""A object-relational mapper against a Redis job group
Parameters
----------
group : str
A group, this name subscribed to for "group" state changes.
forwarder : function
A function to forward on state changes to. This function must accept a
`dict`. Any ... |
biocore/mustached-octo-ironman | moi/group.py | Group.unlisten_to_node | python | def unlisten_to_node(self, id_):
id_pubsub = _pubsub_key(id_)
if id_pubsub in self._listening_to:
del self._listening_to[id_pubsub]
self.toredis.unsubscribe(id_pubsub)
parent = json_decode(r_client.get(id_)).get('parent', None)
if parent is not None:
... | Stop listening to a job
Parameters
----------
id_ : str
An ID to remove
Returns
--------
str or None
The ID removed or None if the ID was not removed | train | https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/group.py#L139-L163 | [
"def _children_key(key):\n \"\"\"Create a key that corresponds to the group's children\n\n Parameters\n ----------\n key : str\n The group key\n\n Returns\n -------\n str\n The augmented key\n \"\"\"\n return key + ':children'\n",
"def _pubsub_key(key):\n \"\"\"Create a... | class Group(object):
"""A object-relational mapper against a Redis job group
Parameters
----------
group : str
A group, this name subscribed to for "group" state changes.
forwarder : function
A function to forward on state changes to. This function must accept a
`dict`. Any ... |
biocore/mustached-octo-ironman | moi/group.py | Group.callback | python | def callback(self, msg):
message_type, channel, payload = msg
if message_type != 'message':
return
try:
payload = self._decode(payload)
except ValueError:
# unable to decode so we cannot handle the message
return
if channel == se... | Accept a message that was published, process and forward
Parameters
----------
msg : tuple, (str, str, str)
The message sent over the line. The `tuple` is of the form:
(message_type, channel, payload).
Notes
-----
This method only handles message... | train | https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/group.py#L165-L202 | [
"def _decode(self, data):\n try:\n return json_decode(data)\n except (ValueError, TypeError):\n raise ValueError(\"Unable to decode data!\")\n",
"def action(self, verb, args):\n \"\"\"Process the described action\n\n Parameters\n ----------\n verb : str, {'add', 'remove', 'get'}\n ... | class Group(object):
"""A object-relational mapper against a Redis job group
Parameters
----------
group : str
A group, this name subscribed to for "group" state changes.
forwarder : function
A function to forward on state changes to. This function must accept a
`dict`. Any ... |
biocore/mustached-octo-ironman | moi/group.py | Group.action | python | def action(self, verb, args):
if not isinstance(args, (list, set, tuple)):
raise TypeError("args is unknown type: %s" % type(args))
if verb == 'add':
response = ({'add': i} for i in self._action_add(args))
elif verb == 'remove':
response = ({'remove': i} for ... | Process the described action
Parameters
----------
verb : str, {'add', 'remove', 'get'}
The specific action to perform
args : {list, set, tuple}
Any relevant arguments for the action.
Raises
------
TypeError
If args is an unre... | train | https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/group.py#L204-L238 | [
"def _action_add(self, ids):\n \"\"\"Add IDs to the group\n\n Parameters\n ----------\n ids : {list, set, tuple, generator} of str\n The IDs to add\n\n Returns\n -------\n list of dict\n The details of the added jobs\n \"\"\"\n return self._action_get((self.listen_to_node(id... | class Group(object):
"""A object-relational mapper against a Redis job group
Parameters
----------
group : str
A group, this name subscribed to for "group" state changes.
forwarder : function
A function to forward on state changes to. This function must accept a
`dict`. Any ... |
biocore/mustached-octo-ironman | moi/group.py | Group._action_add | python | def _action_add(self, ids):
return self._action_get((self.listen_to_node(id_) for id_ in ids)) | Add IDs to the group
Parameters
----------
ids : {list, set, tuple, generator} of str
The IDs to add
Returns
-------
list of dict
The details of the added jobs | train | https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/group.py#L272-L285 | [
"def _action_get(self, ids):\n \"\"\"Get the details for ids\n\n Parameters\n ----------\n ids : {list, set, tuple, generator} of str\n The IDs to get\n\n Notes\n -----\n If ids is empty, then all IDs are returned.\n\n Returns\n -------\n list of dict\n The details of the... | class Group(object):
"""A object-relational mapper against a Redis job group
Parameters
----------
group : str
A group, this name subscribed to for "group" state changes.
forwarder : function
A function to forward on state changes to. This function must accept a
`dict`. Any ... |
biocore/mustached-octo-ironman | moi/group.py | Group._action_remove | python | def _action_remove(self, ids):
return self._action_get((self.unlisten_to_node(id_) for id_ in ids)) | Remove IDs from the group
Parameters
----------
ids : {list, set, tuple, generator} of str
The IDs to remove
Returns
-------
list of dict
The details of the removed jobs | train | https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/group.py#L287-L300 | [
"def _action_get(self, ids):\n \"\"\"Get the details for ids\n\n Parameters\n ----------\n ids : {list, set, tuple, generator} of str\n The IDs to get\n\n Notes\n -----\n If ids is empty, then all IDs are returned.\n\n Returns\n -------\n list of dict\n The details of the... | class Group(object):
"""A object-relational mapper against a Redis job group
Parameters
----------
group : str
A group, this name subscribed to for "group" state changes.
forwarder : function
A function to forward on state changes to. This function must accept a
`dict`. Any ... |
biocore/mustached-octo-ironman | moi/group.py | Group._action_get | python | def _action_get(self, ids):
if not ids:
ids = self.jobs
result = []
ids = set(ids)
while ids:
id_ = ids.pop()
if id_ is None:
continue
try:
payload = r_client.get(id_)
except ResponseError:
... | Get the details for ids
Parameters
----------
ids : {list, set, tuple, generator} of str
The IDs to get
Notes
-----
If ids is empty, then all IDs are returned.
Returns
-------
list of dict
The details of the jobs | train | https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/group.py#L302-L348 | [
"def traverse(self, id_=None):\n \"\"\"Traverse groups and yield info dicts for jobs\"\"\"\n if id_ is None:\n id_ = self.group\n\n nodes = r_client.smembers(_children_key(id_))\n while nodes:\n current_id = nodes.pop()\n\n details = r_client.get(current_id)\n if details is N... | class Group(object):
"""A object-relational mapper against a Redis job group
Parameters
----------
group : str
A group, this name subscribed to for "group" state changes.
forwarder : function
A function to forward on state changes to. This function must accept a
`dict`. Any ... |
biocore/mustached-octo-ironman | moi/__init__.py | _support_directory | python | def _support_directory():
from os.path import join, dirname, abspath
return join(dirname(abspath(__file__)), 'support_files') | Get the path of the support_files directory | train | https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/__init__.py#L21-L24 | null | # -----------------------------------------------------------------------------
# Copyright (c) 2014--, The qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
langloisjp/tstore | tstore/tstore.py | TStore.db | python | def db(self):
if not self._db:
self._db = pgtablestorage.DB(dburl=self.dburl)
return self._db | Lazy init the DB (fork friendly) | train | https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/tstore.py#L102-L106 | null | class TStore(object):
"""
A simple table-oriented storage class.
Override validate_record for record validation.
"""
def __init__(self, dburl, record_types=None, schemafile=None,
schemasql=None, encoder=JSONEncoder):
"""
Create new TStore object.
- dburl: e.... |
langloisjp/tstore | tstore/tstore.py | TStore.get | python | def get(self, cls, rid):
self.validate_record_type(cls)
rows = self.db.select(cls, where={ID: rid}, limit=1)
if not rows:
raise KeyError('No {} record with id {}'.format(cls, rid))
return rows[0] | Return record of given type with key `rid`
>>> s = teststore()
>>> s.create('tstoretest', {'id': '1', 'name': 'Toto'})
>>> r = s.get('tstoretest', '1')
>>> r['name']
'Toto'
>>> s.get('badcls', '1')
Traceback (most recent call last):
...
ValueE... | train | https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/tstore.py#L118-L139 | [
"def validate_record_type(self, cls):\n \"\"\"\n Validate given record is acceptable.\n\n >>> s = teststore()\n >>> s.validate_record_type('tstoretest')\n >>> s.validate_record_type('bad')\n Traceback (most recent call last):\n ...\n ValueError: Unsupported record type \"bad\"\n \"\"\... | class TStore(object):
"""
A simple table-oriented storage class.
Override validate_record for record validation.
"""
def __init__(self, dburl, record_types=None, schemafile=None,
schemasql=None, encoder=JSONEncoder):
"""
Create new TStore object.
- dburl: e.... |
langloisjp/tstore | tstore/tstore.py | TStore.create | python | def create(self, cls, record, user='undefined'):
self.validate_record(cls, record)
record[CREATION_DATE] = record[UPDATE_DATE] = self.nowstr()
record[CREATOR] = record[UPDATER] = user
try:
return self.db.insert(cls, record)
except (psycopg2.IntegrityError, psycopg2.Pr... | Persist new record
>>> s = teststore()
>>> s.create('tstoretest', {'id': '1', 'name': 'Toto'})
>>> s.create('tstoretest', {'id': '2', 'name': 'Tata'}, user='jane')
>>> r = s.get('tstoretest', '2')
>>> r[CREATOR]
'jane'
>>> s.create('badcls', {'id': '1', 'name': '... | train | https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/tstore.py#L141-L184 | [
"def nowstr():\n \"\"\"Return current UTC date/time string in ISO format\"\"\"\n return datetime.datetime.utcnow().strftime(\"%Y-%m-%dT%H:%M:%SZ\")\n",
"def validate_record(self, cls, record):\n \"\"\"Validate given record is proper.\n This default implementation only checks the record\n type. Over... | class TStore(object):
"""
A simple table-oriented storage class.
Override validate_record for record validation.
"""
def __init__(self, dburl, record_types=None, schemafile=None,
schemasql=None, encoder=JSONEncoder):
"""
Create new TStore object.
- dburl: e.... |
langloisjp/tstore | tstore/tstore.py | TStore.update | python | def update(self, cls, rid, partialrecord, user='undefined'):
self.validate_partial_record(cls, partialrecord)
partialrecord[UPDATE_DATE] = self.nowstr()
partialrecord[UPDATER] = user
try:
updatecount = self.db.update(cls, partialrecord, where={ID: rid})
if updatec... | Update existing record
>>> s = teststore()
>>> s.create('tstoretest', {'id': '1', 'name': 'Toto'})
>>> r = s.get('tstoretest', '1')
>>> r['age']
>>> s.update('tstoretest', '1', {'age': 25})
>>> r = s.get('tstoretest', '1')
>>> r['age']
25
>>> s.up... | train | https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/tstore.py#L186-L235 | [
"def nowstr():\n \"\"\"Return current UTC date/time string in ISO format\"\"\"\n return datetime.datetime.utcnow().strftime(\"%Y-%m-%dT%H:%M:%SZ\")\n",
"def validate_partial_record(self, cls, partialrecord):\n \"\"\"Validate given partial record is proper.\n A partial record is used for updates.\n ... | class TStore(object):
"""
A simple table-oriented storage class.
Override validate_record for record validation.
"""
def __init__(self, dburl, record_types=None, schemafile=None,
schemasql=None, encoder=JSONEncoder):
"""
Create new TStore object.
- dburl: e.... |
langloisjp/tstore | tstore/tstore.py | TStore.list | python | def list(self, cls, criteria=None):
self.validate_criteria(cls, criteria)
return self.db.select(cls, where=criteria) | Return list of matching records. criteria is a dict of {field: value}
>>> s = teststore()
>>> s.list('tstoretest')
[] | train | https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/tstore.py#L237-L246 | [
"def validate_criteria(self, cls, criteria):\n \"\"\"Validate given criteria is proper for record type.\n This default implementation doesn't check anything.\n Override as needed.\n \"\"\"\n pass\n"
] | class TStore(object):
"""
A simple table-oriented storage class.
Override validate_record for record validation.
"""
def __init__(self, dburl, record_types=None, schemafile=None,
schemasql=None, encoder=JSONEncoder):
"""
Create new TStore object.
- dburl: e.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.