id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
231,300 | quantmind/pulsar | docs/_ext/sphinxtogithub.py | setup | def setup(app):
"Setup function for Sphinx Extension"
app.add_config_value("sphinx_to_github", True, '')
app.add_config_value("sphinx_to_github_verbose", True, '')
app.connect("build-finished", sphinx_extension) | python | def setup(app):
"Setup function for Sphinx Extension"
app.add_config_value("sphinx_to_github", True, '')
app.add_config_value("sphinx_to_github_verbose", True, '')
app.connect("build-finished", sphinx_extension) | [
"def",
"setup",
"(",
"app",
")",
":",
"app",
".",
"add_config_value",
"(",
"\"sphinx_to_github\"",
",",
"True",
",",
"''",
")",
"app",
".",
"add_config_value",
"(",
"\"sphinx_to_github_verbose\"",
",",
"True",
",",
"''",
")",
"app",
".",
"connect",
"(",
"\"build-finished\"",
",",
"sphinx_extension",
")"
] | Setup function for Sphinx Extension | [
"Setup",
"function",
"for",
"Sphinx",
"Extension"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/docs/_ext/sphinxtogithub.py#L288-L292 |
231,301 | quantmind/pulsar | pulsar/apps/wsgi/route.py | Route.url | def url(self, **urlargs):
'''Build a ``url`` from ``urlargs`` key-value parameters
'''
if self.defaults:
d = self.defaults.copy()
d.update(urlargs)
urlargs = d
url = '/'.join(self._url_generator(urlargs))
if not url:
return '/'
else:
url = '/' + url
return url if self.is_leaf else url + '/' | python | def url(self, **urlargs):
'''Build a ``url`` from ``urlargs`` key-value parameters
'''
if self.defaults:
d = self.defaults.copy()
d.update(urlargs)
urlargs = d
url = '/'.join(self._url_generator(urlargs))
if not url:
return '/'
else:
url = '/' + url
return url if self.is_leaf else url + '/' | [
"def",
"url",
"(",
"self",
",",
"*",
"*",
"urlargs",
")",
":",
"if",
"self",
".",
"defaults",
":",
"d",
"=",
"self",
".",
"defaults",
".",
"copy",
"(",
")",
"d",
".",
"update",
"(",
"urlargs",
")",
"urlargs",
"=",
"d",
"url",
"=",
"'/'",
".",
"join",
"(",
"self",
".",
"_url_generator",
"(",
"urlargs",
")",
")",
"if",
"not",
"url",
":",
"return",
"'/'",
"else",
":",
"url",
"=",
"'/'",
"+",
"url",
"return",
"url",
"if",
"self",
".",
"is_leaf",
"else",
"url",
"+",
"'/'"
] | Build a ``url`` from ``urlargs`` key-value parameters | [
"Build",
"a",
"url",
"from",
"urlargs",
"key",
"-",
"value",
"parameters"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/route.py#L308-L320 |
231,302 | quantmind/pulsar | pulsar/apps/wsgi/route.py | Route.split | def split(self):
'''Return a two element tuple containing the parent route and
the last url bit as route. If this route is the root route, it returns
the root route and ``None``. '''
rule = self.rule
if not self.is_leaf:
rule = rule[:-1]
if not rule:
return Route('/'), None
bits = ('/' + rule).split('/')
last = Route(bits[-1] if self.is_leaf else bits[-1] + '/')
if len(bits) > 1:
return Route('/'.join(bits[:-1]) + '/'), last
else:
return last, None | python | def split(self):
'''Return a two element tuple containing the parent route and
the last url bit as route. If this route is the root route, it returns
the root route and ``None``. '''
rule = self.rule
if not self.is_leaf:
rule = rule[:-1]
if not rule:
return Route('/'), None
bits = ('/' + rule).split('/')
last = Route(bits[-1] if self.is_leaf else bits[-1] + '/')
if len(bits) > 1:
return Route('/'.join(bits[:-1]) + '/'), last
else:
return last, None | [
"def",
"split",
"(",
"self",
")",
":",
"rule",
"=",
"self",
".",
"rule",
"if",
"not",
"self",
".",
"is_leaf",
":",
"rule",
"=",
"rule",
"[",
":",
"-",
"1",
"]",
"if",
"not",
"rule",
":",
"return",
"Route",
"(",
"'/'",
")",
",",
"None",
"bits",
"=",
"(",
"'/'",
"+",
"rule",
")",
".",
"split",
"(",
"'/'",
")",
"last",
"=",
"Route",
"(",
"bits",
"[",
"-",
"1",
"]",
"if",
"self",
".",
"is_leaf",
"else",
"bits",
"[",
"-",
"1",
"]",
"+",
"'/'",
")",
"if",
"len",
"(",
"bits",
")",
">",
"1",
":",
"return",
"Route",
"(",
"'/'",
".",
"join",
"(",
"bits",
"[",
":",
"-",
"1",
"]",
")",
"+",
"'/'",
")",
",",
"last",
"else",
":",
"return",
"last",
",",
"None"
] | Return a two element tuple containing the parent route and
the last url bit as route. If this route is the root route, it returns
the root route and ``None``. | [
"Return",
"a",
"two",
"element",
"tuple",
"containing",
"the",
"parent",
"route",
"and",
"the",
"last",
"url",
"bit",
"as",
"route",
".",
"If",
"this",
"route",
"is",
"the",
"root",
"route",
"it",
"returns",
"the",
"root",
"route",
"and",
"None",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/route.py#L351-L365 |
231,303 | quantmind/pulsar | pulsar/apps/wsgi/routers.py | was_modified_since | def was_modified_since(header=None, mtime=0, size=0):
'''Check if an item was modified since the user last downloaded it
:param header: the value of the ``If-Modified-Since`` header.
If this is ``None``, simply return ``True``
:param mtime: the modification time of the item in question.
:param size: the size of the item.
'''
header_mtime = modified_since(header, size)
if header_mtime and header_mtime <= mtime:
return False
return True | python | def was_modified_since(header=None, mtime=0, size=0):
'''Check if an item was modified since the user last downloaded it
:param header: the value of the ``If-Modified-Since`` header.
If this is ``None``, simply return ``True``
:param mtime: the modification time of the item in question.
:param size: the size of the item.
'''
header_mtime = modified_since(header, size)
if header_mtime and header_mtime <= mtime:
return False
return True | [
"def",
"was_modified_since",
"(",
"header",
"=",
"None",
",",
"mtime",
"=",
"0",
",",
"size",
"=",
"0",
")",
":",
"header_mtime",
"=",
"modified_since",
"(",
"header",
",",
"size",
")",
"if",
"header_mtime",
"and",
"header_mtime",
"<=",
"mtime",
":",
"return",
"False",
"return",
"True"
] | Check if an item was modified since the user last downloaded it
:param header: the value of the ``If-Modified-Since`` header.
If this is ``None``, simply return ``True``
:param mtime: the modification time of the item in question.
:param size: the size of the item. | [
"Check",
"if",
"an",
"item",
"was",
"modified",
"since",
"the",
"user",
"last",
"downloaded",
"it"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/routers.py#L577-L588 |
231,304 | quantmind/pulsar | pulsar/apps/wsgi/routers.py | file_response | def file_response(request, filepath, block=None, status_code=None,
content_type=None, encoding=None, cache_control=None):
"""Utility for serving a local file
Typical usage::
from pulsar.apps import wsgi
class MyRouter(wsgi.Router):
def get(self, request):
return wsgi.file_response(request, "<filepath>")
:param request: Wsgi request
:param filepath: full path of file to serve
:param block: Optional block size (default 1MB)
:param status_code: Optional status code (default 200)
:return: a :class:`~.WsgiResponse` object
"""
file_wrapper = request.get('wsgi.file_wrapper')
if os.path.isfile(filepath):
response = request.response
info = os.stat(filepath)
size = info[stat.ST_SIZE]
modified = info[stat.ST_MTIME]
header = request.get('HTTP_IF_MODIFIED_SINCE')
if not was_modified_since(header, modified, size):
response.status_code = 304
else:
if not content_type:
content_type, encoding = mimetypes.guess_type(filepath)
file = open(filepath, 'rb')
response.headers['content-length'] = str(size)
response.content = file_wrapper(file, block)
response.content_type = content_type
response.encoding = encoding
if status_code:
response.status_code = status_code
else:
response.headers["Last-Modified"] = http_date(modified)
if cache_control:
etag = digest('modified: %d - size: %d' % (modified, size))
cache_control(response.headers, etag=etag)
return response
raise Http404 | python | def file_response(request, filepath, block=None, status_code=None,
content_type=None, encoding=None, cache_control=None):
"""Utility for serving a local file
Typical usage::
from pulsar.apps import wsgi
class MyRouter(wsgi.Router):
def get(self, request):
return wsgi.file_response(request, "<filepath>")
:param request: Wsgi request
:param filepath: full path of file to serve
:param block: Optional block size (default 1MB)
:param status_code: Optional status code (default 200)
:return: a :class:`~.WsgiResponse` object
"""
file_wrapper = request.get('wsgi.file_wrapper')
if os.path.isfile(filepath):
response = request.response
info = os.stat(filepath)
size = info[stat.ST_SIZE]
modified = info[stat.ST_MTIME]
header = request.get('HTTP_IF_MODIFIED_SINCE')
if not was_modified_since(header, modified, size):
response.status_code = 304
else:
if not content_type:
content_type, encoding = mimetypes.guess_type(filepath)
file = open(filepath, 'rb')
response.headers['content-length'] = str(size)
response.content = file_wrapper(file, block)
response.content_type = content_type
response.encoding = encoding
if status_code:
response.status_code = status_code
else:
response.headers["Last-Modified"] = http_date(modified)
if cache_control:
etag = digest('modified: %d - size: %d' % (modified, size))
cache_control(response.headers, etag=etag)
return response
raise Http404 | [
"def",
"file_response",
"(",
"request",
",",
"filepath",
",",
"block",
"=",
"None",
",",
"status_code",
"=",
"None",
",",
"content_type",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"cache_control",
"=",
"None",
")",
":",
"file_wrapper",
"=",
"request",
".",
"get",
"(",
"'wsgi.file_wrapper'",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"filepath",
")",
":",
"response",
"=",
"request",
".",
"response",
"info",
"=",
"os",
".",
"stat",
"(",
"filepath",
")",
"size",
"=",
"info",
"[",
"stat",
".",
"ST_SIZE",
"]",
"modified",
"=",
"info",
"[",
"stat",
".",
"ST_MTIME",
"]",
"header",
"=",
"request",
".",
"get",
"(",
"'HTTP_IF_MODIFIED_SINCE'",
")",
"if",
"not",
"was_modified_since",
"(",
"header",
",",
"modified",
",",
"size",
")",
":",
"response",
".",
"status_code",
"=",
"304",
"else",
":",
"if",
"not",
"content_type",
":",
"content_type",
",",
"encoding",
"=",
"mimetypes",
".",
"guess_type",
"(",
"filepath",
")",
"file",
"=",
"open",
"(",
"filepath",
",",
"'rb'",
")",
"response",
".",
"headers",
"[",
"'content-length'",
"]",
"=",
"str",
"(",
"size",
")",
"response",
".",
"content",
"=",
"file_wrapper",
"(",
"file",
",",
"block",
")",
"response",
".",
"content_type",
"=",
"content_type",
"response",
".",
"encoding",
"=",
"encoding",
"if",
"status_code",
":",
"response",
".",
"status_code",
"=",
"status_code",
"else",
":",
"response",
".",
"headers",
"[",
"\"Last-Modified\"",
"]",
"=",
"http_date",
"(",
"modified",
")",
"if",
"cache_control",
":",
"etag",
"=",
"digest",
"(",
"'modified: %d - size: %d'",
"%",
"(",
"modified",
",",
"size",
")",
")",
"cache_control",
"(",
"response",
".",
"headers",
",",
"etag",
"=",
"etag",
")",
"return",
"response",
"raise",
"Http404"
] | Utility for serving a local file
Typical usage::
from pulsar.apps import wsgi
class MyRouter(wsgi.Router):
def get(self, request):
return wsgi.file_response(request, "<filepath>")
:param request: Wsgi request
:param filepath: full path of file to serve
:param block: Optional block size (default 1MB)
:param status_code: Optional status code (default 200)
:return: a :class:`~.WsgiResponse` object | [
"Utility",
"for",
"serving",
"a",
"local",
"file"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/routers.py#L591-L635 |
231,305 | quantmind/pulsar | pulsar/apps/wsgi/routers.py | Router.has_parent | def has_parent(self, router):
'''Check if ``router`` is ``self`` or a parent or ``self``
'''
parent = self
while parent and parent is not router:
parent = parent._parent
return parent is not None | python | def has_parent(self, router):
'''Check if ``router`` is ``self`` or a parent or ``self``
'''
parent = self
while parent and parent is not router:
parent = parent._parent
return parent is not None | [
"def",
"has_parent",
"(",
"self",
",",
"router",
")",
":",
"parent",
"=",
"self",
"while",
"parent",
"and",
"parent",
"is",
"not",
"router",
":",
"parent",
"=",
"parent",
".",
"_parent",
"return",
"parent",
"is",
"not",
"None"
] | Check if ``router`` is ``self`` or a parent or ``self`` | [
"Check",
"if",
"router",
"is",
"self",
"or",
"a",
"parent",
"or",
"self"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/routers.py#L407-L413 |
231,306 | quantmind/pulsar | pulsar/apps/ds/utils.py | count_bytes | def count_bytes(array):
'''Count the number of bits in a byte ``array``.
It uses the Hamming weight popcount algorithm
'''
# this algorithm can be rewritten as
# for i in array:
# count += sum(b=='1' for b in bin(i)[2:])
# but this version is almost 2 times faster
count = 0
for i in array:
i = i - ((i >> 1) & 0x55555555)
i = (i & 0x33333333) + ((i >> 2) & 0x33333333)
count += (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24
return count | python | def count_bytes(array):
'''Count the number of bits in a byte ``array``.
It uses the Hamming weight popcount algorithm
'''
# this algorithm can be rewritten as
# for i in array:
# count += sum(b=='1' for b in bin(i)[2:])
# but this version is almost 2 times faster
count = 0
for i in array:
i = i - ((i >> 1) & 0x55555555)
i = (i & 0x33333333) + ((i >> 2) & 0x33333333)
count += (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24
return count | [
"def",
"count_bytes",
"(",
"array",
")",
":",
"# this algorithm can be rewritten as",
"# for i in array:",
"# count += sum(b=='1' for b in bin(i)[2:])",
"# but this version is almost 2 times faster",
"count",
"=",
"0",
"for",
"i",
"in",
"array",
":",
"i",
"=",
"i",
"-",
"(",
"(",
"i",
">>",
"1",
")",
"&",
"0x55555555",
")",
"i",
"=",
"(",
"i",
"&",
"0x33333333",
")",
"+",
"(",
"(",
"i",
">>",
"2",
")",
"&",
"0x33333333",
")",
"count",
"+=",
"(",
"(",
"(",
"i",
"+",
"(",
"i",
">>",
"4",
")",
")",
"&",
"0x0F0F0F0F",
")",
"*",
"0x01010101",
")",
">>",
"24",
"return",
"count"
] | Count the number of bits in a byte ``array``.
It uses the Hamming weight popcount algorithm | [
"Count",
"the",
"number",
"of",
"bits",
"in",
"a",
"byte",
"array",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/ds/utils.py#L172-L186 |
231,307 | quantmind/pulsar | pulsar/apps/ws/websocket.py | WebSocketProtocol.write | def write(self, message, opcode=None, encode=True, **kw):
'''Write a new ``message`` into the wire.
It uses the :meth:`~.FrameParser.encode` method of the
websocket :attr:`parser`.
:param message: message to send, must be a string or bytes
:param opcode: optional ``opcode``, if not supplied it is set to 1
if ``message`` is a string, otherwise ``2`` when the message
are bytes.
'''
if encode:
message = self.parser.encode(message, opcode=opcode, **kw)
result = self.connection.write(message)
if opcode == 0x8:
self.connection.close()
return result | python | def write(self, message, opcode=None, encode=True, **kw):
'''Write a new ``message`` into the wire.
It uses the :meth:`~.FrameParser.encode` method of the
websocket :attr:`parser`.
:param message: message to send, must be a string or bytes
:param opcode: optional ``opcode``, if not supplied it is set to 1
if ``message`` is a string, otherwise ``2`` when the message
are bytes.
'''
if encode:
message = self.parser.encode(message, opcode=opcode, **kw)
result = self.connection.write(message)
if opcode == 0x8:
self.connection.close()
return result | [
"def",
"write",
"(",
"self",
",",
"message",
",",
"opcode",
"=",
"None",
",",
"encode",
"=",
"True",
",",
"*",
"*",
"kw",
")",
":",
"if",
"encode",
":",
"message",
"=",
"self",
".",
"parser",
".",
"encode",
"(",
"message",
",",
"opcode",
"=",
"opcode",
",",
"*",
"*",
"kw",
")",
"result",
"=",
"self",
".",
"connection",
".",
"write",
"(",
"message",
")",
"if",
"opcode",
"==",
"0x8",
":",
"self",
".",
"connection",
".",
"close",
"(",
")",
"return",
"result"
] | Write a new ``message`` into the wire.
It uses the :meth:`~.FrameParser.encode` method of the
websocket :attr:`parser`.
:param message: message to send, must be a string or bytes
:param opcode: optional ``opcode``, if not supplied it is set to 1
if ``message`` is a string, otherwise ``2`` when the message
are bytes. | [
"Write",
"a",
"new",
"message",
"into",
"the",
"wire",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/ws/websocket.py#L75-L91 |
231,308 | quantmind/pulsar | pulsar/apps/ws/websocket.py | WebSocketProtocol.ping | def ping(self, message=None):
'''Write a ping ``frame``.
'''
return self.write(self.parser.ping(message), encode=False) | python | def ping(self, message=None):
'''Write a ping ``frame``.
'''
return self.write(self.parser.ping(message), encode=False) | [
"def",
"ping",
"(",
"self",
",",
"message",
"=",
"None",
")",
":",
"return",
"self",
".",
"write",
"(",
"self",
".",
"parser",
".",
"ping",
"(",
"message",
")",
",",
"encode",
"=",
"False",
")"
] | Write a ping ``frame``. | [
"Write",
"a",
"ping",
"frame",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/ws/websocket.py#L93-L96 |
231,309 | quantmind/pulsar | pulsar/apps/ws/websocket.py | WebSocketProtocol.pong | def pong(self, message=None):
'''Write a pong ``frame``.
'''
return self.write(self.parser.pong(message), encode=False) | python | def pong(self, message=None):
'''Write a pong ``frame``.
'''
return self.write(self.parser.pong(message), encode=False) | [
"def",
"pong",
"(",
"self",
",",
"message",
"=",
"None",
")",
":",
"return",
"self",
".",
"write",
"(",
"self",
".",
"parser",
".",
"pong",
"(",
"message",
")",
",",
"encode",
"=",
"False",
")"
] | Write a pong ``frame``. | [
"Write",
"a",
"pong",
"frame",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/ws/websocket.py#L98-L101 |
231,310 | quantmind/pulsar | pulsar/apps/ws/websocket.py | WebSocketProtocol.write_close | def write_close(self, code=None):
'''Write a close ``frame`` with ``code``.
'''
return self.write(self.parser.close(code), opcode=0x8, encode=False) | python | def write_close(self, code=None):
'''Write a close ``frame`` with ``code``.
'''
return self.write(self.parser.close(code), opcode=0x8, encode=False) | [
"def",
"write_close",
"(",
"self",
",",
"code",
"=",
"None",
")",
":",
"return",
"self",
".",
"write",
"(",
"self",
".",
"parser",
".",
"close",
"(",
"code",
")",
",",
"opcode",
"=",
"0x8",
",",
"encode",
"=",
"False",
")"
] | Write a close ``frame`` with ``code``. | [
"Write",
"a",
"close",
"frame",
"with",
"code",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/ws/websocket.py#L103-L106 |
231,311 | quantmind/pulsar | pulsar/utils/html.py | escape | def escape(html, force=False):
"""Returns the given HTML with ampersands,
quotes and angle brackets encoded."""
if hasattr(html, '__html__') and not force:
return html
if html in NOTHING:
return ''
else:
return to_string(html).replace('&', '&').replace(
'<', '<').replace('>', '>').replace("'", ''').replace(
'"', '"') | python | def escape(html, force=False):
"""Returns the given HTML with ampersands,
quotes and angle brackets encoded."""
if hasattr(html, '__html__') and not force:
return html
if html in NOTHING:
return ''
else:
return to_string(html).replace('&', '&').replace(
'<', '<').replace('>', '>').replace("'", ''').replace(
'"', '"') | [
"def",
"escape",
"(",
"html",
",",
"force",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"html",
",",
"'__html__'",
")",
"and",
"not",
"force",
":",
"return",
"html",
"if",
"html",
"in",
"NOTHING",
":",
"return",
"''",
"else",
":",
"return",
"to_string",
"(",
"html",
")",
".",
"replace",
"(",
"'&'",
",",
"'&'",
")",
".",
"replace",
"(",
"'<'",
",",
"'<'",
")",
".",
"replace",
"(",
"'>'",
",",
"'>'",
")",
".",
"replace",
"(",
"\"'\"",
",",
"'''",
")",
".",
"replace",
"(",
"'\"'",
",",
"'"'",
")"
] | Returns the given HTML with ampersands,
quotes and angle brackets encoded. | [
"Returns",
"the",
"given",
"HTML",
"with",
"ampersands",
"quotes",
"and",
"angle",
"brackets",
"encoded",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/html.py#L45-L55 |
231,312 | quantmind/pulsar | pulsar/utils/html.py | capfirst | def capfirst(x):
'''Capitalise the first letter of ``x``.
'''
x = to_string(x).strip()
if x:
return x[0].upper() + x[1:].lower()
else:
return x | python | def capfirst(x):
'''Capitalise the first letter of ``x``.
'''
x = to_string(x).strip()
if x:
return x[0].upper() + x[1:].lower()
else:
return x | [
"def",
"capfirst",
"(",
"x",
")",
":",
"x",
"=",
"to_string",
"(",
"x",
")",
".",
"strip",
"(",
")",
"if",
"x",
":",
"return",
"x",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"+",
"x",
"[",
"1",
":",
"]",
".",
"lower",
"(",
")",
"else",
":",
"return",
"x"
] | Capitalise the first letter of ``x``. | [
"Capitalise",
"the",
"first",
"letter",
"of",
"x",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/html.py#L73-L80 |
231,313 | quantmind/pulsar | pulsar/utils/html.py | nicename | def nicename(name):
'''Make ``name`` a more user friendly string.
Capitalise the first letter and replace dash and underscores with a space
'''
name = to_string(name)
return capfirst(' '.join(name.replace('-', ' ').replace('_', ' ').split())) | python | def nicename(name):
'''Make ``name`` a more user friendly string.
Capitalise the first letter and replace dash and underscores with a space
'''
name = to_string(name)
return capfirst(' '.join(name.replace('-', ' ').replace('_', ' ').split())) | [
"def",
"nicename",
"(",
"name",
")",
":",
"name",
"=",
"to_string",
"(",
"name",
")",
"return",
"capfirst",
"(",
"' '",
".",
"join",
"(",
"name",
".",
"replace",
"(",
"'-'",
",",
"' '",
")",
".",
"replace",
"(",
"'_'",
",",
"' '",
")",
".",
"split",
"(",
")",
")",
")"
] | Make ``name`` a more user friendly string.
Capitalise the first letter and replace dash and underscores with a space | [
"Make",
"name",
"a",
"more",
"user",
"friendly",
"string",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/html.py#L83-L89 |
231,314 | quantmind/pulsar | pulsar/utils/context.py | TaskContext.set | def set(self, key, value):
"""Set a value in the task context
"""
task = Task.current_task()
try:
context = task._context
except AttributeError:
task._context = context = {}
context[key] = value | python | def set(self, key, value):
"""Set a value in the task context
"""
task = Task.current_task()
try:
context = task._context
except AttributeError:
task._context = context = {}
context[key] = value | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"task",
"=",
"Task",
".",
"current_task",
"(",
")",
"try",
":",
"context",
"=",
"task",
".",
"_context",
"except",
"AttributeError",
":",
"task",
".",
"_context",
"=",
"context",
"=",
"{",
"}",
"context",
"[",
"key",
"]",
"=",
"value"
] | Set a value in the task context | [
"Set",
"a",
"value",
"in",
"the",
"task",
"context"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/context.py#L40-L48 |
231,315 | quantmind/pulsar | pulsar/utils/context.py | TaskContext.stack_pop | def stack_pop(self, key):
"""Remove a value in a task context stack
"""
task = Task.current_task()
try:
context = task._context_stack
except AttributeError:
raise KeyError('pop from empty stack') from None
value = context[key]
stack_value = value.pop()
if not value:
context.pop(key)
return stack_value | python | def stack_pop(self, key):
"""Remove a value in a task context stack
"""
task = Task.current_task()
try:
context = task._context_stack
except AttributeError:
raise KeyError('pop from empty stack') from None
value = context[key]
stack_value = value.pop()
if not value:
context.pop(key)
return stack_value | [
"def",
"stack_pop",
"(",
"self",
",",
"key",
")",
":",
"task",
"=",
"Task",
".",
"current_task",
"(",
")",
"try",
":",
"context",
"=",
"task",
".",
"_context_stack",
"except",
"AttributeError",
":",
"raise",
"KeyError",
"(",
"'pop from empty stack'",
")",
"from",
"None",
"value",
"=",
"context",
"[",
"key",
"]",
"stack_value",
"=",
"value",
".",
"pop",
"(",
")",
"if",
"not",
"value",
":",
"context",
".",
"pop",
"(",
"key",
")",
"return",
"stack_value"
] | Remove a value in a task context stack | [
"Remove",
"a",
"value",
"in",
"a",
"task",
"context",
"stack"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/context.py#L85-L97 |
231,316 | quantmind/pulsar | pulsar/utils/importer.py | module_attribute | def module_attribute(dotpath, default=None, safe=False):
'''Load an attribute from a module.
If the module or the attribute is not available, return the default
argument if *safe* is `True`.
'''
if dotpath:
bits = str(dotpath).split(':')
try:
if len(bits) == 2:
attr = bits[1]
module_name = bits[0]
else:
bits = bits[0].split('.')
if len(bits) > 1:
attr = bits[-1]
module_name = '.'.join(bits[:-1])
else:
raise ValueError('Could not find attribute in %s'
% dotpath)
module = import_module(module_name)
return getattr(module, attr)
except Exception:
if not safe:
raise
return default
else:
if not safe:
raise ImportError
return default | python | def module_attribute(dotpath, default=None, safe=False):
'''Load an attribute from a module.
If the module or the attribute is not available, return the default
argument if *safe* is `True`.
'''
if dotpath:
bits = str(dotpath).split(':')
try:
if len(bits) == 2:
attr = bits[1]
module_name = bits[0]
else:
bits = bits[0].split('.')
if len(bits) > 1:
attr = bits[-1]
module_name = '.'.join(bits[:-1])
else:
raise ValueError('Could not find attribute in %s'
% dotpath)
module = import_module(module_name)
return getattr(module, attr)
except Exception:
if not safe:
raise
return default
else:
if not safe:
raise ImportError
return default | [
"def",
"module_attribute",
"(",
"dotpath",
",",
"default",
"=",
"None",
",",
"safe",
"=",
"False",
")",
":",
"if",
"dotpath",
":",
"bits",
"=",
"str",
"(",
"dotpath",
")",
".",
"split",
"(",
"':'",
")",
"try",
":",
"if",
"len",
"(",
"bits",
")",
"==",
"2",
":",
"attr",
"=",
"bits",
"[",
"1",
"]",
"module_name",
"=",
"bits",
"[",
"0",
"]",
"else",
":",
"bits",
"=",
"bits",
"[",
"0",
"]",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"bits",
")",
">",
"1",
":",
"attr",
"=",
"bits",
"[",
"-",
"1",
"]",
"module_name",
"=",
"'.'",
".",
"join",
"(",
"bits",
"[",
":",
"-",
"1",
"]",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Could not find attribute in %s'",
"%",
"dotpath",
")",
"module",
"=",
"import_module",
"(",
"module_name",
")",
"return",
"getattr",
"(",
"module",
",",
"attr",
")",
"except",
"Exception",
":",
"if",
"not",
"safe",
":",
"raise",
"return",
"default",
"else",
":",
"if",
"not",
"safe",
":",
"raise",
"ImportError",
"return",
"default"
] | Load an attribute from a module.
If the module or the attribute is not available, return the default
argument if *safe* is `True`. | [
"Load",
"an",
"attribute",
"from",
"a",
"module",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/importer.py#L50-L80 |
231,317 | quantmind/pulsar | pulsar/async/actor.py | Actor.start | def start(self, exit=True):
'''Called after forking to start the actor's life.
This is where logging is configured, the :attr:`mailbox` is
registered and the :attr:`_loop` is initialised and
started. Calling this method more than once does nothing.
'''
if self.state == ACTOR_STATES.INITIAL:
self._concurrency.before_start(self)
self._concurrency.add_events(self)
try:
self.cfg.when_ready(self)
except Exception: # pragma nocover
self.logger.exception('Unhandled exception in when_ready hook')
self._started = self._loop.time()
self._exit = exit
self.state = ACTOR_STATES.STARTING
self._run() | python | def start(self, exit=True):
'''Called after forking to start the actor's life.
This is where logging is configured, the :attr:`mailbox` is
registered and the :attr:`_loop` is initialised and
started. Calling this method more than once does nothing.
'''
if self.state == ACTOR_STATES.INITIAL:
self._concurrency.before_start(self)
self._concurrency.add_events(self)
try:
self.cfg.when_ready(self)
except Exception: # pragma nocover
self.logger.exception('Unhandled exception in when_ready hook')
self._started = self._loop.time()
self._exit = exit
self.state = ACTOR_STATES.STARTING
self._run() | [
"def",
"start",
"(",
"self",
",",
"exit",
"=",
"True",
")",
":",
"if",
"self",
".",
"state",
"==",
"ACTOR_STATES",
".",
"INITIAL",
":",
"self",
".",
"_concurrency",
".",
"before_start",
"(",
"self",
")",
"self",
".",
"_concurrency",
".",
"add_events",
"(",
"self",
")",
"try",
":",
"self",
".",
"cfg",
".",
"when_ready",
"(",
"self",
")",
"except",
"Exception",
":",
"# pragma nocover",
"self",
".",
"logger",
".",
"exception",
"(",
"'Unhandled exception in when_ready hook'",
")",
"self",
".",
"_started",
"=",
"self",
".",
"_loop",
".",
"time",
"(",
")",
"self",
".",
"_exit",
"=",
"exit",
"self",
".",
"state",
"=",
"ACTOR_STATES",
".",
"STARTING",
"self",
".",
"_run",
"(",
")"
] | Called after forking to start the actor's life.
This is where logging is configured, the :attr:`mailbox` is
registered and the :attr:`_loop` is initialised and
started. Calling this method more than once does nothing. | [
"Called",
"after",
"forking",
"to",
"start",
"the",
"actor",
"s",
"life",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/actor.py#L265-L282 |
231,318 | quantmind/pulsar | pulsar/async/actor.py | Actor.send | def send(self, target, action, *args, **kwargs):
'''Send a message to ``target`` to perform ``action`` with given
positional ``args`` and key-valued ``kwargs``.
Returns a coroutine or a Future.
'''
target = self.monitor if target == 'monitor' else target
mailbox = self.mailbox
if isinstance(target, ActorProxyMonitor):
mailbox = target.mailbox
else:
actor = self.get_actor(target)
if isinstance(actor, Actor):
# this occur when sending a message from arbiter to monitors or
# vice-versa.
return command_in_context(action, self, actor, args, kwargs)
elif isinstance(actor, ActorProxyMonitor):
mailbox = actor.mailbox
if hasattr(mailbox, 'send'):
# if not mailbox.closed:
return mailbox.send(action, self, target, args, kwargs)
else:
raise CommandError('Cannot execute "%s" in %s. Unknown actor %s.'
% (action, self, target)) | python | def send(self, target, action, *args, **kwargs):
'''Send a message to ``target`` to perform ``action`` with given
positional ``args`` and key-valued ``kwargs``.
Returns a coroutine or a Future.
'''
target = self.monitor if target == 'monitor' else target
mailbox = self.mailbox
if isinstance(target, ActorProxyMonitor):
mailbox = target.mailbox
else:
actor = self.get_actor(target)
if isinstance(actor, Actor):
# this occur when sending a message from arbiter to monitors or
# vice-versa.
return command_in_context(action, self, actor, args, kwargs)
elif isinstance(actor, ActorProxyMonitor):
mailbox = actor.mailbox
if hasattr(mailbox, 'send'):
# if not mailbox.closed:
return mailbox.send(action, self, target, args, kwargs)
else:
raise CommandError('Cannot execute "%s" in %s. Unknown actor %s.'
% (action, self, target)) | [
"def",
"send",
"(",
"self",
",",
"target",
",",
"action",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"target",
"=",
"self",
".",
"monitor",
"if",
"target",
"==",
"'monitor'",
"else",
"target",
"mailbox",
"=",
"self",
".",
"mailbox",
"if",
"isinstance",
"(",
"target",
",",
"ActorProxyMonitor",
")",
":",
"mailbox",
"=",
"target",
".",
"mailbox",
"else",
":",
"actor",
"=",
"self",
".",
"get_actor",
"(",
"target",
")",
"if",
"isinstance",
"(",
"actor",
",",
"Actor",
")",
":",
"# this occur when sending a message from arbiter to monitors or",
"# vice-versa.",
"return",
"command_in_context",
"(",
"action",
",",
"self",
",",
"actor",
",",
"args",
",",
"kwargs",
")",
"elif",
"isinstance",
"(",
"actor",
",",
"ActorProxyMonitor",
")",
":",
"mailbox",
"=",
"actor",
".",
"mailbox",
"if",
"hasattr",
"(",
"mailbox",
",",
"'send'",
")",
":",
"# if not mailbox.closed:",
"return",
"mailbox",
".",
"send",
"(",
"action",
",",
"self",
",",
"target",
",",
"args",
",",
"kwargs",
")",
"else",
":",
"raise",
"CommandError",
"(",
"'Cannot execute \"%s\" in %s. Unknown actor %s.'",
"%",
"(",
"action",
",",
"self",
",",
"target",
")",
")"
] | Send a message to ``target`` to perform ``action`` with given
positional ``args`` and key-valued ``kwargs``.
Returns a coroutine or a Future. | [
"Send",
"a",
"message",
"to",
"target",
"to",
"perform",
"action",
"with",
"given",
"positional",
"args",
"and",
"key",
"-",
"valued",
"kwargs",
".",
"Returns",
"a",
"coroutine",
"or",
"a",
"Future",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/actor.py#L284-L306 |
231,319 | quantmind/pulsar | pulsar/apps/wsgi/content.py | String.stream | def stream(self, request, counter=0):
'''Returns an iterable over strings.
'''
if self._children:
for child in self._children:
if isinstance(child, String):
yield from child.stream(request, counter+1)
else:
yield child | python | def stream(self, request, counter=0):
'''Returns an iterable over strings.
'''
if self._children:
for child in self._children:
if isinstance(child, String):
yield from child.stream(request, counter+1)
else:
yield child | [
"def",
"stream",
"(",
"self",
",",
"request",
",",
"counter",
"=",
"0",
")",
":",
"if",
"self",
".",
"_children",
":",
"for",
"child",
"in",
"self",
".",
"_children",
":",
"if",
"isinstance",
"(",
"child",
",",
"String",
")",
":",
"yield",
"from",
"child",
".",
"stream",
"(",
"request",
",",
"counter",
"+",
"1",
")",
"else",
":",
"yield",
"child"
] | Returns an iterable over strings. | [
"Returns",
"an",
"iterable",
"over",
"strings",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/content.py#L158-L166 |
231,320 | quantmind/pulsar | pulsar/apps/wsgi/content.py | String.to_bytes | def to_bytes(self, request=None):
'''Called to transform the collection of
``streams`` into the content string.
This method can be overwritten by derived classes.
:param streams: a collection (list or dictionary) containing
``strings/bytes`` used to build the final ``string/bytes``.
:return: a string or bytes
'''
data = bytearray()
for chunk in self.stream(request):
if isinstance(chunk, str):
chunk = chunk.encode(self.charset)
data.extend(chunk)
return bytes(data) | python | def to_bytes(self, request=None):
'''Called to transform the collection of
``streams`` into the content string.
This method can be overwritten by derived classes.
:param streams: a collection (list or dictionary) containing
``strings/bytes`` used to build the final ``string/bytes``.
:return: a string or bytes
'''
data = bytearray()
for chunk in self.stream(request):
if isinstance(chunk, str):
chunk = chunk.encode(self.charset)
data.extend(chunk)
return bytes(data) | [
"def",
"to_bytes",
"(",
"self",
",",
"request",
"=",
"None",
")",
":",
"data",
"=",
"bytearray",
"(",
")",
"for",
"chunk",
"in",
"self",
".",
"stream",
"(",
"request",
")",
":",
"if",
"isinstance",
"(",
"chunk",
",",
"str",
")",
":",
"chunk",
"=",
"chunk",
".",
"encode",
"(",
"self",
".",
"charset",
")",
"data",
".",
"extend",
"(",
"chunk",
")",
"return",
"bytes",
"(",
"data",
")"
] | Called to transform the collection of
``streams`` into the content string.
This method can be overwritten by derived classes.
:param streams: a collection (list or dictionary) containing
``strings/bytes`` used to build the final ``string/bytes``.
:return: a string or bytes | [
"Called",
"to",
"transform",
"the",
"collection",
"of",
"streams",
"into",
"the",
"content",
"string",
".",
"This",
"method",
"can",
"be",
"overwritten",
"by",
"derived",
"classes",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/content.py#L184-L198 |
231,321 | quantmind/pulsar | pulsar/apps/wsgi/content.py | Html.attr | def attr(self, *args):
'''Add the specific attribute to the attribute dictionary
with key ``name`` and value ``value`` and return ``self``.'''
attr = self._attr
if not args:
return attr or {}
result, adding = self._attrdata('attr', *args)
if adding:
for key, value in result.items():
if DATARE.match(key):
self.data(key[5:], value)
else:
if attr is None:
self._extra['attr'] = attr = {}
attr[key] = value
result = self
return result | python | def attr(self, *args):
'''Add the specific attribute to the attribute dictionary
with key ``name`` and value ``value`` and return ``self``.'''
attr = self._attr
if not args:
return attr or {}
result, adding = self._attrdata('attr', *args)
if adding:
for key, value in result.items():
if DATARE.match(key):
self.data(key[5:], value)
else:
if attr is None:
self._extra['attr'] = attr = {}
attr[key] = value
result = self
return result | [
"def",
"attr",
"(",
"self",
",",
"*",
"args",
")",
":",
"attr",
"=",
"self",
".",
"_attr",
"if",
"not",
"args",
":",
"return",
"attr",
"or",
"{",
"}",
"result",
",",
"adding",
"=",
"self",
".",
"_attrdata",
"(",
"'attr'",
",",
"*",
"args",
")",
"if",
"adding",
":",
"for",
"key",
",",
"value",
"in",
"result",
".",
"items",
"(",
")",
":",
"if",
"DATARE",
".",
"match",
"(",
"key",
")",
":",
"self",
".",
"data",
"(",
"key",
"[",
"5",
":",
"]",
",",
"value",
")",
"else",
":",
"if",
"attr",
"is",
"None",
":",
"self",
".",
"_extra",
"[",
"'attr'",
"]",
"=",
"attr",
"=",
"{",
"}",
"attr",
"[",
"key",
"]",
"=",
"value",
"result",
"=",
"self",
"return",
"result"
] | Add the specific attribute to the attribute dictionary
with key ``name`` and value ``value`` and return ``self``. | [
"Add",
"the",
"specific",
"attribute",
"to",
"the",
"attribute",
"dictionary",
"with",
"key",
"name",
"and",
"value",
"value",
"and",
"return",
"self",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/content.py#L330-L346 |
231,322 | quantmind/pulsar | pulsar/apps/wsgi/content.py | Html.addClass | def addClass(self, cn):
'''Add the specific class names to the class set and return ``self``.
'''
if cn:
if isinstance(cn, (tuple, list, set, frozenset)):
add = self.addClass
for c in cn:
add(c)
else:
classes = self._classes
if classes is None:
self._extra['classes'] = classes = set()
add = classes.add
for cn in cn.split():
add(slugify(cn))
return self | python | def addClass(self, cn):
'''Add the specific class names to the class set and return ``self``.
'''
if cn:
if isinstance(cn, (tuple, list, set, frozenset)):
add = self.addClass
for c in cn:
add(c)
else:
classes = self._classes
if classes is None:
self._extra['classes'] = classes = set()
add = classes.add
for cn in cn.split():
add(slugify(cn))
return self | [
"def",
"addClass",
"(",
"self",
",",
"cn",
")",
":",
"if",
"cn",
":",
"if",
"isinstance",
"(",
"cn",
",",
"(",
"tuple",
",",
"list",
",",
"set",
",",
"frozenset",
")",
")",
":",
"add",
"=",
"self",
".",
"addClass",
"for",
"c",
"in",
"cn",
":",
"add",
"(",
"c",
")",
"else",
":",
"classes",
"=",
"self",
".",
"_classes",
"if",
"classes",
"is",
"None",
":",
"self",
".",
"_extra",
"[",
"'classes'",
"]",
"=",
"classes",
"=",
"set",
"(",
")",
"add",
"=",
"classes",
".",
"add",
"for",
"cn",
"in",
"cn",
".",
"split",
"(",
")",
":",
"add",
"(",
"slugify",
"(",
"cn",
")",
")",
"return",
"self"
] | Add the specific class names to the class set and return ``self``. | [
"Add",
"the",
"specific",
"class",
"names",
"to",
"the",
"class",
"set",
"and",
"return",
"self",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/content.py#L364-L379 |
231,323 | quantmind/pulsar | pulsar/apps/wsgi/content.py | Html.flatatt | def flatatt(self, **attr):
'''Return a string with attributes to add to the tag'''
cs = ''
attr = self._attr
classes = self._classes
data = self._data
css = self._css
attr = attr.copy() if attr else {}
if classes:
cs = ' '.join(classes)
attr['class'] = cs
if css:
attr['style'] = ' '.join(('%s:%s;' % (k, v) for
k, v in css.items()))
if data:
for k, v in data.items():
attr['data-%s' % k] = dump_data_value(v)
if attr:
return ''.join(attr_iter(attr))
else:
return '' | python | def flatatt(self, **attr):
'''Return a string with attributes to add to the tag'''
cs = ''
attr = self._attr
classes = self._classes
data = self._data
css = self._css
attr = attr.copy() if attr else {}
if classes:
cs = ' '.join(classes)
attr['class'] = cs
if css:
attr['style'] = ' '.join(('%s:%s;' % (k, v) for
k, v in css.items()))
if data:
for k, v in data.items():
attr['data-%s' % k] = dump_data_value(v)
if attr:
return ''.join(attr_iter(attr))
else:
return '' | [
"def",
"flatatt",
"(",
"self",
",",
"*",
"*",
"attr",
")",
":",
"cs",
"=",
"''",
"attr",
"=",
"self",
".",
"_attr",
"classes",
"=",
"self",
".",
"_classes",
"data",
"=",
"self",
".",
"_data",
"css",
"=",
"self",
".",
"_css",
"attr",
"=",
"attr",
".",
"copy",
"(",
")",
"if",
"attr",
"else",
"{",
"}",
"if",
"classes",
":",
"cs",
"=",
"' '",
".",
"join",
"(",
"classes",
")",
"attr",
"[",
"'class'",
"]",
"=",
"cs",
"if",
"css",
":",
"attr",
"[",
"'style'",
"]",
"=",
"' '",
".",
"join",
"(",
"(",
"'%s:%s;'",
"%",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"css",
".",
"items",
"(",
")",
")",
")",
"if",
"data",
":",
"for",
"k",
",",
"v",
"in",
"data",
".",
"items",
"(",
")",
":",
"attr",
"[",
"'data-%s'",
"%",
"k",
"]",
"=",
"dump_data_value",
"(",
"v",
")",
"if",
"attr",
":",
"return",
"''",
".",
"join",
"(",
"attr_iter",
"(",
"attr",
")",
")",
"else",
":",
"return",
"''"
] | Return a string with attributes to add to the tag | [
"Return",
"a",
"string",
"with",
"attributes",
"to",
"add",
"to",
"the",
"tag"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/content.py#L396-L416 |
231,324 | quantmind/pulsar | pulsar/apps/wsgi/content.py | Html.css | def css(self, mapping=None):
'''Update the css dictionary if ``mapping`` is a dictionary, otherwise
return the css value at ``mapping``.
If ``mapping`` is not given, return the whole ``css`` dictionary
if available.
'''
css = self._css
if mapping is None:
return css
elif isinstance(mapping, Mapping):
if css is None:
self._extra['css'] = css = {}
css.update(mapping)
return self
else:
return css.get(mapping) if css else None | python | def css(self, mapping=None):
'''Update the css dictionary if ``mapping`` is a dictionary, otherwise
return the css value at ``mapping``.
If ``mapping`` is not given, return the whole ``css`` dictionary
if available.
'''
css = self._css
if mapping is None:
return css
elif isinstance(mapping, Mapping):
if css is None:
self._extra['css'] = css = {}
css.update(mapping)
return self
else:
return css.get(mapping) if css else None | [
"def",
"css",
"(",
"self",
",",
"mapping",
"=",
"None",
")",
":",
"css",
"=",
"self",
".",
"_css",
"if",
"mapping",
"is",
"None",
":",
"return",
"css",
"elif",
"isinstance",
"(",
"mapping",
",",
"Mapping",
")",
":",
"if",
"css",
"is",
"None",
":",
"self",
".",
"_extra",
"[",
"'css'",
"]",
"=",
"css",
"=",
"{",
"}",
"css",
".",
"update",
"(",
"mapping",
")",
"return",
"self",
"else",
":",
"return",
"css",
".",
"get",
"(",
"mapping",
")",
"if",
"css",
"else",
"None"
] | Update the css dictionary if ``mapping`` is a dictionary, otherwise
return the css value at ``mapping``.
If ``mapping`` is not given, return the whole ``css`` dictionary
if available. | [
"Update",
"the",
"css",
"dictionary",
"if",
"mapping",
"is",
"a",
"dictionary",
"otherwise",
"return",
"the",
"css",
"value",
"at",
"mapping",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/content.py#L418-L434 |
231,325 | quantmind/pulsar | pulsar/apps/wsgi/content.py | Media.absolute_path | def absolute_path(self, path, minify=True):
'''Return a suitable absolute url for ``path``.
If ``path`` :meth:`is_relative` build a suitable url by prepending
the :attr:`media_path` attribute.
:return: A url path to insert in a HTML ``link`` or ``script``.
'''
if minify:
ending = '.%s' % self.mediatype
if not path.endswith(ending):
if self.minified:
path = '%s.min' % path
path = '%s%s' % (path, ending)
#
if self.is_relative(path) and self.media_path:
return '%s%s' % (self.media_path, path)
elif self.asset_protocol and path.startswith('//'):
return '%s%s' % (self.asset_protocol, path)
else:
return path | python | def absolute_path(self, path, minify=True):
'''Return a suitable absolute url for ``path``.
If ``path`` :meth:`is_relative` build a suitable url by prepending
the :attr:`media_path` attribute.
:return: A url path to insert in a HTML ``link`` or ``script``.
'''
if minify:
ending = '.%s' % self.mediatype
if not path.endswith(ending):
if self.minified:
path = '%s.min' % path
path = '%s%s' % (path, ending)
#
if self.is_relative(path) and self.media_path:
return '%s%s' % (self.media_path, path)
elif self.asset_protocol and path.startswith('//'):
return '%s%s' % (self.asset_protocol, path)
else:
return path | [
"def",
"absolute_path",
"(",
"self",
",",
"path",
",",
"minify",
"=",
"True",
")",
":",
"if",
"minify",
":",
"ending",
"=",
"'.%s'",
"%",
"self",
".",
"mediatype",
"if",
"not",
"path",
".",
"endswith",
"(",
"ending",
")",
":",
"if",
"self",
".",
"minified",
":",
"path",
"=",
"'%s.min'",
"%",
"path",
"path",
"=",
"'%s%s'",
"%",
"(",
"path",
",",
"ending",
")",
"#",
"if",
"self",
".",
"is_relative",
"(",
"path",
")",
"and",
"self",
".",
"media_path",
":",
"return",
"'%s%s'",
"%",
"(",
"self",
".",
"media_path",
",",
"path",
")",
"elif",
"self",
".",
"asset_protocol",
"and",
"path",
".",
"startswith",
"(",
"'//'",
")",
":",
"return",
"'%s%s'",
"%",
"(",
"self",
".",
"asset_protocol",
",",
"path",
")",
"else",
":",
"return",
"path"
] | Return a suitable absolute url for ``path``.
If ``path`` :meth:`is_relative` build a suitable url by prepending
the :attr:`media_path` attribute.
:return: A url path to insert in a HTML ``link`` or ``script``. | [
"Return",
"a",
"suitable",
"absolute",
"url",
"for",
"path",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/content.py#L531-L551 |
231,326 | quantmind/pulsar | pulsar/apps/wsgi/content.py | Links.insert | def insert(self, index, child, rel=None, type=None, media=None,
condition=None, **kwargs):
'''Append a link to this container.
:param child: a string indicating the location of the linked
document
:param rel: Specifies the relationship between the document
and the linked document. If not given ``stylesheet`` is used.
:param type: Specifies the content type of the linked document.
If not given ``text/css`` is used. It an empty string is given,
it won't be added.
:param media: Specifies on what device the linked document will be
displayed. If not given or ``all``, the media is for all devices.
:param kwargs: additional attributes
'''
if child:
srel = 'stylesheet'
stype = 'text/css'
minify = rel in (None, srel) and type in (None, stype)
path = self.absolute_path(child, minify=minify)
if path.endswith('.css'):
rel = rel or srel
type = type or stype
value = Html('link', href=path, rel=rel, **kwargs)
if type:
value.attr('type', type)
if media not in (None, 'all'):
value.attr('media', media)
if condition:
value = Html(None, '<!--[if %s]>\n' % condition,
value, '<![endif]-->\n')
value = value.to_string()
if value not in self.children:
if index is None:
self.children.append(value)
else:
self.children.insert(index, value) | python | def insert(self, index, child, rel=None, type=None, media=None,
condition=None, **kwargs):
'''Append a link to this container.
:param child: a string indicating the location of the linked
document
:param rel: Specifies the relationship between the document
and the linked document. If not given ``stylesheet`` is used.
:param type: Specifies the content type of the linked document.
If not given ``text/css`` is used. It an empty string is given,
it won't be added.
:param media: Specifies on what device the linked document will be
displayed. If not given or ``all``, the media is for all devices.
:param kwargs: additional attributes
'''
if child:
srel = 'stylesheet'
stype = 'text/css'
minify = rel in (None, srel) and type in (None, stype)
path = self.absolute_path(child, minify=minify)
if path.endswith('.css'):
rel = rel or srel
type = type or stype
value = Html('link', href=path, rel=rel, **kwargs)
if type:
value.attr('type', type)
if media not in (None, 'all'):
value.attr('media', media)
if condition:
value = Html(None, '<!--[if %s]>\n' % condition,
value, '<![endif]-->\n')
value = value.to_string()
if value not in self.children:
if index is None:
self.children.append(value)
else:
self.children.insert(index, value) | [
"def",
"insert",
"(",
"self",
",",
"index",
",",
"child",
",",
"rel",
"=",
"None",
",",
"type",
"=",
"None",
",",
"media",
"=",
"None",
",",
"condition",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"child",
":",
"srel",
"=",
"'stylesheet'",
"stype",
"=",
"'text/css'",
"minify",
"=",
"rel",
"in",
"(",
"None",
",",
"srel",
")",
"and",
"type",
"in",
"(",
"None",
",",
"stype",
")",
"path",
"=",
"self",
".",
"absolute_path",
"(",
"child",
",",
"minify",
"=",
"minify",
")",
"if",
"path",
".",
"endswith",
"(",
"'.css'",
")",
":",
"rel",
"=",
"rel",
"or",
"srel",
"type",
"=",
"type",
"or",
"stype",
"value",
"=",
"Html",
"(",
"'link'",
",",
"href",
"=",
"path",
",",
"rel",
"=",
"rel",
",",
"*",
"*",
"kwargs",
")",
"if",
"type",
":",
"value",
".",
"attr",
"(",
"'type'",
",",
"type",
")",
"if",
"media",
"not",
"in",
"(",
"None",
",",
"'all'",
")",
":",
"value",
".",
"attr",
"(",
"'media'",
",",
"media",
")",
"if",
"condition",
":",
"value",
"=",
"Html",
"(",
"None",
",",
"'<!--[if %s]>\\n'",
"%",
"condition",
",",
"value",
",",
"'<![endif]-->\\n'",
")",
"value",
"=",
"value",
".",
"to_string",
"(",
")",
"if",
"value",
"not",
"in",
"self",
".",
"children",
":",
"if",
"index",
"is",
"None",
":",
"self",
".",
"children",
".",
"append",
"(",
"value",
")",
"else",
":",
"self",
".",
"children",
".",
"insert",
"(",
"index",
",",
"value",
")"
] | Append a link to this container.
:param child: a string indicating the location of the linked
document
:param rel: Specifies the relationship between the document
and the linked document. If not given ``stylesheet`` is used.
:param type: Specifies the content type of the linked document.
If not given ``text/css`` is used. It an empty string is given,
it won't be added.
:param media: Specifies on what device the linked document will be
displayed. If not given or ``all``, the media is for all devices.
:param kwargs: additional attributes | [
"Append",
"a",
"link",
"to",
"this",
"container",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/content.py#L566-L602 |
231,327 | quantmind/pulsar | pulsar/apps/wsgi/content.py | Scripts.insert | def insert(self, index, child, **kwargs):
'''add a new script to the container.
:param child: a ``string`` representing an absolute path to the script
or relative path (does not start with ``http`` or ``/``), in which
case the :attr:`Media.media_path` attribute is prepended.
'''
if child:
script = self.script(child, **kwargs)
if script not in self.children:
if index is None:
self.children.append(script)
else:
self.children.insert(index, script) | python | def insert(self, index, child, **kwargs):
'''add a new script to the container.
:param child: a ``string`` representing an absolute path to the script
or relative path (does not start with ``http`` or ``/``), in which
case the :attr:`Media.media_path` attribute is prepended.
'''
if child:
script = self.script(child, **kwargs)
if script not in self.children:
if index is None:
self.children.append(script)
else:
self.children.insert(index, script) | [
"def",
"insert",
"(",
"self",
",",
"index",
",",
"child",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"child",
":",
"script",
"=",
"self",
".",
"script",
"(",
"child",
",",
"*",
"*",
"kwargs",
")",
"if",
"script",
"not",
"in",
"self",
".",
"children",
":",
"if",
"index",
"is",
"None",
":",
"self",
".",
"children",
".",
"append",
"(",
"script",
")",
"else",
":",
"self",
".",
"children",
".",
"insert",
"(",
"index",
",",
"script",
")"
] | add a new script to the container.
:param child: a ``string`` representing an absolute path to the script
or relative path (does not start with ``http`` or ``/``), in which
case the :attr:`Media.media_path` attribute is prepended. | [
"add",
"a",
"new",
"script",
"to",
"the",
"container",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/content.py#L622-L635 |
231,328 | quantmind/pulsar | pulsar/apps/wsgi/content.py | Head.get_meta | def get_meta(self, name, meta_key=None):
'''Get the ``content`` attribute of a meta tag ``name``.
For example::
head.get_meta('decription')
returns the ``content`` attribute of the meta tag with attribute
``name`` equal to ``description`` or ``None``.
If a different meta key needs to be matched, it can be specified via
the ``meta_key`` parameter::
head.get_meta('og:title', meta_key='property')
'''
meta_key = meta_key or 'name'
for child in self.meta._children:
if isinstance(child, Html) and child.attr(meta_key) == name:
return child.attr('content') | python | def get_meta(self, name, meta_key=None):
'''Get the ``content`` attribute of a meta tag ``name``.
For example::
head.get_meta('decription')
returns the ``content`` attribute of the meta tag with attribute
``name`` equal to ``description`` or ``None``.
If a different meta key needs to be matched, it can be specified via
the ``meta_key`` parameter::
head.get_meta('og:title', meta_key='property')
'''
meta_key = meta_key or 'name'
for child in self.meta._children:
if isinstance(child, Html) and child.attr(meta_key) == name:
return child.attr('content') | [
"def",
"get_meta",
"(",
"self",
",",
"name",
",",
"meta_key",
"=",
"None",
")",
":",
"meta_key",
"=",
"meta_key",
"or",
"'name'",
"for",
"child",
"in",
"self",
".",
"meta",
".",
"_children",
":",
"if",
"isinstance",
"(",
"child",
",",
"Html",
")",
"and",
"child",
".",
"attr",
"(",
"meta_key",
")",
"==",
"name",
":",
"return",
"child",
".",
"attr",
"(",
"'content'",
")"
] | Get the ``content`` attribute of a meta tag ``name``.
For example::
head.get_meta('decription')
returns the ``content`` attribute of the meta tag with attribute
``name`` equal to ``description`` or ``None``.
If a different meta key needs to be matched, it can be specified via
the ``meta_key`` parameter::
head.get_meta('og:title', meta_key='property') | [
"Get",
"the",
"content",
"attribute",
"of",
"a",
"meta",
"tag",
"name",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/content.py#L779-L796 |
231,329 | quantmind/pulsar | pulsar/apps/wsgi/content.py | Head.replace_meta | def replace_meta(self, name, content=None, meta_key=None):
'''Replace the ``content`` attribute of meta tag ``name``
If the meta with ``name`` is not available, it is added, otherwise
its content is replaced. If ``content`` is not given or it is empty
the meta tag with ``name`` is removed.
'''
children = self.meta._children
if not content: # small optimazation
children = tuple(children)
meta_key = meta_key or 'name'
for child in children:
if child.attr(meta_key) == name:
if content:
child.attr('content', content)
else:
self.meta._children.remove(child)
return
if content:
self.add_meta(**{meta_key: name, 'content': content}) | python | def replace_meta(self, name, content=None, meta_key=None):
'''Replace the ``content`` attribute of meta tag ``name``
If the meta with ``name`` is not available, it is added, otherwise
its content is replaced. If ``content`` is not given or it is empty
the meta tag with ``name`` is removed.
'''
children = self.meta._children
if not content: # small optimazation
children = tuple(children)
meta_key = meta_key or 'name'
for child in children:
if child.attr(meta_key) == name:
if content:
child.attr('content', content)
else:
self.meta._children.remove(child)
return
if content:
self.add_meta(**{meta_key: name, 'content': content}) | [
"def",
"replace_meta",
"(",
"self",
",",
"name",
",",
"content",
"=",
"None",
",",
"meta_key",
"=",
"None",
")",
":",
"children",
"=",
"self",
".",
"meta",
".",
"_children",
"if",
"not",
"content",
":",
"# small optimazation",
"children",
"=",
"tuple",
"(",
"children",
")",
"meta_key",
"=",
"meta_key",
"or",
"'name'",
"for",
"child",
"in",
"children",
":",
"if",
"child",
".",
"attr",
"(",
"meta_key",
")",
"==",
"name",
":",
"if",
"content",
":",
"child",
".",
"attr",
"(",
"'content'",
",",
"content",
")",
"else",
":",
"self",
".",
"meta",
".",
"_children",
".",
"remove",
"(",
"child",
")",
"return",
"if",
"content",
":",
"self",
".",
"add_meta",
"(",
"*",
"*",
"{",
"meta_key",
":",
"name",
",",
"'content'",
":",
"content",
"}",
")"
] | Replace the ``content`` attribute of meta tag ``name``
If the meta with ``name`` is not available, it is added, otherwise
its content is replaced. If ``content`` is not given or it is empty
the meta tag with ``name`` is removed. | [
"Replace",
"the",
"content",
"attribute",
"of",
"meta",
"tag",
"name"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/content.py#L798-L817 |
231,330 | quantmind/pulsar | examples/calculator/manage.py | randompaths | def randompaths(request, num_paths=1, size=250, mu=0, sigma=1):
'''Lists of random walks.'''
r = []
for p in range(num_paths):
v = 0
path = [v]
r.append(path)
for t in range(size):
v += normalvariate(mu, sigma)
path.append(v)
return r | python | def randompaths(request, num_paths=1, size=250, mu=0, sigma=1):
'''Lists of random walks.'''
r = []
for p in range(num_paths):
v = 0
path = [v]
r.append(path)
for t in range(size):
v += normalvariate(mu, sigma)
path.append(v)
return r | [
"def",
"randompaths",
"(",
"request",
",",
"num_paths",
"=",
"1",
",",
"size",
"=",
"250",
",",
"mu",
"=",
"0",
",",
"sigma",
"=",
"1",
")",
":",
"r",
"=",
"[",
"]",
"for",
"p",
"in",
"range",
"(",
"num_paths",
")",
":",
"v",
"=",
"0",
"path",
"=",
"[",
"v",
"]",
"r",
".",
"append",
"(",
"path",
")",
"for",
"t",
"in",
"range",
"(",
"size",
")",
":",
"v",
"+=",
"normalvariate",
"(",
"mu",
",",
"sigma",
")",
"path",
".",
"append",
"(",
"v",
")",
"return",
"r"
] | Lists of random walks. | [
"Lists",
"of",
"random",
"walks",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/calculator/manage.py#L22-L32 |
231,331 | quantmind/pulsar | examples/calculator/manage.py | Site.setup | def setup(self, environ):
'''Called once to setup the list of wsgi middleware.'''
json_handler = Root().putSubHandler('calc', Calculator())
middleware = wsgi.Router('/', post=json_handler,
accept_content_types=JSON_CONTENT_TYPES)
response = [wsgi.GZipMiddleware(200)]
return wsgi.WsgiHandler(middleware=[wsgi.wait_for_body_middleware,
middleware],
response_middleware=response) | python | def setup(self, environ):
'''Called once to setup the list of wsgi middleware.'''
json_handler = Root().putSubHandler('calc', Calculator())
middleware = wsgi.Router('/', post=json_handler,
accept_content_types=JSON_CONTENT_TYPES)
response = [wsgi.GZipMiddleware(200)]
return wsgi.WsgiHandler(middleware=[wsgi.wait_for_body_middleware,
middleware],
response_middleware=response) | [
"def",
"setup",
"(",
"self",
",",
"environ",
")",
":",
"json_handler",
"=",
"Root",
"(",
")",
".",
"putSubHandler",
"(",
"'calc'",
",",
"Calculator",
"(",
")",
")",
"middleware",
"=",
"wsgi",
".",
"Router",
"(",
"'/'",
",",
"post",
"=",
"json_handler",
",",
"accept_content_types",
"=",
"JSON_CONTENT_TYPES",
")",
"response",
"=",
"[",
"wsgi",
".",
"GZipMiddleware",
"(",
"200",
")",
"]",
"return",
"wsgi",
".",
"WsgiHandler",
"(",
"middleware",
"=",
"[",
"wsgi",
".",
"wait_for_body_middleware",
",",
"middleware",
"]",
",",
"response_middleware",
"=",
"response",
")"
] | Called once to setup the list of wsgi middleware. | [
"Called",
"once",
"to",
"setup",
"the",
"list",
"of",
"wsgi",
"middleware",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/calculator/manage.py#L72-L80 |
231,332 | quantmind/pulsar | examples/chat/manage.py | AsyncResponseMiddleware | def AsyncResponseMiddleware(environ, resp):
'''This is just for testing the asynchronous response middleware
'''
future = create_future()
future._loop.call_soon(future.set_result, resp)
return future | python | def AsyncResponseMiddleware(environ, resp):
'''This is just for testing the asynchronous response middleware
'''
future = create_future()
future._loop.call_soon(future.set_result, resp)
return future | [
"def",
"AsyncResponseMiddleware",
"(",
"environ",
",",
"resp",
")",
":",
"future",
"=",
"create_future",
"(",
")",
"future",
".",
"_loop",
".",
"call_soon",
"(",
"future",
".",
"set_result",
",",
"resp",
")",
"return",
"future"
] | This is just for testing the asynchronous response middleware | [
"This",
"is",
"just",
"for",
"testing",
"the",
"asynchronous",
"response",
"middleware"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/chat/manage.py#L161-L166 |
231,333 | quantmind/pulsar | examples/chat/manage.py | Protocol.encode | def encode(self, message):
'''Encode a message when publishing.'''
if not isinstance(message, dict):
message = {'message': message}
message['time'] = time.time()
return json.dumps(message) | python | def encode(self, message):
'''Encode a message when publishing.'''
if not isinstance(message, dict):
message = {'message': message}
message['time'] = time.time()
return json.dumps(message) | [
"def",
"encode",
"(",
"self",
",",
"message",
")",
":",
"if",
"not",
"isinstance",
"(",
"message",
",",
"dict",
")",
":",
"message",
"=",
"{",
"'message'",
":",
"message",
"}",
"message",
"[",
"'time'",
"]",
"=",
"time",
".",
"time",
"(",
")",
"return",
"json",
".",
"dumps",
"(",
"message",
")"
] | Encode a message when publishing. | [
"Encode",
"a",
"message",
"when",
"publishing",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/chat/manage.py#L70-L75 |
231,334 | quantmind/pulsar | examples/chat/manage.py | Chat.on_message | def on_message(self, websocket, msg):
'''When a new message arrives, it publishes to all listening clients.
'''
if msg:
lines = []
for li in msg.split('\n'):
li = li.strip()
if li:
lines.append(li)
msg = ' '.join(lines)
if msg:
return self.pubsub.publish(self.channel, msg) | python | def on_message(self, websocket, msg):
'''When a new message arrives, it publishes to all listening clients.
'''
if msg:
lines = []
for li in msg.split('\n'):
li = li.strip()
if li:
lines.append(li)
msg = ' '.join(lines)
if msg:
return self.pubsub.publish(self.channel, msg) | [
"def",
"on_message",
"(",
"self",
",",
"websocket",
",",
"msg",
")",
":",
"if",
"msg",
":",
"lines",
"=",
"[",
"]",
"for",
"li",
"in",
"msg",
".",
"split",
"(",
"'\\n'",
")",
":",
"li",
"=",
"li",
".",
"strip",
"(",
")",
"if",
"li",
":",
"lines",
".",
"append",
"(",
"li",
")",
"msg",
"=",
"' '",
".",
"join",
"(",
"lines",
")",
"if",
"msg",
":",
"return",
"self",
".",
"pubsub",
".",
"publish",
"(",
"self",
".",
"channel",
",",
"msg",
")"
] | When a new message arrives, it publishes to all listening clients. | [
"When",
"a",
"new",
"message",
"arrives",
"it",
"publishes",
"to",
"all",
"listening",
"clients",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/chat/manage.py#L100-L111 |
231,335 | quantmind/pulsar | examples/chat/manage.py | Rpc.rpc_message | async def rpc_message(self, request, message):
'''Publish a message via JSON-RPC'''
await self.pubsub.publish(self.channel, message)
return 'OK' | python | async def rpc_message(self, request, message):
'''Publish a message via JSON-RPC'''
await self.pubsub.publish(self.channel, message)
return 'OK' | [
"async",
"def",
"rpc_message",
"(",
"self",
",",
"request",
",",
"message",
")",
":",
"await",
"self",
".",
"pubsub",
".",
"publish",
"(",
"self",
".",
"channel",
",",
"message",
")",
"return",
"'OK'"
] | Publish a message via JSON-RPC | [
"Publish",
"a",
"message",
"via",
"JSON",
"-",
"RPC"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/chat/manage.py#L122-L125 |
231,336 | quantmind/pulsar | examples/chat/manage.py | WebChat.setup | def setup(self, environ):
'''Called once only to setup the WSGI application handler.
Check :ref:`lazy wsgi handler <wsgi-lazy-handler>`
section for further information.
'''
request = wsgi_request(environ)
cfg = request.cache.cfg
loop = request.cache._loop
self.store = create_store(cfg.data_store, loop=loop)
pubsub = self.store.pubsub(protocol=Protocol())
channel = '%s_webchat' % self.name
ensure_future(pubsub.subscribe(channel), loop=loop)
return WsgiHandler([Router('/', get=self.home_page),
WebSocket('/message', Chat(pubsub, channel)),
Router('/rpc', post=Rpc(pubsub, channel),
response_content_types=JSON_CONTENT_TYPES)],
[AsyncResponseMiddleware,
GZipMiddleware(min_length=20)]) | python | def setup(self, environ):
'''Called once only to setup the WSGI application handler.
Check :ref:`lazy wsgi handler <wsgi-lazy-handler>`
section for further information.
'''
request = wsgi_request(environ)
cfg = request.cache.cfg
loop = request.cache._loop
self.store = create_store(cfg.data_store, loop=loop)
pubsub = self.store.pubsub(protocol=Protocol())
channel = '%s_webchat' % self.name
ensure_future(pubsub.subscribe(channel), loop=loop)
return WsgiHandler([Router('/', get=self.home_page),
WebSocket('/message', Chat(pubsub, channel)),
Router('/rpc', post=Rpc(pubsub, channel),
response_content_types=JSON_CONTENT_TYPES)],
[AsyncResponseMiddleware,
GZipMiddleware(min_length=20)]) | [
"def",
"setup",
"(",
"self",
",",
"environ",
")",
":",
"request",
"=",
"wsgi_request",
"(",
"environ",
")",
"cfg",
"=",
"request",
".",
"cache",
".",
"cfg",
"loop",
"=",
"request",
".",
"cache",
".",
"_loop",
"self",
".",
"store",
"=",
"create_store",
"(",
"cfg",
".",
"data_store",
",",
"loop",
"=",
"loop",
")",
"pubsub",
"=",
"self",
".",
"store",
".",
"pubsub",
"(",
"protocol",
"=",
"Protocol",
"(",
")",
")",
"channel",
"=",
"'%s_webchat'",
"%",
"self",
".",
"name",
"ensure_future",
"(",
"pubsub",
".",
"subscribe",
"(",
"channel",
")",
",",
"loop",
"=",
"loop",
")",
"return",
"WsgiHandler",
"(",
"[",
"Router",
"(",
"'/'",
",",
"get",
"=",
"self",
".",
"home_page",
")",
",",
"WebSocket",
"(",
"'/message'",
",",
"Chat",
"(",
"pubsub",
",",
"channel",
")",
")",
",",
"Router",
"(",
"'/rpc'",
",",
"post",
"=",
"Rpc",
"(",
"pubsub",
",",
"channel",
")",
",",
"response_content_types",
"=",
"JSON_CONTENT_TYPES",
")",
"]",
",",
"[",
"AsyncResponseMiddleware",
",",
"GZipMiddleware",
"(",
"min_length",
"=",
"20",
")",
"]",
")"
] | Called once only to setup the WSGI application handler.
Check :ref:`lazy wsgi handler <wsgi-lazy-handler>`
section for further information. | [
"Called",
"once",
"only",
"to",
"setup",
"the",
"WSGI",
"application",
"handler",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/chat/manage.py#L134-L152 |
231,337 | quantmind/pulsar | pulsar/utils/pylib/wsgiresponse.py | WsgiResponse._get_headers | def _get_headers(self, environ):
"""The list of headers for this response
"""
headers = self.headers
method = environ['REQUEST_METHOD']
if has_empty_content(self.status_code, method) and method != HEAD:
headers.pop('content-type', None)
headers.pop('content-length', None)
self._content = ()
else:
if not self.is_streamed():
cl = reduce(count_len, self._content, 0)
headers['content-length'] = str(cl)
ct = headers.get('content-type')
# content type encoding available
if self.encoding:
ct = ct or 'text/plain'
if ';' not in ct:
ct = '%s; charset=%s' % (ct, self.encoding)
if ct:
headers['content-type'] = ct
if method == HEAD:
self._content = ()
# Cookies
if (self.status_code < 400 and self._can_store_cookies and
self._cookies):
for c in self.cookies.values():
headers.add('set-cookie', c.OutputString())
return headers.items() | python | def _get_headers(self, environ):
"""The list of headers for this response
"""
headers = self.headers
method = environ['REQUEST_METHOD']
if has_empty_content(self.status_code, method) and method != HEAD:
headers.pop('content-type', None)
headers.pop('content-length', None)
self._content = ()
else:
if not self.is_streamed():
cl = reduce(count_len, self._content, 0)
headers['content-length'] = str(cl)
ct = headers.get('content-type')
# content type encoding available
if self.encoding:
ct = ct or 'text/plain'
if ';' not in ct:
ct = '%s; charset=%s' % (ct, self.encoding)
if ct:
headers['content-type'] = ct
if method == HEAD:
self._content = ()
# Cookies
if (self.status_code < 400 and self._can_store_cookies and
self._cookies):
for c in self.cookies.values():
headers.add('set-cookie', c.OutputString())
return headers.items() | [
"def",
"_get_headers",
"(",
"self",
",",
"environ",
")",
":",
"headers",
"=",
"self",
".",
"headers",
"method",
"=",
"environ",
"[",
"'REQUEST_METHOD'",
"]",
"if",
"has_empty_content",
"(",
"self",
".",
"status_code",
",",
"method",
")",
"and",
"method",
"!=",
"HEAD",
":",
"headers",
".",
"pop",
"(",
"'content-type'",
",",
"None",
")",
"headers",
".",
"pop",
"(",
"'content-length'",
",",
"None",
")",
"self",
".",
"_content",
"=",
"(",
")",
"else",
":",
"if",
"not",
"self",
".",
"is_streamed",
"(",
")",
":",
"cl",
"=",
"reduce",
"(",
"count_len",
",",
"self",
".",
"_content",
",",
"0",
")",
"headers",
"[",
"'content-length'",
"]",
"=",
"str",
"(",
"cl",
")",
"ct",
"=",
"headers",
".",
"get",
"(",
"'content-type'",
")",
"# content type encoding available",
"if",
"self",
".",
"encoding",
":",
"ct",
"=",
"ct",
"or",
"'text/plain'",
"if",
"';'",
"not",
"in",
"ct",
":",
"ct",
"=",
"'%s; charset=%s'",
"%",
"(",
"ct",
",",
"self",
".",
"encoding",
")",
"if",
"ct",
":",
"headers",
"[",
"'content-type'",
"]",
"=",
"ct",
"if",
"method",
"==",
"HEAD",
":",
"self",
".",
"_content",
"=",
"(",
")",
"# Cookies",
"if",
"(",
"self",
".",
"status_code",
"<",
"400",
"and",
"self",
".",
"_can_store_cookies",
"and",
"self",
".",
"_cookies",
")",
":",
"for",
"c",
"in",
"self",
".",
"cookies",
".",
"values",
"(",
")",
":",
"headers",
".",
"add",
"(",
"'set-cookie'",
",",
"c",
".",
"OutputString",
"(",
")",
")",
"return",
"headers",
".",
"items",
"(",
")"
] | The list of headers for this response | [
"The",
"list",
"of",
"headers",
"for",
"this",
"response"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/pylib/wsgiresponse.py#L214-L243 |
231,338 | quantmind/pulsar | pulsar/apps/rpc/handlers.py | rpc_method | def rpc_method(func, doc=None, format='json', request_handler=None):
'''A decorator which exposes a function ``func`` as an rpc function.
:param func: The function to expose.
:param doc: Optional doc string. If not provided the doc string of
``func`` will be used.
:param format: Optional output format.
:param request_handler: function which takes ``request``, ``format``
and ``kwargs`` and return a new ``kwargs`` to be passed to ``func``.
It can be used to add additional parameters based on request and
format.
'''
def _(self, *args, **kwargs):
request = args[0]
if request_handler:
kwargs = request_handler(request, format, kwargs)
try:
return func(*args, **kwargs)
except TypeError:
msg = checkarity(func, args, kwargs)
if msg:
raise InvalidParams('Invalid Parameters. %s' % msg)
else:
raise
_.__doc__ = doc or func.__doc__
_.__name__ = func.__name__
_.FromApi = True
return _ | python | def rpc_method(func, doc=None, format='json', request_handler=None):
'''A decorator which exposes a function ``func`` as an rpc function.
:param func: The function to expose.
:param doc: Optional doc string. If not provided the doc string of
``func`` will be used.
:param format: Optional output format.
:param request_handler: function which takes ``request``, ``format``
and ``kwargs`` and return a new ``kwargs`` to be passed to ``func``.
It can be used to add additional parameters based on request and
format.
'''
def _(self, *args, **kwargs):
request = args[0]
if request_handler:
kwargs = request_handler(request, format, kwargs)
try:
return func(*args, **kwargs)
except TypeError:
msg = checkarity(func, args, kwargs)
if msg:
raise InvalidParams('Invalid Parameters. %s' % msg)
else:
raise
_.__doc__ = doc or func.__doc__
_.__name__ = func.__name__
_.FromApi = True
return _ | [
"def",
"rpc_method",
"(",
"func",
",",
"doc",
"=",
"None",
",",
"format",
"=",
"'json'",
",",
"request_handler",
"=",
"None",
")",
":",
"def",
"_",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"args",
"[",
"0",
"]",
"if",
"request_handler",
":",
"kwargs",
"=",
"request_handler",
"(",
"request",
",",
"format",
",",
"kwargs",
")",
"try",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"TypeError",
":",
"msg",
"=",
"checkarity",
"(",
"func",
",",
"args",
",",
"kwargs",
")",
"if",
"msg",
":",
"raise",
"InvalidParams",
"(",
"'Invalid Parameters. %s'",
"%",
"msg",
")",
"else",
":",
"raise",
"_",
".",
"__doc__",
"=",
"doc",
"or",
"func",
".",
"__doc__",
"_",
".",
"__name__",
"=",
"func",
".",
"__name__",
"_",
".",
"FromApi",
"=",
"True",
"return",
"_"
] | A decorator which exposes a function ``func`` as an rpc function.
:param func: The function to expose.
:param doc: Optional doc string. If not provided the doc string of
``func`` will be used.
:param format: Optional output format.
:param request_handler: function which takes ``request``, ``format``
and ``kwargs`` and return a new ``kwargs`` to be passed to ``func``.
It can be used to add additional parameters based on request and
format. | [
"A",
"decorator",
"which",
"exposes",
"a",
"function",
"func",
"as",
"an",
"rpc",
"function",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/rpc/handlers.py#L58-L86 |
231,339 | quantmind/pulsar | pulsar/apps/wsgi/middleware.py | clean_path_middleware | def clean_path_middleware(environ, start_response=None):
'''Clean url from double slashes and redirect if needed.'''
path = environ['PATH_INFO']
if path and '//' in path:
url = re.sub("/+", '/', path)
if not url.startswith('/'):
url = '/%s' % url
qs = environ['QUERY_STRING']
if qs:
url = '%s?%s' % (url, qs)
raise HttpRedirect(url) | python | def clean_path_middleware(environ, start_response=None):
'''Clean url from double slashes and redirect if needed.'''
path = environ['PATH_INFO']
if path and '//' in path:
url = re.sub("/+", '/', path)
if not url.startswith('/'):
url = '/%s' % url
qs = environ['QUERY_STRING']
if qs:
url = '%s?%s' % (url, qs)
raise HttpRedirect(url) | [
"def",
"clean_path_middleware",
"(",
"environ",
",",
"start_response",
"=",
"None",
")",
":",
"path",
"=",
"environ",
"[",
"'PATH_INFO'",
"]",
"if",
"path",
"and",
"'//'",
"in",
"path",
":",
"url",
"=",
"re",
".",
"sub",
"(",
"\"/+\"",
",",
"'/'",
",",
"path",
")",
"if",
"not",
"url",
".",
"startswith",
"(",
"'/'",
")",
":",
"url",
"=",
"'/%s'",
"%",
"url",
"qs",
"=",
"environ",
"[",
"'QUERY_STRING'",
"]",
"if",
"qs",
":",
"url",
"=",
"'%s?%s'",
"%",
"(",
"url",
",",
"qs",
")",
"raise",
"HttpRedirect",
"(",
"url",
")"
] | Clean url from double slashes and redirect if needed. | [
"Clean",
"url",
"from",
"double",
"slashes",
"and",
"redirect",
"if",
"needed",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/middleware.py#L61-L71 |
231,340 | quantmind/pulsar | pulsar/apps/wsgi/middleware.py | authorization_middleware | def authorization_middleware(environ, start_response=None):
'''Parse the ``HTTP_AUTHORIZATION`` key in the ``environ``.
If available, set the ``http.authorization`` key in ``environ`` with
the result obtained from :func:`~.parse_authorization_header` function.
'''
key = 'http.authorization'
c = environ.get(key)
if c is None:
code = 'HTTP_AUTHORIZATION'
if code in environ:
environ[key] = parse_authorization_header(environ[code]) | python | def authorization_middleware(environ, start_response=None):
'''Parse the ``HTTP_AUTHORIZATION`` key in the ``environ``.
If available, set the ``http.authorization`` key in ``environ`` with
the result obtained from :func:`~.parse_authorization_header` function.
'''
key = 'http.authorization'
c = environ.get(key)
if c is None:
code = 'HTTP_AUTHORIZATION'
if code in environ:
environ[key] = parse_authorization_header(environ[code]) | [
"def",
"authorization_middleware",
"(",
"environ",
",",
"start_response",
"=",
"None",
")",
":",
"key",
"=",
"'http.authorization'",
"c",
"=",
"environ",
".",
"get",
"(",
"key",
")",
"if",
"c",
"is",
"None",
":",
"code",
"=",
"'HTTP_AUTHORIZATION'",
"if",
"code",
"in",
"environ",
":",
"environ",
"[",
"key",
"]",
"=",
"parse_authorization_header",
"(",
"environ",
"[",
"code",
"]",
")"
] | Parse the ``HTTP_AUTHORIZATION`` key in the ``environ``.
If available, set the ``http.authorization`` key in ``environ`` with
the result obtained from :func:`~.parse_authorization_header` function. | [
"Parse",
"the",
"HTTP_AUTHORIZATION",
"key",
"in",
"the",
"environ",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/middleware.py#L74-L85 |
231,341 | quantmind/pulsar | pulsar/apps/wsgi/middleware.py | wait_for_body_middleware | async def wait_for_body_middleware(environ, start_response=None):
'''Use this middleware to wait for the full body.
This middleware wait for the full body to be received before letting
other middleware to be processed.
Useful when using synchronous web-frameworks such as :django:`django <>`.
'''
if environ.get('wsgi.async'):
try:
chunk = await environ['wsgi.input'].read()
except TypeError:
chunk = b''
environ['wsgi.input'] = BytesIO(chunk)
environ.pop('wsgi.async') | python | async def wait_for_body_middleware(environ, start_response=None):
'''Use this middleware to wait for the full body.
This middleware wait for the full body to be received before letting
other middleware to be processed.
Useful when using synchronous web-frameworks such as :django:`django <>`.
'''
if environ.get('wsgi.async'):
try:
chunk = await environ['wsgi.input'].read()
except TypeError:
chunk = b''
environ['wsgi.input'] = BytesIO(chunk)
environ.pop('wsgi.async') | [
"async",
"def",
"wait_for_body_middleware",
"(",
"environ",
",",
"start_response",
"=",
"None",
")",
":",
"if",
"environ",
".",
"get",
"(",
"'wsgi.async'",
")",
":",
"try",
":",
"chunk",
"=",
"await",
"environ",
"[",
"'wsgi.input'",
"]",
".",
"read",
"(",
")",
"except",
"TypeError",
":",
"chunk",
"=",
"b''",
"environ",
"[",
"'wsgi.input'",
"]",
"=",
"BytesIO",
"(",
"chunk",
")",
"environ",
".",
"pop",
"(",
"'wsgi.async'",
")"
] | Use this middleware to wait for the full body.
This middleware wait for the full body to be received before letting
other middleware to be processed.
Useful when using synchronous web-frameworks such as :django:`django <>`. | [
"Use",
"this",
"middleware",
"to",
"wait",
"for",
"the",
"full",
"body",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/middleware.py#L88-L102 |
231,342 | quantmind/pulsar | pulsar/apps/wsgi/middleware.py | middleware_in_executor | def middleware_in_executor(middleware):
'''Use this middleware to run a synchronous middleware in the event loop
executor.
Useful when using synchronous web-frameworks such as :django:`django <>`.
'''
@wraps(middleware)
def _(environ, start_response):
loop = get_event_loop()
return loop.run_in_executor(None, middleware, environ, start_response)
return _ | python | def middleware_in_executor(middleware):
'''Use this middleware to run a synchronous middleware in the event loop
executor.
Useful when using synchronous web-frameworks such as :django:`django <>`.
'''
@wraps(middleware)
def _(environ, start_response):
loop = get_event_loop()
return loop.run_in_executor(None, middleware, environ, start_response)
return _ | [
"def",
"middleware_in_executor",
"(",
"middleware",
")",
":",
"@",
"wraps",
"(",
"middleware",
")",
"def",
"_",
"(",
"environ",
",",
"start_response",
")",
":",
"loop",
"=",
"get_event_loop",
"(",
")",
"return",
"loop",
".",
"run_in_executor",
"(",
"None",
",",
"middleware",
",",
"environ",
",",
"start_response",
")",
"return",
"_"
] | Use this middleware to run a synchronous middleware in the event loop
executor.
Useful when using synchronous web-frameworks such as :django:`django <>`. | [
"Use",
"this",
"middleware",
"to",
"run",
"a",
"synchronous",
"middleware",
"in",
"the",
"event",
"loop",
"executor",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/middleware.py#L105-L116 |
231,343 | quantmind/pulsar | examples/philosophers/manage.py | DiningPhilosophers.release_forks | async def release_forks(self, philosopher):
'''The ``philosopher`` has just eaten and is ready to release both
forks.
This method releases them, one by one, by sending the ``put_down``
action to the monitor.
'''
forks = self.forks
self.forks = []
self.started_waiting = 0
for fork in forks:
philosopher.logger.debug('Putting down fork %s', fork)
await philosopher.send('monitor', 'putdown_fork', fork)
await sleep(self.cfg.waiting_period) | python | async def release_forks(self, philosopher):
'''The ``philosopher`` has just eaten and is ready to release both
forks.
This method releases them, one by one, by sending the ``put_down``
action to the monitor.
'''
forks = self.forks
self.forks = []
self.started_waiting = 0
for fork in forks:
philosopher.logger.debug('Putting down fork %s', fork)
await philosopher.send('monitor', 'putdown_fork', fork)
await sleep(self.cfg.waiting_period) | [
"async",
"def",
"release_forks",
"(",
"self",
",",
"philosopher",
")",
":",
"forks",
"=",
"self",
".",
"forks",
"self",
".",
"forks",
"=",
"[",
"]",
"self",
".",
"started_waiting",
"=",
"0",
"for",
"fork",
"in",
"forks",
":",
"philosopher",
".",
"logger",
".",
"debug",
"(",
"'Putting down fork %s'",
",",
"fork",
")",
"await",
"philosopher",
".",
"send",
"(",
"'monitor'",
",",
"'putdown_fork'",
",",
"fork",
")",
"await",
"sleep",
"(",
"self",
".",
"cfg",
".",
"waiting_period",
")"
] | The ``philosopher`` has just eaten and is ready to release both
forks.
This method releases them, one by one, by sending the ``put_down``
action to the monitor. | [
"The",
"philosopher",
"has",
"just",
"eaten",
"and",
"is",
"ready",
"to",
"release",
"both",
"forks",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/philosophers/manage.py#L177-L190 |
231,344 | quantmind/pulsar | examples/helloworld/manage.py | hello | def hello(environ, start_response):
'''The WSGI_ application handler which returns an iterable
over the "Hello World!" message.'''
if environ['REQUEST_METHOD'] == 'GET':
data = b'Hello World!\n'
status = '200 OK'
response_headers = [
('Content-type', 'text/plain'),
('Content-Length', str(len(data)))
]
start_response(status, response_headers)
return iter([data])
else:
raise MethodNotAllowed | python | def hello(environ, start_response):
'''The WSGI_ application handler which returns an iterable
over the "Hello World!" message.'''
if environ['REQUEST_METHOD'] == 'GET':
data = b'Hello World!\n'
status = '200 OK'
response_headers = [
('Content-type', 'text/plain'),
('Content-Length', str(len(data)))
]
start_response(status, response_headers)
return iter([data])
else:
raise MethodNotAllowed | [
"def",
"hello",
"(",
"environ",
",",
"start_response",
")",
":",
"if",
"environ",
"[",
"'REQUEST_METHOD'",
"]",
"==",
"'GET'",
":",
"data",
"=",
"b'Hello World!\\n'",
"status",
"=",
"'200 OK'",
"response_headers",
"=",
"[",
"(",
"'Content-type'",
",",
"'text/plain'",
")",
",",
"(",
"'Content-Length'",
",",
"str",
"(",
"len",
"(",
"data",
")",
")",
")",
"]",
"start_response",
"(",
"status",
",",
"response_headers",
")",
"return",
"iter",
"(",
"[",
"data",
"]",
")",
"else",
":",
"raise",
"MethodNotAllowed"
] | The WSGI_ application handler which returns an iterable
over the "Hello World!" message. | [
"The",
"WSGI_",
"application",
"handler",
"which",
"returns",
"an",
"iterable",
"over",
"the",
"Hello",
"World!",
"message",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/helloworld/manage.py#L20-L33 |
231,345 | quantmind/pulsar | pulsar/apps/wsgi/formdata.py | parse_headers | async def parse_headers(fp, _class=HTTPMessage):
"""Parses only RFC2822 headers from a file pointer.
email Parser wants to see strings rather than bytes.
But a TextIOWrapper around self.rfile would buffer too many bytes
from the stream, bytes which we later need to read as bytes.
So we read the correct bytes here, as bytes, for email Parser
to parse.
"""
headers = []
while True:
line = await fp.readline()
headers.append(line)
if len(headers) > _MAXHEADERS:
raise HttpException("got more than %d headers" % _MAXHEADERS)
if line in (b'\r\n', b'\n', b''):
break
hstring = b''.join(headers).decode('iso-8859-1')
return email.parser.Parser(_class=_class).parsestr(hstring) | python | async def parse_headers(fp, _class=HTTPMessage):
"""Parses only RFC2822 headers from a file pointer.
email Parser wants to see strings rather than bytes.
But a TextIOWrapper around self.rfile would buffer too many bytes
from the stream, bytes which we later need to read as bytes.
So we read the correct bytes here, as bytes, for email Parser
to parse.
"""
headers = []
while True:
line = await fp.readline()
headers.append(line)
if len(headers) > _MAXHEADERS:
raise HttpException("got more than %d headers" % _MAXHEADERS)
if line in (b'\r\n', b'\n', b''):
break
hstring = b''.join(headers).decode('iso-8859-1')
return email.parser.Parser(_class=_class).parsestr(hstring) | [
"async",
"def",
"parse_headers",
"(",
"fp",
",",
"_class",
"=",
"HTTPMessage",
")",
":",
"headers",
"=",
"[",
"]",
"while",
"True",
":",
"line",
"=",
"await",
"fp",
".",
"readline",
"(",
")",
"headers",
".",
"append",
"(",
"line",
")",
"if",
"len",
"(",
"headers",
")",
">",
"_MAXHEADERS",
":",
"raise",
"HttpException",
"(",
"\"got more than %d headers\"",
"%",
"_MAXHEADERS",
")",
"if",
"line",
"in",
"(",
"b'\\r\\n'",
",",
"b'\\n'",
",",
"b''",
")",
":",
"break",
"hstring",
"=",
"b''",
".",
"join",
"(",
"headers",
")",
".",
"decode",
"(",
"'iso-8859-1'",
")",
"return",
"email",
".",
"parser",
".",
"Parser",
"(",
"_class",
"=",
"_class",
")",
".",
"parsestr",
"(",
"hstring",
")"
] | Parses only RFC2822 headers from a file pointer.
email Parser wants to see strings rather than bytes.
But a TextIOWrapper around self.rfile would buffer too many bytes
from the stream, bytes which we later need to read as bytes.
So we read the correct bytes here, as bytes, for email Parser
to parse. | [
"Parses",
"only",
"RFC2822",
"headers",
"from",
"a",
"file",
"pointer",
".",
"email",
"Parser",
"wants",
"to",
"see",
"strings",
"rather",
"than",
"bytes",
".",
"But",
"a",
"TextIOWrapper",
"around",
"self",
".",
"rfile",
"would",
"buffer",
"too",
"many",
"bytes",
"from",
"the",
"stream",
"bytes",
"which",
"we",
"later",
"need",
"to",
"read",
"as",
"bytes",
".",
"So",
"we",
"read",
"the",
"correct",
"bytes",
"here",
"as",
"bytes",
"for",
"email",
"Parser",
"to",
"parse",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/formdata.py#L372-L389 |
231,346 | quantmind/pulsar | pulsar/apps/wsgi/formdata.py | HttpBodyReader._waiting_expect | def _waiting_expect(self):
'''``True`` when the client is waiting for 100 Continue.
'''
if self._expect_sent is None:
if self.environ.get('HTTP_EXPECT', '').lower() == '100-continue':
return True
self._expect_sent = ''
return False | python | def _waiting_expect(self):
'''``True`` when the client is waiting for 100 Continue.
'''
if self._expect_sent is None:
if self.environ.get('HTTP_EXPECT', '').lower() == '100-continue':
return True
self._expect_sent = ''
return False | [
"def",
"_waiting_expect",
"(",
"self",
")",
":",
"if",
"self",
".",
"_expect_sent",
"is",
"None",
":",
"if",
"self",
".",
"environ",
".",
"get",
"(",
"'HTTP_EXPECT'",
",",
"''",
")",
".",
"lower",
"(",
")",
"==",
"'100-continue'",
":",
"return",
"True",
"self",
".",
"_expect_sent",
"=",
"''",
"return",
"False"
] | ``True`` when the client is waiting for 100 Continue. | [
"True",
"when",
"the",
"client",
"is",
"waiting",
"for",
"100",
"Continue",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/formdata.py#L82-L89 |
231,347 | quantmind/pulsar | pulsar/apps/wsgi/formdata.py | MultipartPart.base64 | def base64(self, charset=None):
'''Data encoded as base 64'''
return b64encode(self.bytes()).decode(charset or self.charset) | python | def base64(self, charset=None):
'''Data encoded as base 64'''
return b64encode(self.bytes()).decode(charset or self.charset) | [
"def",
"base64",
"(",
"self",
",",
"charset",
"=",
"None",
")",
":",
"return",
"b64encode",
"(",
"self",
".",
"bytes",
"(",
")",
")",
".",
"decode",
"(",
"charset",
"or",
"self",
".",
"charset",
")"
] | Data encoded as base 64 | [
"Data",
"encoded",
"as",
"base",
"64"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/formdata.py#L318-L320 |
231,348 | quantmind/pulsar | pulsar/apps/wsgi/formdata.py | MultipartPart.feed_data | def feed_data(self, data):
"""Feed new data into the MultiPart parser or the data stream"""
if data:
self._bytes.append(data)
if self.parser.stream:
self.parser.stream(self)
else:
self.parser.buffer.extend(data) | python | def feed_data(self, data):
"""Feed new data into the MultiPart parser or the data stream"""
if data:
self._bytes.append(data)
if self.parser.stream:
self.parser.stream(self)
else:
self.parser.buffer.extend(data) | [
"def",
"feed_data",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
":",
"self",
".",
"_bytes",
".",
"append",
"(",
"data",
")",
"if",
"self",
".",
"parser",
".",
"stream",
":",
"self",
".",
"parser",
".",
"stream",
"(",
"self",
")",
"else",
":",
"self",
".",
"parser",
".",
"buffer",
".",
"extend",
"(",
"data",
")"
] | Feed new data into the MultiPart parser or the data stream | [
"Feed",
"new",
"data",
"into",
"the",
"MultiPart",
"parser",
"or",
"the",
"data",
"stream"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/formdata.py#L329-L336 |
231,349 | quantmind/pulsar | examples/proxyserver/manage.py | server | def server(name='proxy-server', headers_middleware=None,
server_software=None, **kwargs):
'''Function to Create a WSGI Proxy Server.'''
if headers_middleware is None:
headers_middleware = [x_forwarded_for]
wsgi_proxy = ProxyServerWsgiHandler(headers_middleware)
kwargs['server_software'] = server_software or SERVER_SOFTWARE
return wsgi.WSGIServer(wsgi_proxy, name=name, **kwargs) | python | def server(name='proxy-server', headers_middleware=None,
server_software=None, **kwargs):
'''Function to Create a WSGI Proxy Server.'''
if headers_middleware is None:
headers_middleware = [x_forwarded_for]
wsgi_proxy = ProxyServerWsgiHandler(headers_middleware)
kwargs['server_software'] = server_software or SERVER_SOFTWARE
return wsgi.WSGIServer(wsgi_proxy, name=name, **kwargs) | [
"def",
"server",
"(",
"name",
"=",
"'proxy-server'",
",",
"headers_middleware",
"=",
"None",
",",
"server_software",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"headers_middleware",
"is",
"None",
":",
"headers_middleware",
"=",
"[",
"x_forwarded_for",
"]",
"wsgi_proxy",
"=",
"ProxyServerWsgiHandler",
"(",
"headers_middleware",
")",
"kwargs",
"[",
"'server_software'",
"]",
"=",
"server_software",
"or",
"SERVER_SOFTWARE",
"return",
"wsgi",
".",
"WSGIServer",
"(",
"wsgi_proxy",
",",
"name",
"=",
"name",
",",
"*",
"*",
"kwargs",
")"
] | Function to Create a WSGI Proxy Server. | [
"Function",
"to",
"Create",
"a",
"WSGI",
"Proxy",
"Server",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/proxyserver/manage.py#L241-L248 |
231,350 | quantmind/pulsar | examples/proxyserver/manage.py | TunnelResponse.request | async def request(self):
'''Perform the Http request to the upstream server
'''
request_headers = self.request_headers()
environ = self.environ
method = environ['REQUEST_METHOD']
data = None
if method in ENCODE_BODY_METHODS:
data = DataIterator(self)
http = self.wsgi.http_client
try:
await http.request(method,
environ['RAW_URI'],
data=data,
headers=request_headers,
version=environ['SERVER_PROTOCOL'],
pre_request=self.pre_request)
except Exception as exc:
self.error(exc) | python | async def request(self):
'''Perform the Http request to the upstream server
'''
request_headers = self.request_headers()
environ = self.environ
method = environ['REQUEST_METHOD']
data = None
if method in ENCODE_BODY_METHODS:
data = DataIterator(self)
http = self.wsgi.http_client
try:
await http.request(method,
environ['RAW_URI'],
data=data,
headers=request_headers,
version=environ['SERVER_PROTOCOL'],
pre_request=self.pre_request)
except Exception as exc:
self.error(exc) | [
"async",
"def",
"request",
"(",
"self",
")",
":",
"request_headers",
"=",
"self",
".",
"request_headers",
"(",
")",
"environ",
"=",
"self",
".",
"environ",
"method",
"=",
"environ",
"[",
"'REQUEST_METHOD'",
"]",
"data",
"=",
"None",
"if",
"method",
"in",
"ENCODE_BODY_METHODS",
":",
"data",
"=",
"DataIterator",
"(",
"self",
")",
"http",
"=",
"self",
".",
"wsgi",
".",
"http_client",
"try",
":",
"await",
"http",
".",
"request",
"(",
"method",
",",
"environ",
"[",
"'RAW_URI'",
"]",
",",
"data",
"=",
"data",
",",
"headers",
"=",
"request_headers",
",",
"version",
"=",
"environ",
"[",
"'SERVER_PROTOCOL'",
"]",
",",
"pre_request",
"=",
"self",
".",
"pre_request",
")",
"except",
"Exception",
"as",
"exc",
":",
"self",
".",
"error",
"(",
"exc",
")"
] | Perform the Http request to the upstream server | [
"Perform",
"the",
"Http",
"request",
"to",
"the",
"upstream",
"server"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/proxyserver/manage.py#L112-L130 |
231,351 | quantmind/pulsar | examples/proxyserver/manage.py | TunnelResponse.pre_request | def pre_request(self, response, exc=None):
"""Start the tunnel.
This is a callback fired once a connection with upstream server is
established.
"""
if response.request.method == 'CONNECT':
self.start_response(
'200 Connection established',
[('content-length', '0')]
)
# send empty byte so that headers are sent
self.future.set_result([b''])
# proxy - server connection
upstream = response.connection
# client - proxy connection
dostream = self.connection
# Upgrade downstream connection
dostream.upgrade(partial(StreamTunnel.create, upstream))
#
# upstream upgrade
upstream.upgrade(partial(StreamTunnel.create, dostream))
response.fire_event('post_request')
# abort the event
raise AbortEvent
else:
response.event('data_processed').bind(self.data_processed)
response.event('post_request').bind(self.post_request) | python | def pre_request(self, response, exc=None):
"""Start the tunnel.
This is a callback fired once a connection with upstream server is
established.
"""
if response.request.method == 'CONNECT':
self.start_response(
'200 Connection established',
[('content-length', '0')]
)
# send empty byte so that headers are sent
self.future.set_result([b''])
# proxy - server connection
upstream = response.connection
# client - proxy connection
dostream = self.connection
# Upgrade downstream connection
dostream.upgrade(partial(StreamTunnel.create, upstream))
#
# upstream upgrade
upstream.upgrade(partial(StreamTunnel.create, dostream))
response.fire_event('post_request')
# abort the event
raise AbortEvent
else:
response.event('data_processed').bind(self.data_processed)
response.event('post_request').bind(self.post_request) | [
"def",
"pre_request",
"(",
"self",
",",
"response",
",",
"exc",
"=",
"None",
")",
":",
"if",
"response",
".",
"request",
".",
"method",
"==",
"'CONNECT'",
":",
"self",
".",
"start_response",
"(",
"'200 Connection established'",
",",
"[",
"(",
"'content-length'",
",",
"'0'",
")",
"]",
")",
"# send empty byte so that headers are sent",
"self",
".",
"future",
".",
"set_result",
"(",
"[",
"b''",
"]",
")",
"# proxy - server connection",
"upstream",
"=",
"response",
".",
"connection",
"# client - proxy connection",
"dostream",
"=",
"self",
".",
"connection",
"# Upgrade downstream connection",
"dostream",
".",
"upgrade",
"(",
"partial",
"(",
"StreamTunnel",
".",
"create",
",",
"upstream",
")",
")",
"#",
"# upstream upgrade",
"upstream",
".",
"upgrade",
"(",
"partial",
"(",
"StreamTunnel",
".",
"create",
",",
"dostream",
")",
")",
"response",
".",
"fire_event",
"(",
"'post_request'",
")",
"# abort the event",
"raise",
"AbortEvent",
"else",
":",
"response",
".",
"event",
"(",
"'data_processed'",
")",
".",
"bind",
"(",
"self",
".",
"data_processed",
")",
"response",
".",
"event",
"(",
"'post_request'",
")",
".",
"bind",
"(",
"self",
".",
"post_request",
")"
] | Start the tunnel.
This is a callback fired once a connection with upstream server is
established. | [
"Start",
"the",
"tunnel",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/proxyserver/manage.py#L157-L184 |
231,352 | quantmind/pulsar | pulsar/utils/pylib/protocols.py | Protocol.connection_lost | def connection_lost(self, exc=None):
"""Fires the ``connection_lost`` event.
"""
if self._loop.get_debug():
self.producer.logger.debug('connection lost %s', self)
self.event('connection_lost').fire(exc=exc) | python | def connection_lost(self, exc=None):
"""Fires the ``connection_lost`` event.
"""
if self._loop.get_debug():
self.producer.logger.debug('connection lost %s', self)
self.event('connection_lost').fire(exc=exc) | [
"def",
"connection_lost",
"(",
"self",
",",
"exc",
"=",
"None",
")",
":",
"if",
"self",
".",
"_loop",
".",
"get_debug",
"(",
")",
":",
"self",
".",
"producer",
".",
"logger",
".",
"debug",
"(",
"'connection lost %s'",
",",
"self",
")",
"self",
".",
"event",
"(",
"'connection_lost'",
")",
".",
"fire",
"(",
"exc",
"=",
"exc",
")"
] | Fires the ``connection_lost`` event. | [
"Fires",
"the",
"connection_lost",
"event",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/pylib/protocols.py#L163-L168 |
231,353 | quantmind/pulsar | pulsar/utils/pylib/protocols.py | ProtocolConsumer.start | def start(self, request=None):
"""Starts processing the request for this protocol consumer.
There is no need to override this method,
implement :meth:`start_request` instead.
If either :attr:`connection` or :attr:`transport` are missing, a
:class:`RuntimeError` occurs.
For server side consumer, this method simply fires the ``pre_request``
event.
"""
self.connection.processed += 1
self.producer.requests_processed += 1
self.event('post_request').bind(self.finished_reading)
self.request = request or self.create_request()
try:
self.fire_event('pre_request')
except AbortEvent:
if self._loop.get_debug():
self.producer.logger.debug('Abort request %s', request)
else:
self.start_request() | python | def start(self, request=None):
"""Starts processing the request for this protocol consumer.
There is no need to override this method,
implement :meth:`start_request` instead.
If either :attr:`connection` or :attr:`transport` are missing, a
:class:`RuntimeError` occurs.
For server side consumer, this method simply fires the ``pre_request``
event.
"""
self.connection.processed += 1
self.producer.requests_processed += 1
self.event('post_request').bind(self.finished_reading)
self.request = request or self.create_request()
try:
self.fire_event('pre_request')
except AbortEvent:
if self._loop.get_debug():
self.producer.logger.debug('Abort request %s', request)
else:
self.start_request() | [
"def",
"start",
"(",
"self",
",",
"request",
"=",
"None",
")",
":",
"self",
".",
"connection",
".",
"processed",
"+=",
"1",
"self",
".",
"producer",
".",
"requests_processed",
"+=",
"1",
"self",
".",
"event",
"(",
"'post_request'",
")",
".",
"bind",
"(",
"self",
".",
"finished_reading",
")",
"self",
".",
"request",
"=",
"request",
"or",
"self",
".",
"create_request",
"(",
")",
"try",
":",
"self",
".",
"fire_event",
"(",
"'pre_request'",
")",
"except",
"AbortEvent",
":",
"if",
"self",
".",
"_loop",
".",
"get_debug",
"(",
")",
":",
"self",
".",
"producer",
".",
"logger",
".",
"debug",
"(",
"'Abort request %s'",
",",
"request",
")",
"else",
":",
"self",
".",
"start_request",
"(",
")"
] | Starts processing the request for this protocol consumer.
There is no need to override this method,
implement :meth:`start_request` instead.
If either :attr:`connection` or :attr:`transport` are missing, a
:class:`RuntimeError` occurs.
For server side consumer, this method simply fires the ``pre_request``
event. | [
"Starts",
"processing",
"the",
"request",
"for",
"this",
"protocol",
"consumer",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/pylib/protocols.py#L216-L237 |
231,354 | quantmind/pulsar | pulsar/utils/log.py | process_global | def process_global(name, val=None, setval=False):
'''Access and set global variables for the current process.'''
p = current_process()
if not hasattr(p, '_pulsar_globals'):
p._pulsar_globals = {'lock': Lock()}
if setval:
p._pulsar_globals[name] = val
else:
return p._pulsar_globals.get(name) | python | def process_global(name, val=None, setval=False):
'''Access and set global variables for the current process.'''
p = current_process()
if not hasattr(p, '_pulsar_globals'):
p._pulsar_globals = {'lock': Lock()}
if setval:
p._pulsar_globals[name] = val
else:
return p._pulsar_globals.get(name) | [
"def",
"process_global",
"(",
"name",
",",
"val",
"=",
"None",
",",
"setval",
"=",
"False",
")",
":",
"p",
"=",
"current_process",
"(",
")",
"if",
"not",
"hasattr",
"(",
"p",
",",
"'_pulsar_globals'",
")",
":",
"p",
".",
"_pulsar_globals",
"=",
"{",
"'lock'",
":",
"Lock",
"(",
")",
"}",
"if",
"setval",
":",
"p",
".",
"_pulsar_globals",
"[",
"name",
"]",
"=",
"val",
"else",
":",
"return",
"p",
".",
"_pulsar_globals",
".",
"get",
"(",
"name",
")"
] | Access and set global variables for the current process. | [
"Access",
"and",
"set",
"global",
"variables",
"for",
"the",
"current",
"process",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/log.py#L213-L221 |
231,355 | quantmind/pulsar | pulsar/utils/httpurl.py | get_environ_proxies | def get_environ_proxies():
"""Return a dict of environment proxies. From requests_."""
proxy_keys = [
'all',
'http',
'https',
'ftp',
'socks',
'ws',
'wss',
'no'
]
def get_proxy(k):
return os.environ.get(k) or os.environ.get(k.upper())
proxies = [(key, get_proxy(key + '_proxy')) for key in proxy_keys]
return dict([(key, val) for (key, val) in proxies if val]) | python | def get_environ_proxies():
"""Return a dict of environment proxies. From requests_."""
proxy_keys = [
'all',
'http',
'https',
'ftp',
'socks',
'ws',
'wss',
'no'
]
def get_proxy(k):
return os.environ.get(k) or os.environ.get(k.upper())
proxies = [(key, get_proxy(key + '_proxy')) for key in proxy_keys]
return dict([(key, val) for (key, val) in proxies if val]) | [
"def",
"get_environ_proxies",
"(",
")",
":",
"proxy_keys",
"=",
"[",
"'all'",
",",
"'http'",
",",
"'https'",
",",
"'ftp'",
",",
"'socks'",
",",
"'ws'",
",",
"'wss'",
",",
"'no'",
"]",
"def",
"get_proxy",
"(",
"k",
")",
":",
"return",
"os",
".",
"environ",
".",
"get",
"(",
"k",
")",
"or",
"os",
".",
"environ",
".",
"get",
"(",
"k",
".",
"upper",
"(",
")",
")",
"proxies",
"=",
"[",
"(",
"key",
",",
"get_proxy",
"(",
"key",
"+",
"'_proxy'",
")",
")",
"for",
"key",
"in",
"proxy_keys",
"]",
"return",
"dict",
"(",
"[",
"(",
"key",
",",
"val",
")",
"for",
"(",
"key",
",",
"val",
")",
"in",
"proxies",
"if",
"val",
"]",
")"
] | Return a dict of environment proxies. From requests_. | [
"Return",
"a",
"dict",
"of",
"environment",
"proxies",
".",
"From",
"requests_",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/httpurl.py#L310-L328 |
231,356 | quantmind/pulsar | pulsar/utils/httpurl.py | has_vary_header | def has_vary_header(response, header_query):
"""
Checks to see if the response has a given header name in its Vary header.
"""
if not response.has_header('Vary'):
return False
vary_headers = cc_delim_re.split(response['Vary'])
existing_headers = set([header.lower() for header in vary_headers])
return header_query.lower() in existing_headers | python | def has_vary_header(response, header_query):
"""
Checks to see if the response has a given header name in its Vary header.
"""
if not response.has_header('Vary'):
return False
vary_headers = cc_delim_re.split(response['Vary'])
existing_headers = set([header.lower() for header in vary_headers])
return header_query.lower() in existing_headers | [
"def",
"has_vary_header",
"(",
"response",
",",
"header_query",
")",
":",
"if",
"not",
"response",
".",
"has_header",
"(",
"'Vary'",
")",
":",
"return",
"False",
"vary_headers",
"=",
"cc_delim_re",
".",
"split",
"(",
"response",
"[",
"'Vary'",
"]",
")",
"existing_headers",
"=",
"set",
"(",
"[",
"header",
".",
"lower",
"(",
")",
"for",
"header",
"in",
"vary_headers",
"]",
")",
"return",
"header_query",
".",
"lower",
"(",
")",
"in",
"existing_headers"
] | Checks to see if the response has a given header name in its Vary header. | [
"Checks",
"to",
"see",
"if",
"the",
"response",
"has",
"a",
"given",
"header",
"name",
"in",
"its",
"Vary",
"header",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/httpurl.py#L475-L483 |
231,357 | quantmind/pulsar | pulsar/apps/ds/client.py | PulsarStoreClient.execute | def execute(self, request):
'''Execute a new ``request``.
'''
handle = None
if request:
request[0] = command = to_string(request[0]).lower()
info = COMMANDS_INFO.get(command)
if info:
handle = getattr(self.store, info.method_name)
#
if self.channels or self.patterns:
if command not in self.store.SUBSCRIBE_COMMANDS:
return self.reply_error(self.store.PUBSUB_ONLY)
if self.blocked:
return self.reply_error('Blocked client cannot request')
if self.transaction is not None and command not in 'exec':
self.transaction.append((handle, request))
return self.connection.write(self.store.QUEUED)
self.execute_command(handle, request) | python | def execute(self, request):
'''Execute a new ``request``.
'''
handle = None
if request:
request[0] = command = to_string(request[0]).lower()
info = COMMANDS_INFO.get(command)
if info:
handle = getattr(self.store, info.method_name)
#
if self.channels or self.patterns:
if command not in self.store.SUBSCRIBE_COMMANDS:
return self.reply_error(self.store.PUBSUB_ONLY)
if self.blocked:
return self.reply_error('Blocked client cannot request')
if self.transaction is not None and command not in 'exec':
self.transaction.append((handle, request))
return self.connection.write(self.store.QUEUED)
self.execute_command(handle, request) | [
"def",
"execute",
"(",
"self",
",",
"request",
")",
":",
"handle",
"=",
"None",
"if",
"request",
":",
"request",
"[",
"0",
"]",
"=",
"command",
"=",
"to_string",
"(",
"request",
"[",
"0",
"]",
")",
".",
"lower",
"(",
")",
"info",
"=",
"COMMANDS_INFO",
".",
"get",
"(",
"command",
")",
"if",
"info",
":",
"handle",
"=",
"getattr",
"(",
"self",
".",
"store",
",",
"info",
".",
"method_name",
")",
"#",
"if",
"self",
".",
"channels",
"or",
"self",
".",
"patterns",
":",
"if",
"command",
"not",
"in",
"self",
".",
"store",
".",
"SUBSCRIBE_COMMANDS",
":",
"return",
"self",
".",
"reply_error",
"(",
"self",
".",
"store",
".",
"PUBSUB_ONLY",
")",
"if",
"self",
".",
"blocked",
":",
"return",
"self",
".",
"reply_error",
"(",
"'Blocked client cannot request'",
")",
"if",
"self",
".",
"transaction",
"is",
"not",
"None",
"and",
"command",
"not",
"in",
"'exec'",
":",
"self",
".",
"transaction",
".",
"append",
"(",
"(",
"handle",
",",
"request",
")",
")",
"return",
"self",
".",
"connection",
".",
"write",
"(",
"self",
".",
"store",
".",
"QUEUED",
")",
"self",
".",
"execute_command",
"(",
"handle",
",",
"request",
")"
] | Execute a new ``request``. | [
"Execute",
"a",
"new",
"request",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/ds/client.py#L65-L83 |
231,358 | quantmind/pulsar | pulsar/apps/http/plugins.py | handle_cookies | def handle_cookies(response, exc=None):
'''Handle response cookies.
'''
if exc:
return
headers = response.headers
request = response.request
client = request.client
response._cookies = c = SimpleCookie()
if 'set-cookie' in headers or 'set-cookie2' in headers:
for cookie in (headers.get('set-cookie2'),
headers.get('set-cookie')):
if cookie:
c.load(cookie)
if client.store_cookies:
client.cookies.extract_cookies(response, request) | python | def handle_cookies(response, exc=None):
'''Handle response cookies.
'''
if exc:
return
headers = response.headers
request = response.request
client = request.client
response._cookies = c = SimpleCookie()
if 'set-cookie' in headers or 'set-cookie2' in headers:
for cookie in (headers.get('set-cookie2'),
headers.get('set-cookie')):
if cookie:
c.load(cookie)
if client.store_cookies:
client.cookies.extract_cookies(response, request) | [
"def",
"handle_cookies",
"(",
"response",
",",
"exc",
"=",
"None",
")",
":",
"if",
"exc",
":",
"return",
"headers",
"=",
"response",
".",
"headers",
"request",
"=",
"response",
".",
"request",
"client",
"=",
"request",
".",
"client",
"response",
".",
"_cookies",
"=",
"c",
"=",
"SimpleCookie",
"(",
")",
"if",
"'set-cookie'",
"in",
"headers",
"or",
"'set-cookie2'",
"in",
"headers",
":",
"for",
"cookie",
"in",
"(",
"headers",
".",
"get",
"(",
"'set-cookie2'",
")",
",",
"headers",
".",
"get",
"(",
"'set-cookie'",
")",
")",
":",
"if",
"cookie",
":",
"c",
".",
"load",
"(",
"cookie",
")",
"if",
"client",
".",
"store_cookies",
":",
"client",
".",
"cookies",
".",
"extract_cookies",
"(",
"response",
",",
"request",
")"
] | Handle response cookies. | [
"Handle",
"response",
"cookies",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/plugins.py#L191-L206 |
231,359 | quantmind/pulsar | pulsar/apps/http/plugins.py | WebSocket.on_headers | def on_headers(self, response, exc=None):
'''Websocket upgrade as ``on_headers`` event.'''
if response.status_code == 101:
connection = response.connection
request = response.request
handler = request.websocket_handler
if not handler:
handler = WS()
parser = request.client.frame_parser(kind=1)
consumer = partial(WebSocketClient.create,
response, handler, parser)
connection.upgrade(consumer)
response.event('post_request').fire()
websocket = connection.current_consumer()
response.request_again = lambda r: websocket | python | def on_headers(self, response, exc=None):
'''Websocket upgrade as ``on_headers`` event.'''
if response.status_code == 101:
connection = response.connection
request = response.request
handler = request.websocket_handler
if not handler:
handler = WS()
parser = request.client.frame_parser(kind=1)
consumer = partial(WebSocketClient.create,
response, handler, parser)
connection.upgrade(consumer)
response.event('post_request').fire()
websocket = connection.current_consumer()
response.request_again = lambda r: websocket | [
"def",
"on_headers",
"(",
"self",
",",
"response",
",",
"exc",
"=",
"None",
")",
":",
"if",
"response",
".",
"status_code",
"==",
"101",
":",
"connection",
"=",
"response",
".",
"connection",
"request",
"=",
"response",
".",
"request",
"handler",
"=",
"request",
".",
"websocket_handler",
"if",
"not",
"handler",
":",
"handler",
"=",
"WS",
"(",
")",
"parser",
"=",
"request",
".",
"client",
".",
"frame_parser",
"(",
"kind",
"=",
"1",
")",
"consumer",
"=",
"partial",
"(",
"WebSocketClient",
".",
"create",
",",
"response",
",",
"handler",
",",
"parser",
")",
"connection",
".",
"upgrade",
"(",
"consumer",
")",
"response",
".",
"event",
"(",
"'post_request'",
")",
".",
"fire",
"(",
")",
"websocket",
"=",
"connection",
".",
"current_consumer",
"(",
")",
"response",
".",
"request_again",
"=",
"lambda",
"r",
":",
"websocket"
] | Websocket upgrade as ``on_headers`` event. | [
"Websocket",
"upgrade",
"as",
"on_headers",
"event",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/plugins.py#L230-L245 |
231,360 | quantmind/pulsar | pulsar/utils/path.py | Path.add2python | def add2python(self, module=None, up=0, down=None, front=False,
must_exist=True):
'''Add a directory to the python path.
:parameter module: Optional module name to try to import once we
have found the directory
:parameter up: number of level to go up the directory three from
:attr:`local_path`.
:parameter down: Optional tuple of directory names to travel down
once we have gone *up* levels.
:parameter front: Boolean indicating if we want to insert the new
path at the front of ``sys.path`` using
``sys.path.insert(0,path)``.
:parameter must_exist: Boolean indicating if the module must exists.
'''
if module:
try:
return import_module(module)
except ImportError:
pass
dir = self.dir().ancestor(up)
if down:
dir = dir.join(*down)
if dir.isdir():
if dir not in sys.path:
if front:
sys.path.insert(0, dir)
else:
sys.path.append(dir)
elif must_exist:
raise ImportError('Directory {0} not available'.format(dir))
else:
return None
if module:
try:
return import_module(module)
except ImportError:
if must_exist:
raise | python | def add2python(self, module=None, up=0, down=None, front=False,
must_exist=True):
'''Add a directory to the python path.
:parameter module: Optional module name to try to import once we
have found the directory
:parameter up: number of level to go up the directory three from
:attr:`local_path`.
:parameter down: Optional tuple of directory names to travel down
once we have gone *up* levels.
:parameter front: Boolean indicating if we want to insert the new
path at the front of ``sys.path`` using
``sys.path.insert(0,path)``.
:parameter must_exist: Boolean indicating if the module must exists.
'''
if module:
try:
return import_module(module)
except ImportError:
pass
dir = self.dir().ancestor(up)
if down:
dir = dir.join(*down)
if dir.isdir():
if dir not in sys.path:
if front:
sys.path.insert(0, dir)
else:
sys.path.append(dir)
elif must_exist:
raise ImportError('Directory {0} not available'.format(dir))
else:
return None
if module:
try:
return import_module(module)
except ImportError:
if must_exist:
raise | [
"def",
"add2python",
"(",
"self",
",",
"module",
"=",
"None",
",",
"up",
"=",
"0",
",",
"down",
"=",
"None",
",",
"front",
"=",
"False",
",",
"must_exist",
"=",
"True",
")",
":",
"if",
"module",
":",
"try",
":",
"return",
"import_module",
"(",
"module",
")",
"except",
"ImportError",
":",
"pass",
"dir",
"=",
"self",
".",
"dir",
"(",
")",
".",
"ancestor",
"(",
"up",
")",
"if",
"down",
":",
"dir",
"=",
"dir",
".",
"join",
"(",
"*",
"down",
")",
"if",
"dir",
".",
"isdir",
"(",
")",
":",
"if",
"dir",
"not",
"in",
"sys",
".",
"path",
":",
"if",
"front",
":",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"dir",
")",
"else",
":",
"sys",
".",
"path",
".",
"append",
"(",
"dir",
")",
"elif",
"must_exist",
":",
"raise",
"ImportError",
"(",
"'Directory {0} not available'",
".",
"format",
"(",
"dir",
")",
")",
"else",
":",
"return",
"None",
"if",
"module",
":",
"try",
":",
"return",
"import_module",
"(",
"module",
")",
"except",
"ImportError",
":",
"if",
"must_exist",
":",
"raise"
] | Add a directory to the python path.
:parameter module: Optional module name to try to import once we
have found the directory
:parameter up: number of level to go up the directory three from
:attr:`local_path`.
:parameter down: Optional tuple of directory names to travel down
once we have gone *up* levels.
:parameter front: Boolean indicating if we want to insert the new
path at the front of ``sys.path`` using
``sys.path.insert(0,path)``.
:parameter must_exist: Boolean indicating if the module must exists. | [
"Add",
"a",
"directory",
"to",
"the",
"python",
"path",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/path.py#L79-L117 |
231,361 | quantmind/pulsar | examples/httpbin/manage.py | HttpBin.get | def get(self, request):
'''The home page of this router'''
ul = Html('ul')
for router in sorted(self.routes, key=lambda r: r.creation_count):
a = router.link(escape(router.route.path))
a.addClass(router.name)
for method in METHODS:
if router.getparam(method):
a.addClass(method)
li = Html('li', a, ' %s' % router.getparam('title', ''))
ul.append(li)
title = 'Pulsar'
html = request.html_document
html.head.title = title
html.head.links.append('httpbin.css')
html.head.links.append('favicon.ico', rel="icon", type='image/x-icon')
html.head.scripts.append('httpbin.js')
ul = ul.to_string(request)
templ = asset('template.html')
body = templ % (title, JAPANESE, CHINESE, version, pyversion, ul)
html.body.append(body)
return html.http_response(request) | python | def get(self, request):
'''The home page of this router'''
ul = Html('ul')
for router in sorted(self.routes, key=lambda r: r.creation_count):
a = router.link(escape(router.route.path))
a.addClass(router.name)
for method in METHODS:
if router.getparam(method):
a.addClass(method)
li = Html('li', a, ' %s' % router.getparam('title', ''))
ul.append(li)
title = 'Pulsar'
html = request.html_document
html.head.title = title
html.head.links.append('httpbin.css')
html.head.links.append('favicon.ico', rel="icon", type='image/x-icon')
html.head.scripts.append('httpbin.js')
ul = ul.to_string(request)
templ = asset('template.html')
body = templ % (title, JAPANESE, CHINESE, version, pyversion, ul)
html.body.append(body)
return html.http_response(request) | [
"def",
"get",
"(",
"self",
",",
"request",
")",
":",
"ul",
"=",
"Html",
"(",
"'ul'",
")",
"for",
"router",
"in",
"sorted",
"(",
"self",
".",
"routes",
",",
"key",
"=",
"lambda",
"r",
":",
"r",
".",
"creation_count",
")",
":",
"a",
"=",
"router",
".",
"link",
"(",
"escape",
"(",
"router",
".",
"route",
".",
"path",
")",
")",
"a",
".",
"addClass",
"(",
"router",
".",
"name",
")",
"for",
"method",
"in",
"METHODS",
":",
"if",
"router",
".",
"getparam",
"(",
"method",
")",
":",
"a",
".",
"addClass",
"(",
"method",
")",
"li",
"=",
"Html",
"(",
"'li'",
",",
"a",
",",
"' %s'",
"%",
"router",
".",
"getparam",
"(",
"'title'",
",",
"''",
")",
")",
"ul",
".",
"append",
"(",
"li",
")",
"title",
"=",
"'Pulsar'",
"html",
"=",
"request",
".",
"html_document",
"html",
".",
"head",
".",
"title",
"=",
"title",
"html",
".",
"head",
".",
"links",
".",
"append",
"(",
"'httpbin.css'",
")",
"html",
".",
"head",
".",
"links",
".",
"append",
"(",
"'favicon.ico'",
",",
"rel",
"=",
"\"icon\"",
",",
"type",
"=",
"'image/x-icon'",
")",
"html",
".",
"head",
".",
"scripts",
".",
"append",
"(",
"'httpbin.js'",
")",
"ul",
"=",
"ul",
".",
"to_string",
"(",
"request",
")",
"templ",
"=",
"asset",
"(",
"'template.html'",
")",
"body",
"=",
"templ",
"%",
"(",
"title",
",",
"JAPANESE",
",",
"CHINESE",
",",
"version",
",",
"pyversion",
",",
"ul",
")",
"html",
".",
"body",
".",
"append",
"(",
"body",
")",
"return",
"html",
".",
"http_response",
"(",
"request",
")"
] | The home page of this router | [
"The",
"home",
"page",
"of",
"this",
"router"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/httpbin/manage.py#L106-L127 |
231,362 | quantmind/pulsar | examples/httpbin/manage.py | HttpBin.stats | def stats(self, request):
'''Live stats for the server.
Try sending lots of requests
'''
# scheme = 'wss' if request.is_secure else 'ws'
# host = request.get('HTTP_HOST')
# address = '%s://%s/stats' % (scheme, host)
doc = HtmlDocument(title='Live server stats', media_path='/assets/')
# docs.head.scripts
return doc.http_response(request) | python | def stats(self, request):
'''Live stats for the server.
Try sending lots of requests
'''
# scheme = 'wss' if request.is_secure else 'ws'
# host = request.get('HTTP_HOST')
# address = '%s://%s/stats' % (scheme, host)
doc = HtmlDocument(title='Live server stats', media_path='/assets/')
# docs.head.scripts
return doc.http_response(request) | [
"def",
"stats",
"(",
"self",
",",
"request",
")",
":",
"# scheme = 'wss' if request.is_secure else 'ws'",
"# host = request.get('HTTP_HOST')",
"# address = '%s://%s/stats' % (scheme, host)",
"doc",
"=",
"HtmlDocument",
"(",
"title",
"=",
"'Live server stats'",
",",
"media_path",
"=",
"'/assets/'",
")",
"# docs.head.scripts",
"return",
"doc",
".",
"http_response",
"(",
"request",
")"
] | Live stats for the server.
Try sending lots of requests | [
"Live",
"stats",
"for",
"the",
"server",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/httpbin/manage.py#L273-L283 |
231,363 | quantmind/pulsar | pulsar/utils/system/winprocess.py | get_preparation_data | def get_preparation_data(name):
'''
Return info about parent needed by child to unpickle process object.
Monkey-patch from
'''
d = dict(
name=name,
sys_path=sys.path,
sys_argv=sys.argv,
log_to_stderr=_log_to_stderr,
orig_dir=process.ORIGINAL_DIR,
authkey=process.current_process().authkey,
)
if _logger is not None:
d['log_level'] = _logger.getEffectiveLevel()
if not WINEXE:
main_path = getattr(sys.modules['__main__'], '__file__', None)
if not main_path and sys.argv[0] not in ('', '-c'):
main_path = sys.argv[0]
if main_path is not None:
if (not os.path.isabs(main_path) and process.ORIGINAL_DIR
is not None):
main_path = os.path.join(process.ORIGINAL_DIR, main_path)
if not main_path.endswith('.exe'):
d['main_path'] = os.path.normpath(main_path)
return d | python | def get_preparation_data(name):
'''
Return info about parent needed by child to unpickle process object.
Monkey-patch from
'''
d = dict(
name=name,
sys_path=sys.path,
sys_argv=sys.argv,
log_to_stderr=_log_to_stderr,
orig_dir=process.ORIGINAL_DIR,
authkey=process.current_process().authkey,
)
if _logger is not None:
d['log_level'] = _logger.getEffectiveLevel()
if not WINEXE:
main_path = getattr(sys.modules['__main__'], '__file__', None)
if not main_path and sys.argv[0] not in ('', '-c'):
main_path = sys.argv[0]
if main_path is not None:
if (not os.path.isabs(main_path) and process.ORIGINAL_DIR
is not None):
main_path = os.path.join(process.ORIGINAL_DIR, main_path)
if not main_path.endswith('.exe'):
d['main_path'] = os.path.normpath(main_path)
return d | [
"def",
"get_preparation_data",
"(",
"name",
")",
":",
"d",
"=",
"dict",
"(",
"name",
"=",
"name",
",",
"sys_path",
"=",
"sys",
".",
"path",
",",
"sys_argv",
"=",
"sys",
".",
"argv",
",",
"log_to_stderr",
"=",
"_log_to_stderr",
",",
"orig_dir",
"=",
"process",
".",
"ORIGINAL_DIR",
",",
"authkey",
"=",
"process",
".",
"current_process",
"(",
")",
".",
"authkey",
",",
")",
"if",
"_logger",
"is",
"not",
"None",
":",
"d",
"[",
"'log_level'",
"]",
"=",
"_logger",
".",
"getEffectiveLevel",
"(",
")",
"if",
"not",
"WINEXE",
":",
"main_path",
"=",
"getattr",
"(",
"sys",
".",
"modules",
"[",
"'__main__'",
"]",
",",
"'__file__'",
",",
"None",
")",
"if",
"not",
"main_path",
"and",
"sys",
".",
"argv",
"[",
"0",
"]",
"not",
"in",
"(",
"''",
",",
"'-c'",
")",
":",
"main_path",
"=",
"sys",
".",
"argv",
"[",
"0",
"]",
"if",
"main_path",
"is",
"not",
"None",
":",
"if",
"(",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"main_path",
")",
"and",
"process",
".",
"ORIGINAL_DIR",
"is",
"not",
"None",
")",
":",
"main_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"process",
".",
"ORIGINAL_DIR",
",",
"main_path",
")",
"if",
"not",
"main_path",
".",
"endswith",
"(",
"'.exe'",
")",
":",
"d",
"[",
"'main_path'",
"]",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"main_path",
")",
"return",
"d"
] | Return info about parent needed by child to unpickle process object.
Monkey-patch from | [
"Return",
"info",
"about",
"parent",
"needed",
"by",
"child",
"to",
"unpickle",
"process",
"object",
".",
"Monkey",
"-",
"patch",
"from"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/system/winprocess.py#L9-L37 |
231,364 | quantmind/pulsar | examples/snippets/remote.py | remote_call | def remote_call(request, cls, method, args, kw):
'''Command for executing remote calls on a remote object
'''
actor = request.actor
name = 'remote_%s' % cls.__name__
if not hasattr(actor, name):
object = cls(actor)
setattr(actor, name, object)
else:
object = getattr(actor, name)
method_name = '%s%s' % (PREFIX, method)
return getattr(object, method_name)(request, *args, **kw) | python | def remote_call(request, cls, method, args, kw):
'''Command for executing remote calls on a remote object
'''
actor = request.actor
name = 'remote_%s' % cls.__name__
if not hasattr(actor, name):
object = cls(actor)
setattr(actor, name, object)
else:
object = getattr(actor, name)
method_name = '%s%s' % (PREFIX, method)
return getattr(object, method_name)(request, *args, **kw) | [
"def",
"remote_call",
"(",
"request",
",",
"cls",
",",
"method",
",",
"args",
",",
"kw",
")",
":",
"actor",
"=",
"request",
".",
"actor",
"name",
"=",
"'remote_%s'",
"%",
"cls",
".",
"__name__",
"if",
"not",
"hasattr",
"(",
"actor",
",",
"name",
")",
":",
"object",
"=",
"cls",
"(",
"actor",
")",
"setattr",
"(",
"actor",
",",
"name",
",",
"object",
")",
"else",
":",
"object",
"=",
"getattr",
"(",
"actor",
",",
"name",
")",
"method_name",
"=",
"'%s%s'",
"%",
"(",
"PREFIX",
",",
"method",
")",
"return",
"getattr",
"(",
"object",
",",
"method_name",
")",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")"
] | Command for executing remote calls on a remote object | [
"Command",
"for",
"executing",
"remote",
"calls",
"on",
"a",
"remote",
"object"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/snippets/remote.py#L8-L19 |
231,365 | quantmind/pulsar | pulsar/utils/structures/skiplist.py | Skiplist.clear | def clear(self):
'''Clear the container from all data.'''
self._size = 0
self._level = 1
self._head = Node('HEAD', None,
[None]*SKIPLIST_MAXLEVEL,
[1]*SKIPLIST_MAXLEVEL) | python | def clear(self):
'''Clear the container from all data.'''
self._size = 0
self._level = 1
self._head = Node('HEAD', None,
[None]*SKIPLIST_MAXLEVEL,
[1]*SKIPLIST_MAXLEVEL) | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"_size",
"=",
"0",
"self",
".",
"_level",
"=",
"1",
"self",
".",
"_head",
"=",
"Node",
"(",
"'HEAD'",
",",
"None",
",",
"[",
"None",
"]",
"*",
"SKIPLIST_MAXLEVEL",
",",
"[",
"1",
"]",
"*",
"SKIPLIST_MAXLEVEL",
")"
] | Clear the container from all data. | [
"Clear",
"the",
"container",
"from",
"all",
"data",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/structures/skiplist.py#L55-L61 |
231,366 | quantmind/pulsar | pulsar/utils/structures/skiplist.py | Skiplist.extend | def extend(self, iterable):
'''Extend this skiplist with an iterable over
``score``, ``value`` pairs.
'''
i = self.insert
for score_values in iterable:
i(*score_values) | python | def extend(self, iterable):
'''Extend this skiplist with an iterable over
``score``, ``value`` pairs.
'''
i = self.insert
for score_values in iterable:
i(*score_values) | [
"def",
"extend",
"(",
"self",
",",
"iterable",
")",
":",
"i",
"=",
"self",
".",
"insert",
"for",
"score_values",
"in",
"iterable",
":",
"i",
"(",
"*",
"score_values",
")"
] | Extend this skiplist with an iterable over
``score``, ``value`` pairs. | [
"Extend",
"this",
"skiplist",
"with",
"an",
"iterable",
"over",
"score",
"value",
"pairs",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/structures/skiplist.py#L63-L69 |
231,367 | quantmind/pulsar | pulsar/utils/structures/skiplist.py | Skiplist.remove_range | def remove_range(self, start, end, callback=None):
'''Remove a range by rank.
This is equivalent to perform::
del l[start:end]
on a python list.
It returns the number of element removed.
'''
N = len(self)
if start < 0:
start = max(N + start, 0)
if start >= N:
return 0
if end is None:
end = N
elif end < 0:
end = max(N + end, 0)
else:
end = min(end, N)
if start >= end:
return 0
node = self._head
index = 0
chain = [None] * self._level
for i in range(self._level-1, -1, -1):
while node.next[i] and (index + node.width[i]) <= start:
index += node.width[i]
node = node.next[i]
chain[i] = node
node = node.next[0]
initial = self._size
while node and index < end:
next = node.next[0]
self._remove_node(node, chain)
index += 1
if callback:
callback(node.score, node.value)
node = next
return initial - self._size | python | def remove_range(self, start, end, callback=None):
'''Remove a range by rank.
This is equivalent to perform::
del l[start:end]
on a python list.
It returns the number of element removed.
'''
N = len(self)
if start < 0:
start = max(N + start, 0)
if start >= N:
return 0
if end is None:
end = N
elif end < 0:
end = max(N + end, 0)
else:
end = min(end, N)
if start >= end:
return 0
node = self._head
index = 0
chain = [None] * self._level
for i in range(self._level-1, -1, -1):
while node.next[i] and (index + node.width[i]) <= start:
index += node.width[i]
node = node.next[i]
chain[i] = node
node = node.next[0]
initial = self._size
while node and index < end:
next = node.next[0]
self._remove_node(node, chain)
index += 1
if callback:
callback(node.score, node.value)
node = next
return initial - self._size | [
"def",
"remove_range",
"(",
"self",
",",
"start",
",",
"end",
",",
"callback",
"=",
"None",
")",
":",
"N",
"=",
"len",
"(",
"self",
")",
"if",
"start",
"<",
"0",
":",
"start",
"=",
"max",
"(",
"N",
"+",
"start",
",",
"0",
")",
"if",
"start",
">=",
"N",
":",
"return",
"0",
"if",
"end",
"is",
"None",
":",
"end",
"=",
"N",
"elif",
"end",
"<",
"0",
":",
"end",
"=",
"max",
"(",
"N",
"+",
"end",
",",
"0",
")",
"else",
":",
"end",
"=",
"min",
"(",
"end",
",",
"N",
")",
"if",
"start",
">=",
"end",
":",
"return",
"0",
"node",
"=",
"self",
".",
"_head",
"index",
"=",
"0",
"chain",
"=",
"[",
"None",
"]",
"*",
"self",
".",
"_level",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"_level",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"while",
"node",
".",
"next",
"[",
"i",
"]",
"and",
"(",
"index",
"+",
"node",
".",
"width",
"[",
"i",
"]",
")",
"<=",
"start",
":",
"index",
"+=",
"node",
".",
"width",
"[",
"i",
"]",
"node",
"=",
"node",
".",
"next",
"[",
"i",
"]",
"chain",
"[",
"i",
"]",
"=",
"node",
"node",
"=",
"node",
".",
"next",
"[",
"0",
"]",
"initial",
"=",
"self",
".",
"_size",
"while",
"node",
"and",
"index",
"<",
"end",
":",
"next",
"=",
"node",
".",
"next",
"[",
"0",
"]",
"self",
".",
"_remove_node",
"(",
"node",
",",
"chain",
")",
"index",
"+=",
"1",
"if",
"callback",
":",
"callback",
"(",
"node",
".",
"score",
",",
"node",
".",
"value",
")",
"node",
"=",
"next",
"return",
"initial",
"-",
"self",
".",
"_size"
] | Remove a range by rank.
This is equivalent to perform::
del l[start:end]
on a python list.
It returns the number of element removed. | [
"Remove",
"a",
"range",
"by",
"rank",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/structures/skiplist.py#L184-L224 |
231,368 | quantmind/pulsar | pulsar/utils/structures/skiplist.py | Skiplist.remove_range_by_score | def remove_range_by_score(self, minval, maxval, include_min=True,
include_max=True, callback=None):
'''Remove a range with scores between ``minval`` and ``maxval``.
:param minval: the start value of the range to remove
:param maxval: the end value of the range to remove
:param include_min: whether or not to include ``minval`` in the
values to remove
:param include_max: whether or not to include ``maxval`` in the
scores to to remove
:param callback: optional callback function invoked for each
score, value pair removed.
:return: the number of elements removed.
'''
node = self._head
chain = [None] * self._level
if include_min:
for i in range(self._level-1, -1, -1):
while node.next[i] and node.next[i].score < minval:
node = node.next[i]
chain[i] = node
else:
for i in range(self._level-1, -1, -1):
while node.next[i] and node.next[i].score <= minval:
node = node.next[i]
chain[i] = node
node = node.next[0]
initial = self._size
while node and node.score >= minval:
if ((include_max and node.score > maxval) or
(not include_max and node.score >= maxval)):
break
next = node.next[0]
self._remove_node(node, chain)
if callback:
callback(node.score, node.value)
node = next
return initial - self._size | python | def remove_range_by_score(self, minval, maxval, include_min=True,
include_max=True, callback=None):
'''Remove a range with scores between ``minval`` and ``maxval``.
:param minval: the start value of the range to remove
:param maxval: the end value of the range to remove
:param include_min: whether or not to include ``minval`` in the
values to remove
:param include_max: whether or not to include ``maxval`` in the
scores to to remove
:param callback: optional callback function invoked for each
score, value pair removed.
:return: the number of elements removed.
'''
node = self._head
chain = [None] * self._level
if include_min:
for i in range(self._level-1, -1, -1):
while node.next[i] and node.next[i].score < minval:
node = node.next[i]
chain[i] = node
else:
for i in range(self._level-1, -1, -1):
while node.next[i] and node.next[i].score <= minval:
node = node.next[i]
chain[i] = node
node = node.next[0]
initial = self._size
while node and node.score >= minval:
if ((include_max and node.score > maxval) or
(not include_max and node.score >= maxval)):
break
next = node.next[0]
self._remove_node(node, chain)
if callback:
callback(node.score, node.value)
node = next
return initial - self._size | [
"def",
"remove_range_by_score",
"(",
"self",
",",
"minval",
",",
"maxval",
",",
"include_min",
"=",
"True",
",",
"include_max",
"=",
"True",
",",
"callback",
"=",
"None",
")",
":",
"node",
"=",
"self",
".",
"_head",
"chain",
"=",
"[",
"None",
"]",
"*",
"self",
".",
"_level",
"if",
"include_min",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"_level",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"while",
"node",
".",
"next",
"[",
"i",
"]",
"and",
"node",
".",
"next",
"[",
"i",
"]",
".",
"score",
"<",
"minval",
":",
"node",
"=",
"node",
".",
"next",
"[",
"i",
"]",
"chain",
"[",
"i",
"]",
"=",
"node",
"else",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"_level",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"while",
"node",
".",
"next",
"[",
"i",
"]",
"and",
"node",
".",
"next",
"[",
"i",
"]",
".",
"score",
"<=",
"minval",
":",
"node",
"=",
"node",
".",
"next",
"[",
"i",
"]",
"chain",
"[",
"i",
"]",
"=",
"node",
"node",
"=",
"node",
".",
"next",
"[",
"0",
"]",
"initial",
"=",
"self",
".",
"_size",
"while",
"node",
"and",
"node",
".",
"score",
">=",
"minval",
":",
"if",
"(",
"(",
"include_max",
"and",
"node",
".",
"score",
">",
"maxval",
")",
"or",
"(",
"not",
"include_max",
"and",
"node",
".",
"score",
">=",
"maxval",
")",
")",
":",
"break",
"next",
"=",
"node",
".",
"next",
"[",
"0",
"]",
"self",
".",
"_remove_node",
"(",
"node",
",",
"chain",
")",
"if",
"callback",
":",
"callback",
"(",
"node",
".",
"score",
",",
"node",
".",
"value",
")",
"node",
"=",
"next",
"return",
"initial",
"-",
"self",
".",
"_size"
] | Remove a range with scores between ``minval`` and ``maxval``.
:param minval: the start value of the range to remove
:param maxval: the end value of the range to remove
:param include_min: whether or not to include ``minval`` in the
values to remove
:param include_max: whether or not to include ``maxval`` in the
scores to to remove
:param callback: optional callback function invoked for each
score, value pair removed.
:return: the number of elements removed. | [
"Remove",
"a",
"range",
"with",
"scores",
"between",
"minval",
"and",
"maxval",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/structures/skiplist.py#L226-L263 |
231,369 | quantmind/pulsar | pulsar/utils/structures/skiplist.py | Skiplist.count | def count(self, minval, maxval, include_min=True, include_max=True):
'''Returns the number of elements in the skiplist with a score
between min and max.
'''
rank1 = self.rank(minval)
if rank1 < 0:
rank1 = -rank1 - 1
elif not include_min:
rank1 += 1
rank2 = self.rank(maxval)
if rank2 < 0:
rank2 = -rank2 - 1
elif include_max:
rank2 += 1
return max(rank2 - rank1, 0) | python | def count(self, minval, maxval, include_min=True, include_max=True):
'''Returns the number of elements in the skiplist with a score
between min and max.
'''
rank1 = self.rank(minval)
if rank1 < 0:
rank1 = -rank1 - 1
elif not include_min:
rank1 += 1
rank2 = self.rank(maxval)
if rank2 < 0:
rank2 = -rank2 - 1
elif include_max:
rank2 += 1
return max(rank2 - rank1, 0) | [
"def",
"count",
"(",
"self",
",",
"minval",
",",
"maxval",
",",
"include_min",
"=",
"True",
",",
"include_max",
"=",
"True",
")",
":",
"rank1",
"=",
"self",
".",
"rank",
"(",
"minval",
")",
"if",
"rank1",
"<",
"0",
":",
"rank1",
"=",
"-",
"rank1",
"-",
"1",
"elif",
"not",
"include_min",
":",
"rank1",
"+=",
"1",
"rank2",
"=",
"self",
".",
"rank",
"(",
"maxval",
")",
"if",
"rank2",
"<",
"0",
":",
"rank2",
"=",
"-",
"rank2",
"-",
"1",
"elif",
"include_max",
":",
"rank2",
"+=",
"1",
"return",
"max",
"(",
"rank2",
"-",
"rank1",
",",
"0",
")"
] | Returns the number of elements in the skiplist with a score
between min and max. | [
"Returns",
"the",
"number",
"of",
"elements",
"in",
"the",
"skiplist",
"with",
"a",
"score",
"between",
"min",
"and",
"max",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/structures/skiplist.py#L265-L279 |
231,370 | quantmind/pulsar | pulsar/apps/wsgi/structures.py | Accept.quality | def quality(self, key):
"""Returns the quality of the key.
.. versionadded:: 0.6
In previous versions you had to use the item-lookup syntax
(eg: ``obj[key]`` instead of ``obj.quality(key)``)
"""
for item, quality in self:
if self._value_matches(key, item):
return quality
return 0 | python | def quality(self, key):
"""Returns the quality of the key.
.. versionadded:: 0.6
In previous versions you had to use the item-lookup syntax
(eg: ``obj[key]`` instead of ``obj.quality(key)``)
"""
for item, quality in self:
if self._value_matches(key, item):
return quality
return 0 | [
"def",
"quality",
"(",
"self",
",",
"key",
")",
":",
"for",
"item",
",",
"quality",
"in",
"self",
":",
"if",
"self",
".",
"_value_matches",
"(",
"key",
",",
"item",
")",
":",
"return",
"quality",
"return",
"0"
] | Returns the quality of the key.
.. versionadded:: 0.6
In previous versions you had to use the item-lookup syntax
(eg: ``obj[key]`` instead of ``obj.quality(key)``) | [
"Returns",
"the",
"quality",
"of",
"the",
"key",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/structures.py#L54-L64 |
231,371 | quantmind/pulsar | pulsar/apps/wsgi/structures.py | Accept.to_header | def to_header(self):
"""Convert the header set into an HTTP header string."""
result = []
for value, quality in self:
if quality != 1:
value = '%s;q=%s' % (value, quality)
result.append(value)
return ','.join(result) | python | def to_header(self):
"""Convert the header set into an HTTP header string."""
result = []
for value, quality in self:
if quality != 1:
value = '%s;q=%s' % (value, quality)
result.append(value)
return ','.join(result) | [
"def",
"to_header",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"for",
"value",
",",
"quality",
"in",
"self",
":",
"if",
"quality",
"!=",
"1",
":",
"value",
"=",
"'%s;q=%s'",
"%",
"(",
"value",
",",
"quality",
")",
"result",
".",
"append",
"(",
"value",
")",
"return",
"','",
".",
"join",
"(",
"result",
")"
] | Convert the header set into an HTTP header string. | [
"Convert",
"the",
"header",
"set",
"into",
"an",
"HTTP",
"header",
"string",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/structures.py#L109-L116 |
231,372 | quantmind/pulsar | pulsar/apps/wsgi/structures.py | Accept.best_match | def best_match(self, matches, default=None):
"""Returns the best match from a list of possible matches based
on the quality of the client. If two items have the same quality,
the one is returned that comes first.
:param matches: a list of matches to check for
:param default: the value that is returned if none match
"""
if matches:
best_quality = -1
result = default
for client_item, quality in self:
for server_item in matches:
if quality <= best_quality:
break
if self._value_matches(server_item, client_item):
best_quality = quality
result = server_item
return result
else:
return self.best | python | def best_match(self, matches, default=None):
"""Returns the best match from a list of possible matches based
on the quality of the client. If two items have the same quality,
the one is returned that comes first.
:param matches: a list of matches to check for
:param default: the value that is returned if none match
"""
if matches:
best_quality = -1
result = default
for client_item, quality in self:
for server_item in matches:
if quality <= best_quality:
break
if self._value_matches(server_item, client_item):
best_quality = quality
result = server_item
return result
else:
return self.best | [
"def",
"best_match",
"(",
"self",
",",
"matches",
",",
"default",
"=",
"None",
")",
":",
"if",
"matches",
":",
"best_quality",
"=",
"-",
"1",
"result",
"=",
"default",
"for",
"client_item",
",",
"quality",
"in",
"self",
":",
"for",
"server_item",
"in",
"matches",
":",
"if",
"quality",
"<=",
"best_quality",
":",
"break",
"if",
"self",
".",
"_value_matches",
"(",
"server_item",
",",
"client_item",
")",
":",
"best_quality",
"=",
"quality",
"result",
"=",
"server_item",
"return",
"result",
"else",
":",
"return",
"self",
".",
"best"
] | Returns the best match from a list of possible matches based
on the quality of the client. If two items have the same quality,
the one is returned that comes first.
:param matches: a list of matches to check for
:param default: the value that is returned if none match | [
"Returns",
"the",
"best",
"match",
"from",
"a",
"list",
"of",
"possible",
"matches",
"based",
"on",
"the",
"quality",
"of",
"the",
"client",
".",
"If",
"two",
"items",
"have",
"the",
"same",
"quality",
"the",
"one",
"is",
"returned",
"that",
"comes",
"first",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/structures.py#L121-L141 |
231,373 | quantmind/pulsar | pulsar/utils/system/__init__.py | convert_bytes | def convert_bytes(b):
'''Convert a number of bytes into a human readable memory usage, bytes,
kilo, mega, giga, tera, peta, exa, zetta, yotta'''
if b is None:
return '#NA'
for s in reversed(memory_symbols):
if b >= memory_size[s]:
value = float(b) / memory_size[s]
return '%.1f%sB' % (value, s)
return "%sB" % b | python | def convert_bytes(b):
'''Convert a number of bytes into a human readable memory usage, bytes,
kilo, mega, giga, tera, peta, exa, zetta, yotta'''
if b is None:
return '#NA'
for s in reversed(memory_symbols):
if b >= memory_size[s]:
value = float(b) / memory_size[s]
return '%.1f%sB' % (value, s)
return "%sB" % b | [
"def",
"convert_bytes",
"(",
"b",
")",
":",
"if",
"b",
"is",
"None",
":",
"return",
"'#NA'",
"for",
"s",
"in",
"reversed",
"(",
"memory_symbols",
")",
":",
"if",
"b",
">=",
"memory_size",
"[",
"s",
"]",
":",
"value",
"=",
"float",
"(",
"b",
")",
"/",
"memory_size",
"[",
"s",
"]",
"return",
"'%.1f%sB'",
"%",
"(",
"value",
",",
"s",
")",
"return",
"\"%sB\"",
"%",
"b"
] | Convert a number of bytes into a human readable memory usage, bytes,
kilo, mega, giga, tera, peta, exa, zetta, yotta | [
"Convert",
"a",
"number",
"of",
"bytes",
"into",
"a",
"human",
"readable",
"memory",
"usage",
"bytes",
"kilo",
"mega",
"giga",
"tera",
"peta",
"exa",
"zetta",
"yotta"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/system/__init__.py#L32-L41 |
231,374 | quantmind/pulsar | pulsar/utils/system/__init__.py | process_info | def process_info(pid=None):
'''Returns a dictionary of system information for the process ``pid``.
It uses the psutil_ module for the purpose. If psutil_ is not available
it returns an empty dictionary.
.. _psutil: http://code.google.com/p/psutil/
'''
if psutil is None: # pragma nocover
return {}
pid = pid or os.getpid()
try:
p = psutil.Process(pid)
# this fails on platforms which don't allow multiprocessing
except psutil.NoSuchProcess: # pragma nocover
return {}
else:
mem = p.memory_info()
return {'memory': convert_bytes(mem.rss),
'memory_virtual': convert_bytes(mem.vms),
'cpu_percent': p.cpu_percent(),
'nice': p.nice(),
'num_threads': p.num_threads()} | python | def process_info(pid=None):
'''Returns a dictionary of system information for the process ``pid``.
It uses the psutil_ module for the purpose. If psutil_ is not available
it returns an empty dictionary.
.. _psutil: http://code.google.com/p/psutil/
'''
if psutil is None: # pragma nocover
return {}
pid = pid or os.getpid()
try:
p = psutil.Process(pid)
# this fails on platforms which don't allow multiprocessing
except psutil.NoSuchProcess: # pragma nocover
return {}
else:
mem = p.memory_info()
return {'memory': convert_bytes(mem.rss),
'memory_virtual': convert_bytes(mem.vms),
'cpu_percent': p.cpu_percent(),
'nice': p.nice(),
'num_threads': p.num_threads()} | [
"def",
"process_info",
"(",
"pid",
"=",
"None",
")",
":",
"if",
"psutil",
"is",
"None",
":",
"# pragma nocover",
"return",
"{",
"}",
"pid",
"=",
"pid",
"or",
"os",
".",
"getpid",
"(",
")",
"try",
":",
"p",
"=",
"psutil",
".",
"Process",
"(",
"pid",
")",
"# this fails on platforms which don't allow multiprocessing",
"except",
"psutil",
".",
"NoSuchProcess",
":",
"# pragma nocover",
"return",
"{",
"}",
"else",
":",
"mem",
"=",
"p",
".",
"memory_info",
"(",
")",
"return",
"{",
"'memory'",
":",
"convert_bytes",
"(",
"mem",
".",
"rss",
")",
",",
"'memory_virtual'",
":",
"convert_bytes",
"(",
"mem",
".",
"vms",
")",
",",
"'cpu_percent'",
":",
"p",
".",
"cpu_percent",
"(",
")",
",",
"'nice'",
":",
"p",
".",
"nice",
"(",
")",
",",
"'num_threads'",
":",
"p",
".",
"num_threads",
"(",
")",
"}"
] | Returns a dictionary of system information for the process ``pid``.
It uses the psutil_ module for the purpose. If psutil_ is not available
it returns an empty dictionary.
.. _psutil: http://code.google.com/p/psutil/ | [
"Returns",
"a",
"dictionary",
"of",
"system",
"information",
"for",
"the",
"process",
"pid",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/system/__init__.py#L44-L66 |
231,375 | quantmind/pulsar | pulsar/async/protocols.py | TcpServer.start_serving | async def start_serving(self, address=None, sockets=None,
backlog=100, sslcontext=None):
"""Start serving.
:param address: optional address to bind to
:param sockets: optional list of sockets to bind to
:param backlog: Number of maximum connections
:param sslcontext: optional SSLContext object
"""
if self._server:
raise RuntimeError('Already serving')
create_server = self._loop.create_server
server = None
if sockets:
for sock in sockets:
srv = await create_server(self.create_protocol,
sock=sock,
backlog=backlog,
ssl=sslcontext)
if server:
server.sockets.extend(srv.sockets)
else:
server = srv
elif isinstance(address, tuple):
server = await create_server(self.create_protocol,
host=address[0],
port=address[1],
backlog=backlog,
ssl=sslcontext)
else:
raise RuntimeError('sockets or address must be supplied')
self._set_server(server) | python | async def start_serving(self, address=None, sockets=None,
backlog=100, sslcontext=None):
"""Start serving.
:param address: optional address to bind to
:param sockets: optional list of sockets to bind to
:param backlog: Number of maximum connections
:param sslcontext: optional SSLContext object
"""
if self._server:
raise RuntimeError('Already serving')
create_server = self._loop.create_server
server = None
if sockets:
for sock in sockets:
srv = await create_server(self.create_protocol,
sock=sock,
backlog=backlog,
ssl=sslcontext)
if server:
server.sockets.extend(srv.sockets)
else:
server = srv
elif isinstance(address, tuple):
server = await create_server(self.create_protocol,
host=address[0],
port=address[1],
backlog=backlog,
ssl=sslcontext)
else:
raise RuntimeError('sockets or address must be supplied')
self._set_server(server) | [
"async",
"def",
"start_serving",
"(",
"self",
",",
"address",
"=",
"None",
",",
"sockets",
"=",
"None",
",",
"backlog",
"=",
"100",
",",
"sslcontext",
"=",
"None",
")",
":",
"if",
"self",
".",
"_server",
":",
"raise",
"RuntimeError",
"(",
"'Already serving'",
")",
"create_server",
"=",
"self",
".",
"_loop",
".",
"create_server",
"server",
"=",
"None",
"if",
"sockets",
":",
"for",
"sock",
"in",
"sockets",
":",
"srv",
"=",
"await",
"create_server",
"(",
"self",
".",
"create_protocol",
",",
"sock",
"=",
"sock",
",",
"backlog",
"=",
"backlog",
",",
"ssl",
"=",
"sslcontext",
")",
"if",
"server",
":",
"server",
".",
"sockets",
".",
"extend",
"(",
"srv",
".",
"sockets",
")",
"else",
":",
"server",
"=",
"srv",
"elif",
"isinstance",
"(",
"address",
",",
"tuple",
")",
":",
"server",
"=",
"await",
"create_server",
"(",
"self",
".",
"create_protocol",
",",
"host",
"=",
"address",
"[",
"0",
"]",
",",
"port",
"=",
"address",
"[",
"1",
"]",
",",
"backlog",
"=",
"backlog",
",",
"ssl",
"=",
"sslcontext",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"'sockets or address must be supplied'",
")",
"self",
".",
"_set_server",
"(",
"server",
")"
] | Start serving.
:param address: optional address to bind to
:param sockets: optional list of sockets to bind to
:param backlog: Number of maximum connections
:param sslcontext: optional SSLContext object | [
"Start",
"serving",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/protocols.py#L212-L243 |
231,376 | quantmind/pulsar | pulsar/async/protocols.py | TcpServer._close_connections | def _close_connections(self, connection=None, timeout=5):
"""Close ``connection`` if specified, otherwise close all connections.
Return a list of :class:`.Future` called back once the connection/s
are closed.
"""
all = []
if connection:
waiter = connection.event('connection_lost').waiter()
if waiter:
all.append(waiter)
connection.close()
else:
connections = list(self._concurrent_connections)
self._concurrent_connections = set()
for connection in connections:
waiter = connection.event('connection_lost').waiter()
if waiter:
all.append(waiter)
connection.close()
if all:
self.logger.info('%s closing %d connections', self, len(all))
return asyncio.wait(all, timeout=timeout, loop=self._loop) | python | def _close_connections(self, connection=None, timeout=5):
"""Close ``connection`` if specified, otherwise close all connections.
Return a list of :class:`.Future` called back once the connection/s
are closed.
"""
all = []
if connection:
waiter = connection.event('connection_lost').waiter()
if waiter:
all.append(waiter)
connection.close()
else:
connections = list(self._concurrent_connections)
self._concurrent_connections = set()
for connection in connections:
waiter = connection.event('connection_lost').waiter()
if waiter:
all.append(waiter)
connection.close()
if all:
self.logger.info('%s closing %d connections', self, len(all))
return asyncio.wait(all, timeout=timeout, loop=self._loop) | [
"def",
"_close_connections",
"(",
"self",
",",
"connection",
"=",
"None",
",",
"timeout",
"=",
"5",
")",
":",
"all",
"=",
"[",
"]",
"if",
"connection",
":",
"waiter",
"=",
"connection",
".",
"event",
"(",
"'connection_lost'",
")",
".",
"waiter",
"(",
")",
"if",
"waiter",
":",
"all",
".",
"append",
"(",
"waiter",
")",
"connection",
".",
"close",
"(",
")",
"else",
":",
"connections",
"=",
"list",
"(",
"self",
".",
"_concurrent_connections",
")",
"self",
".",
"_concurrent_connections",
"=",
"set",
"(",
")",
"for",
"connection",
"in",
"connections",
":",
"waiter",
"=",
"connection",
".",
"event",
"(",
"'connection_lost'",
")",
".",
"waiter",
"(",
")",
"if",
"waiter",
":",
"all",
".",
"append",
"(",
"waiter",
")",
"connection",
".",
"close",
"(",
")",
"if",
"all",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'%s closing %d connections'",
",",
"self",
",",
"len",
"(",
"all",
")",
")",
"return",
"asyncio",
".",
"wait",
"(",
"all",
",",
"timeout",
"=",
"timeout",
",",
"loop",
"=",
"self",
".",
"_loop",
")"
] | Close ``connection`` if specified, otherwise close all connections.
Return a list of :class:`.Future` called back once the connection/s
are closed. | [
"Close",
"connection",
"if",
"specified",
"otherwise",
"close",
"all",
"connections",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/protocols.py#L282-L304 |
231,377 | quantmind/pulsar | pulsar/async/protocols.py | DatagramServer.start_serving | async def start_serving(self, address=None, sockets=None, **kw):
"""create the server endpoint.
"""
if self._server:
raise RuntimeError('Already serving')
server = DGServer(self._loop)
loop = self._loop
if sockets:
for sock in sockets:
transport, _ = await loop.create_datagram_endpoint(
self.create_protocol, sock=sock)
server.transports.append(transport)
elif isinstance(address, tuple):
transport, _ = await loop.create_datagram_endpoint(
self.create_protocol, local_addr=address)
server.transports.append(transport)
else:
raise RuntimeError('sockets or address must be supplied')
self._set_server(server) | python | async def start_serving(self, address=None, sockets=None, **kw):
"""create the server endpoint.
"""
if self._server:
raise RuntimeError('Already serving')
server = DGServer(self._loop)
loop = self._loop
if sockets:
for sock in sockets:
transport, _ = await loop.create_datagram_endpoint(
self.create_protocol, sock=sock)
server.transports.append(transport)
elif isinstance(address, tuple):
transport, _ = await loop.create_datagram_endpoint(
self.create_protocol, local_addr=address)
server.transports.append(transport)
else:
raise RuntimeError('sockets or address must be supplied')
self._set_server(server) | [
"async",
"def",
"start_serving",
"(",
"self",
",",
"address",
"=",
"None",
",",
"sockets",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"if",
"self",
".",
"_server",
":",
"raise",
"RuntimeError",
"(",
"'Already serving'",
")",
"server",
"=",
"DGServer",
"(",
"self",
".",
"_loop",
")",
"loop",
"=",
"self",
".",
"_loop",
"if",
"sockets",
":",
"for",
"sock",
"in",
"sockets",
":",
"transport",
",",
"_",
"=",
"await",
"loop",
".",
"create_datagram_endpoint",
"(",
"self",
".",
"create_protocol",
",",
"sock",
"=",
"sock",
")",
"server",
".",
"transports",
".",
"append",
"(",
"transport",
")",
"elif",
"isinstance",
"(",
"address",
",",
"tuple",
")",
":",
"transport",
",",
"_",
"=",
"await",
"loop",
".",
"create_datagram_endpoint",
"(",
"self",
".",
"create_protocol",
",",
"local_addr",
"=",
"address",
")",
"server",
".",
"transports",
".",
"append",
"(",
"transport",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"'sockets or address must be supplied'",
")",
"self",
".",
"_set_server",
"(",
"server",
")"
] | create the server endpoint. | [
"create",
"the",
"server",
"endpoint",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/protocols.py#L333-L351 |
231,378 | quantmind/pulsar | pulsar/apps/socket/__init__.py | SocketServer.monitor_start | async def monitor_start(self, monitor):
'''Create the socket listening to the ``bind`` address.
If the platform does not support multiprocessing sockets set the
number of workers to 0.
'''
cfg = self.cfg
if (not platform.has_multiprocessing_socket or
cfg.concurrency == 'thread'):
cfg.set('workers', 0)
servers = await self.binds(monitor)
if not servers:
raise ImproperlyConfigured('Could not open a socket. '
'No address to bind to')
addresses = []
for server in servers.values():
addresses.extend(server.addresses)
self.cfg.addresses = addresses | python | async def monitor_start(self, monitor):
'''Create the socket listening to the ``bind`` address.
If the platform does not support multiprocessing sockets set the
number of workers to 0.
'''
cfg = self.cfg
if (not platform.has_multiprocessing_socket or
cfg.concurrency == 'thread'):
cfg.set('workers', 0)
servers = await self.binds(monitor)
if not servers:
raise ImproperlyConfigured('Could not open a socket. '
'No address to bind to')
addresses = []
for server in servers.values():
addresses.extend(server.addresses)
self.cfg.addresses = addresses | [
"async",
"def",
"monitor_start",
"(",
"self",
",",
"monitor",
")",
":",
"cfg",
"=",
"self",
".",
"cfg",
"if",
"(",
"not",
"platform",
".",
"has_multiprocessing_socket",
"or",
"cfg",
".",
"concurrency",
"==",
"'thread'",
")",
":",
"cfg",
".",
"set",
"(",
"'workers'",
",",
"0",
")",
"servers",
"=",
"await",
"self",
".",
"binds",
"(",
"monitor",
")",
"if",
"not",
"servers",
":",
"raise",
"ImproperlyConfigured",
"(",
"'Could not open a socket. '",
"'No address to bind to'",
")",
"addresses",
"=",
"[",
"]",
"for",
"server",
"in",
"servers",
".",
"values",
"(",
")",
":",
"addresses",
".",
"extend",
"(",
"server",
".",
"addresses",
")",
"self",
".",
"cfg",
".",
"addresses",
"=",
"addresses"
] | Create the socket listening to the ``bind`` address.
If the platform does not support multiprocessing sockets set the
number of workers to 0. | [
"Create",
"the",
"socket",
"listening",
"to",
"the",
"bind",
"address",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/socket/__init__.py#L256-L273 |
231,379 | quantmind/pulsar | pulsar/apps/socket/__init__.py | SocketServer.create_server | async def create_server(self, worker, protocol_factory, address=None,
sockets=None, idx=0):
'''Create the Server which will listen for requests.
:return: a :class:`.TcpServer`.
'''
cfg = self.cfg
max_requests = cfg.max_requests
if max_requests:
max_requests = int(lognormvariate(log(max_requests), 0.2))
server = self.server_factory(
protocol_factory,
loop=worker._loop,
max_requests=max_requests,
keep_alive=cfg.keep_alive,
name=self.name,
logger=self.logger,
server_software=cfg.server_software,
cfg=cfg,
idx=idx
)
for event in ('connection_made', 'pre_request', 'post_request',
'connection_lost'):
callback = getattr(cfg, event)
if callback != pass_through:
server.event(event).bind(callback)
await server.start_serving(
sockets=sockets,
address=address,
backlog=cfg.backlog,
sslcontext=self.sslcontext()
)
return server | python | async def create_server(self, worker, protocol_factory, address=None,
sockets=None, idx=0):
'''Create the Server which will listen for requests.
:return: a :class:`.TcpServer`.
'''
cfg = self.cfg
max_requests = cfg.max_requests
if max_requests:
max_requests = int(lognormvariate(log(max_requests), 0.2))
server = self.server_factory(
protocol_factory,
loop=worker._loop,
max_requests=max_requests,
keep_alive=cfg.keep_alive,
name=self.name,
logger=self.logger,
server_software=cfg.server_software,
cfg=cfg,
idx=idx
)
for event in ('connection_made', 'pre_request', 'post_request',
'connection_lost'):
callback = getattr(cfg, event)
if callback != pass_through:
server.event(event).bind(callback)
await server.start_serving(
sockets=sockets,
address=address,
backlog=cfg.backlog,
sslcontext=self.sslcontext()
)
return server | [
"async",
"def",
"create_server",
"(",
"self",
",",
"worker",
",",
"protocol_factory",
",",
"address",
"=",
"None",
",",
"sockets",
"=",
"None",
",",
"idx",
"=",
"0",
")",
":",
"cfg",
"=",
"self",
".",
"cfg",
"max_requests",
"=",
"cfg",
".",
"max_requests",
"if",
"max_requests",
":",
"max_requests",
"=",
"int",
"(",
"lognormvariate",
"(",
"log",
"(",
"max_requests",
")",
",",
"0.2",
")",
")",
"server",
"=",
"self",
".",
"server_factory",
"(",
"protocol_factory",
",",
"loop",
"=",
"worker",
".",
"_loop",
",",
"max_requests",
"=",
"max_requests",
",",
"keep_alive",
"=",
"cfg",
".",
"keep_alive",
",",
"name",
"=",
"self",
".",
"name",
",",
"logger",
"=",
"self",
".",
"logger",
",",
"server_software",
"=",
"cfg",
".",
"server_software",
",",
"cfg",
"=",
"cfg",
",",
"idx",
"=",
"idx",
")",
"for",
"event",
"in",
"(",
"'connection_made'",
",",
"'pre_request'",
",",
"'post_request'",
",",
"'connection_lost'",
")",
":",
"callback",
"=",
"getattr",
"(",
"cfg",
",",
"event",
")",
"if",
"callback",
"!=",
"pass_through",
":",
"server",
".",
"event",
"(",
"event",
")",
".",
"bind",
"(",
"callback",
")",
"await",
"server",
".",
"start_serving",
"(",
"sockets",
"=",
"sockets",
",",
"address",
"=",
"address",
",",
"backlog",
"=",
"cfg",
".",
"backlog",
",",
"sslcontext",
"=",
"self",
".",
"sslcontext",
"(",
")",
")",
"return",
"server"
] | Create the Server which will listen for requests.
:return: a :class:`.TcpServer`. | [
"Create",
"the",
"Server",
"which",
"will",
"listen",
"for",
"requests",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/socket/__init__.py#L306-L338 |
231,380 | quantmind/pulsar | pulsar/apps/data/redis/pubsub.py | RedisPubSub.channels | def channels(self, pattern=None):
'''Lists the currently active channels matching ``pattern``
'''
if pattern:
return self.store.execute('PUBSUB', 'CHANNELS', pattern)
else:
return self.store.execute('PUBSUB', 'CHANNELS') | python | def channels(self, pattern=None):
'''Lists the currently active channels matching ``pattern``
'''
if pattern:
return self.store.execute('PUBSUB', 'CHANNELS', pattern)
else:
return self.store.execute('PUBSUB', 'CHANNELS') | [
"def",
"channels",
"(",
"self",
",",
"pattern",
"=",
"None",
")",
":",
"if",
"pattern",
":",
"return",
"self",
".",
"store",
".",
"execute",
"(",
"'PUBSUB'",
",",
"'CHANNELS'",
",",
"pattern",
")",
"else",
":",
"return",
"self",
".",
"store",
".",
"execute",
"(",
"'PUBSUB'",
",",
"'CHANNELS'",
")"
] | Lists the currently active channels matching ``pattern`` | [
"Lists",
"the",
"currently",
"active",
"channels",
"matching",
"pattern"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/data/redis/pubsub.py#L45-L51 |
231,381 | quantmind/pulsar | pulsar/apps/data/redis/pubsub.py | RedisChannels.lock | def lock(self, name, **kwargs):
"""Global distributed lock
"""
return self.pubsub.store.client().lock(self.prefixed(name), **kwargs) | python | def lock(self, name, **kwargs):
"""Global distributed lock
"""
return self.pubsub.store.client().lock(self.prefixed(name), **kwargs) | [
"def",
"lock",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"pubsub",
".",
"store",
".",
"client",
"(",
")",
".",
"lock",
"(",
"self",
".",
"prefixed",
"(",
"name",
")",
",",
"*",
"*",
"kwargs",
")"
] | Global distributed lock | [
"Global",
"distributed",
"lock"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/data/redis/pubsub.py#L104-L107 |
231,382 | quantmind/pulsar | pulsar/apps/data/redis/pubsub.py | RedisChannels.publish | async def publish(self, channel, event, data=None):
"""Publish a new ``event`` on a ``channel``
:param channel: channel name
:param event: event name
:param data: optional payload to include in the event
:return: a coroutine and therefore it must be awaited
"""
msg = {'event': event, 'channel': channel}
if data:
msg['data'] = data
try:
await self.pubsub.publish(self.prefixed(channel), msg)
except ConnectionRefusedError:
self.connection_error = True
self.logger.critical(
'%s cannot publish on "%s" channel - connection error',
self,
channel
)
else:
self.connection_ok() | python | async def publish(self, channel, event, data=None):
"""Publish a new ``event`` on a ``channel``
:param channel: channel name
:param event: event name
:param data: optional payload to include in the event
:return: a coroutine and therefore it must be awaited
"""
msg = {'event': event, 'channel': channel}
if data:
msg['data'] = data
try:
await self.pubsub.publish(self.prefixed(channel), msg)
except ConnectionRefusedError:
self.connection_error = True
self.logger.critical(
'%s cannot publish on "%s" channel - connection error',
self,
channel
)
else:
self.connection_ok() | [
"async",
"def",
"publish",
"(",
"self",
",",
"channel",
",",
"event",
",",
"data",
"=",
"None",
")",
":",
"msg",
"=",
"{",
"'event'",
":",
"event",
",",
"'channel'",
":",
"channel",
"}",
"if",
"data",
":",
"msg",
"[",
"'data'",
"]",
"=",
"data",
"try",
":",
"await",
"self",
".",
"pubsub",
".",
"publish",
"(",
"self",
".",
"prefixed",
"(",
"channel",
")",
",",
"msg",
")",
"except",
"ConnectionRefusedError",
":",
"self",
".",
"connection_error",
"=",
"True",
"self",
".",
"logger",
".",
"critical",
"(",
"'%s cannot publish on \"%s\" channel - connection error'",
",",
"self",
",",
"channel",
")",
"else",
":",
"self",
".",
"connection_ok",
"(",
")"
] | Publish a new ``event`` on a ``channel``
:param channel: channel name
:param event: event name
:param data: optional payload to include in the event
:return: a coroutine and therefore it must be awaited | [
"Publish",
"a",
"new",
"event",
"on",
"a",
"channel"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/data/redis/pubsub.py#L109-L130 |
231,383 | quantmind/pulsar | pulsar/apps/data/redis/pubsub.py | RedisChannels.close | async def close(self):
"""Close channels and underlying pubsub handler
:return: a coroutine and therefore it must be awaited
"""
push_connection = self.pubsub.push_connection
self.status = self.statusType.closed
if push_connection:
push_connection.event('connection_lost').unbind(
self._connection_lost
)
await self.pubsub.close() | python | async def close(self):
"""Close channels and underlying pubsub handler
:return: a coroutine and therefore it must be awaited
"""
push_connection = self.pubsub.push_connection
self.status = self.statusType.closed
if push_connection:
push_connection.event('connection_lost').unbind(
self._connection_lost
)
await self.pubsub.close() | [
"async",
"def",
"close",
"(",
"self",
")",
":",
"push_connection",
"=",
"self",
".",
"pubsub",
".",
"push_connection",
"self",
".",
"status",
"=",
"self",
".",
"statusType",
".",
"closed",
"if",
"push_connection",
":",
"push_connection",
".",
"event",
"(",
"'connection_lost'",
")",
".",
"unbind",
"(",
"self",
".",
"_connection_lost",
")",
"await",
"self",
".",
"pubsub",
".",
"close",
"(",
")"
] | Close channels and underlying pubsub handler
:return: a coroutine and therefore it must be awaited | [
"Close",
"channels",
"and",
"underlying",
"pubsub",
"handler"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/data/redis/pubsub.py#L140-L151 |
231,384 | quantmind/pulsar | pulsar/apps/http/client.py | RequestBase.origin_req_host | def origin_req_host(self):
"""Required by Cookies handlers
"""
if self.history:
return self.history[0].request.origin_req_host
else:
return scheme_host_port(self.url)[1] | python | def origin_req_host(self):
"""Required by Cookies handlers
"""
if self.history:
return self.history[0].request.origin_req_host
else:
return scheme_host_port(self.url)[1] | [
"def",
"origin_req_host",
"(",
"self",
")",
":",
"if",
"self",
".",
"history",
":",
"return",
"self",
".",
"history",
"[",
"0",
"]",
".",
"request",
".",
"origin_req_host",
"else",
":",
"return",
"scheme_host_port",
"(",
"self",
".",
"url",
")",
"[",
"1",
"]"
] | Required by Cookies handlers | [
"Required",
"by",
"Cookies",
"handlers"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L119-L125 |
231,385 | quantmind/pulsar | pulsar/apps/http/client.py | HttpRequest.get_header | def get_header(self, header_name, default=None):
"""Retrieve ``header_name`` from this request headers.
"""
return self.headers.get(
header_name, self.unredirected_headers.get(header_name, default)) | python | def get_header(self, header_name, default=None):
"""Retrieve ``header_name`` from this request headers.
"""
return self.headers.get(
header_name, self.unredirected_headers.get(header_name, default)) | [
"def",
"get_header",
"(",
"self",
",",
"header_name",
",",
"default",
"=",
"None",
")",
":",
"return",
"self",
".",
"headers",
".",
"get",
"(",
"header_name",
",",
"self",
".",
"unredirected_headers",
".",
"get",
"(",
"header_name",
",",
"default",
")",
")"
] | Retrieve ``header_name`` from this request headers. | [
"Retrieve",
"header_name",
"from",
"this",
"request",
"headers",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L325-L329 |
231,386 | quantmind/pulsar | pulsar/apps/http/client.py | HttpRequest.remove_header | def remove_header(self, header_name):
"""Remove ``header_name`` from this request.
"""
val1 = self.headers.pop(header_name, None)
val2 = self.unredirected_headers.pop(header_name, None)
return val1 or val2 | python | def remove_header(self, header_name):
"""Remove ``header_name`` from this request.
"""
val1 = self.headers.pop(header_name, None)
val2 = self.unredirected_headers.pop(header_name, None)
return val1 or val2 | [
"def",
"remove_header",
"(",
"self",
",",
"header_name",
")",
":",
"val1",
"=",
"self",
".",
"headers",
".",
"pop",
"(",
"header_name",
",",
"None",
")",
"val2",
"=",
"self",
".",
"unredirected_headers",
".",
"pop",
"(",
"header_name",
",",
"None",
")",
"return",
"val1",
"or",
"val2"
] | Remove ``header_name`` from this request. | [
"Remove",
"header_name",
"from",
"this",
"request",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L331-L336 |
231,387 | quantmind/pulsar | pulsar/apps/http/client.py | HttpResponse.raw | def raw(self):
"""A raw asynchronous Http response
"""
if self._raw is None:
self._raw = HttpStream(self)
return self._raw | python | def raw(self):
"""A raw asynchronous Http response
"""
if self._raw is None:
self._raw = HttpStream(self)
return self._raw | [
"def",
"raw",
"(",
"self",
")",
":",
"if",
"self",
".",
"_raw",
"is",
"None",
":",
"self",
".",
"_raw",
"=",
"HttpStream",
"(",
"self",
")",
"return",
"self",
".",
"_raw"
] | A raw asynchronous Http response | [
"A",
"raw",
"asynchronous",
"Http",
"response"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L539-L544 |
231,388 | quantmind/pulsar | pulsar/apps/http/client.py | HttpResponse.links | def links(self):
"""Returns the parsed header links of the response, if any
"""
headers = self.headers or {}
header = headers.get('link')
li = {}
if header:
links = parse_header_links(header)
for link in links:
key = link.get('rel') or link.get('url')
li[key] = link
return li | python | def links(self):
"""Returns the parsed header links of the response, if any
"""
headers = self.headers or {}
header = headers.get('link')
li = {}
if header:
links = parse_header_links(header)
for link in links:
key = link.get('rel') or link.get('url')
li[key] = link
return li | [
"def",
"links",
"(",
"self",
")",
":",
"headers",
"=",
"self",
".",
"headers",
"or",
"{",
"}",
"header",
"=",
"headers",
".",
"get",
"(",
"'link'",
")",
"li",
"=",
"{",
"}",
"if",
"header",
":",
"links",
"=",
"parse_header_links",
"(",
"header",
")",
"for",
"link",
"in",
"links",
":",
"key",
"=",
"link",
".",
"get",
"(",
"'rel'",
")",
"or",
"link",
".",
"get",
"(",
"'url'",
")",
"li",
"[",
"key",
"]",
"=",
"link",
"return",
"li"
] | Returns the parsed header links of the response, if any | [
"Returns",
"the",
"parsed",
"header",
"links",
"of",
"the",
"response",
"if",
"any"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L547-L558 |
231,389 | quantmind/pulsar | pulsar/apps/http/client.py | HttpResponse.text | def text(self):
"""Decode content as a string.
"""
data = self.content
return data.decode(self.encoding or 'utf-8') if data else '' | python | def text(self):
"""Decode content as a string.
"""
data = self.content
return data.decode(self.encoding or 'utf-8') if data else '' | [
"def",
"text",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"content",
"return",
"data",
".",
"decode",
"(",
"self",
".",
"encoding",
"or",
"'utf-8'",
")",
"if",
"data",
"else",
"''"
] | Decode content as a string. | [
"Decode",
"content",
"as",
"a",
"string",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L565-L569 |
231,390 | quantmind/pulsar | pulsar/apps/http/client.py | HttpResponse.decode_content | def decode_content(self):
"""Return the best possible representation of the response body.
"""
ct = self.headers.get('content-type')
if ct:
ct, options = parse_options_header(ct)
charset = options.get('charset')
if ct in JSON_CONTENT_TYPES:
return self.json()
elif ct.startswith('text/'):
return self.text
elif ct == FORM_URL_ENCODED:
return parse_qsl(self.content.decode(charset),
keep_blank_values=True)
return self.content | python | def decode_content(self):
"""Return the best possible representation of the response body.
"""
ct = self.headers.get('content-type')
if ct:
ct, options = parse_options_header(ct)
charset = options.get('charset')
if ct in JSON_CONTENT_TYPES:
return self.json()
elif ct.startswith('text/'):
return self.text
elif ct == FORM_URL_ENCODED:
return parse_qsl(self.content.decode(charset),
keep_blank_values=True)
return self.content | [
"def",
"decode_content",
"(",
"self",
")",
":",
"ct",
"=",
"self",
".",
"headers",
".",
"get",
"(",
"'content-type'",
")",
"if",
"ct",
":",
"ct",
",",
"options",
"=",
"parse_options_header",
"(",
"ct",
")",
"charset",
"=",
"options",
".",
"get",
"(",
"'charset'",
")",
"if",
"ct",
"in",
"JSON_CONTENT_TYPES",
":",
"return",
"self",
".",
"json",
"(",
")",
"elif",
"ct",
".",
"startswith",
"(",
"'text/'",
")",
":",
"return",
"self",
".",
"text",
"elif",
"ct",
"==",
"FORM_URL_ENCODED",
":",
"return",
"parse_qsl",
"(",
"self",
".",
"content",
".",
"decode",
"(",
"charset",
")",
",",
"keep_blank_values",
"=",
"True",
")",
"return",
"self",
".",
"content"
] | Return the best possible representation of the response body. | [
"Return",
"the",
"best",
"possible",
"representation",
"of",
"the",
"response",
"body",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L576-L590 |
231,391 | quantmind/pulsar | pulsar/apps/http/client.py | HttpClient.request | def request(self, method, url, **params):
"""Constructs and sends a request to a remote server.
It returns a :class:`.Future` which results in a
:class:`.HttpResponse` object.
:param method: request method for the :class:`HttpRequest`.
:param url: URL for the :class:`HttpRequest`.
:param params: optional parameters for the :class:`HttpRequest`
initialisation.
:rtype: a coroutine
"""
response = self._request(method, url, **params)
if not self._loop.is_running():
return self._loop.run_until_complete(response)
else:
return response | python | def request(self, method, url, **params):
"""Constructs and sends a request to a remote server.
It returns a :class:`.Future` which results in a
:class:`.HttpResponse` object.
:param method: request method for the :class:`HttpRequest`.
:param url: URL for the :class:`HttpRequest`.
:param params: optional parameters for the :class:`HttpRequest`
initialisation.
:rtype: a coroutine
"""
response = self._request(method, url, **params)
if not self._loop.is_running():
return self._loop.run_until_complete(response)
else:
return response | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"url",
",",
"*",
"*",
"params",
")",
":",
"response",
"=",
"self",
".",
"_request",
"(",
"method",
",",
"url",
",",
"*",
"*",
"params",
")",
"if",
"not",
"self",
".",
"_loop",
".",
"is_running",
"(",
")",
":",
"return",
"self",
".",
"_loop",
".",
"run_until_complete",
"(",
"response",
")",
"else",
":",
"return",
"response"
] | Constructs and sends a request to a remote server.
It returns a :class:`.Future` which results in a
:class:`.HttpResponse` object.
:param method: request method for the :class:`HttpRequest`.
:param url: URL for the :class:`HttpRequest`.
:param params: optional parameters for the :class:`HttpRequest`
initialisation.
:rtype: a coroutine | [
"Constructs",
"and",
"sends",
"a",
"request",
"to",
"a",
"remote",
"server",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L864-L881 |
231,392 | quantmind/pulsar | pulsar/apps/http/client.py | HttpClient.ssl_context | def ssl_context(self, verify=True, cert_reqs=None,
check_hostname=False, certfile=None, keyfile=None,
cafile=None, capath=None, cadata=None, **kw):
"""Create a SSL context object.
This method should not be called by from user code
"""
assert ssl, 'SSL not supported'
cafile = cafile or DEFAULT_CA_BUNDLE_PATH
if verify is True:
cert_reqs = ssl.CERT_REQUIRED
check_hostname = True
if isinstance(verify, str):
cert_reqs = ssl.CERT_REQUIRED
if os.path.isfile(verify):
cafile = verify
elif os.path.isdir(verify):
capath = verify
return ssl._create_unverified_context(cert_reqs=cert_reqs,
check_hostname=check_hostname,
certfile=certfile,
keyfile=keyfile,
cafile=cafile,
capath=capath,
cadata=cadata) | python | def ssl_context(self, verify=True, cert_reqs=None,
check_hostname=False, certfile=None, keyfile=None,
cafile=None, capath=None, cadata=None, **kw):
"""Create a SSL context object.
This method should not be called by from user code
"""
assert ssl, 'SSL not supported'
cafile = cafile or DEFAULT_CA_BUNDLE_PATH
if verify is True:
cert_reqs = ssl.CERT_REQUIRED
check_hostname = True
if isinstance(verify, str):
cert_reqs = ssl.CERT_REQUIRED
if os.path.isfile(verify):
cafile = verify
elif os.path.isdir(verify):
capath = verify
return ssl._create_unverified_context(cert_reqs=cert_reqs,
check_hostname=check_hostname,
certfile=certfile,
keyfile=keyfile,
cafile=cafile,
capath=capath,
cadata=cadata) | [
"def",
"ssl_context",
"(",
"self",
",",
"verify",
"=",
"True",
",",
"cert_reqs",
"=",
"None",
",",
"check_hostname",
"=",
"False",
",",
"certfile",
"=",
"None",
",",
"keyfile",
"=",
"None",
",",
"cafile",
"=",
"None",
",",
"capath",
"=",
"None",
",",
"cadata",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"assert",
"ssl",
",",
"'SSL not supported'",
"cafile",
"=",
"cafile",
"or",
"DEFAULT_CA_BUNDLE_PATH",
"if",
"verify",
"is",
"True",
":",
"cert_reqs",
"=",
"ssl",
".",
"CERT_REQUIRED",
"check_hostname",
"=",
"True",
"if",
"isinstance",
"(",
"verify",
",",
"str",
")",
":",
"cert_reqs",
"=",
"ssl",
".",
"CERT_REQUIRED",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"verify",
")",
":",
"cafile",
"=",
"verify",
"elif",
"os",
".",
"path",
".",
"isdir",
"(",
"verify",
")",
":",
"capath",
"=",
"verify",
"return",
"ssl",
".",
"_create_unverified_context",
"(",
"cert_reqs",
"=",
"cert_reqs",
",",
"check_hostname",
"=",
"check_hostname",
",",
"certfile",
"=",
"certfile",
",",
"keyfile",
"=",
"keyfile",
",",
"cafile",
"=",
"cafile",
",",
"capath",
"=",
"capath",
",",
"cadata",
"=",
"cadata",
")"
] | Create a SSL context object.
This method should not be called by from user code | [
"Create",
"a",
"SSL",
"context",
"object",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L972-L999 |
231,393 | quantmind/pulsar | pulsar/apps/http/client.py | HttpClient.create_tunnel_connection | async def create_tunnel_connection(self, req):
"""Create a tunnel connection
"""
tunnel_address = req.tunnel_address
connection = await self.create_connection(tunnel_address)
response = connection.current_consumer()
for event in response.events().values():
event.clear()
response.start(HttpTunnel(self, req))
await response.event('post_request').waiter()
if response.status_code != 200:
raise ConnectionRefusedError(
'Cannot connect to tunnel: status code %s'
% response.status_code
)
raw_sock = connection.transport.get_extra_info('socket')
if raw_sock is None:
raise RuntimeError('Transport without socket')
# duplicate socket so we can close transport
raw_sock = raw_sock.dup()
connection.transport.close()
await connection.event('connection_lost').waiter()
self.sessions -= 1
self.requests_processed -= 1
#
connection = await self.create_connection(
sock=raw_sock, ssl=req.ssl(self), server_hostname=req.netloc
)
return connection | python | async def create_tunnel_connection(self, req):
"""Create a tunnel connection
"""
tunnel_address = req.tunnel_address
connection = await self.create_connection(tunnel_address)
response = connection.current_consumer()
for event in response.events().values():
event.clear()
response.start(HttpTunnel(self, req))
await response.event('post_request').waiter()
if response.status_code != 200:
raise ConnectionRefusedError(
'Cannot connect to tunnel: status code %s'
% response.status_code
)
raw_sock = connection.transport.get_extra_info('socket')
if raw_sock is None:
raise RuntimeError('Transport without socket')
# duplicate socket so we can close transport
raw_sock = raw_sock.dup()
connection.transport.close()
await connection.event('connection_lost').waiter()
self.sessions -= 1
self.requests_processed -= 1
#
connection = await self.create_connection(
sock=raw_sock, ssl=req.ssl(self), server_hostname=req.netloc
)
return connection | [
"async",
"def",
"create_tunnel_connection",
"(",
"self",
",",
"req",
")",
":",
"tunnel_address",
"=",
"req",
".",
"tunnel_address",
"connection",
"=",
"await",
"self",
".",
"create_connection",
"(",
"tunnel_address",
")",
"response",
"=",
"connection",
".",
"current_consumer",
"(",
")",
"for",
"event",
"in",
"response",
".",
"events",
"(",
")",
".",
"values",
"(",
")",
":",
"event",
".",
"clear",
"(",
")",
"response",
".",
"start",
"(",
"HttpTunnel",
"(",
"self",
",",
"req",
")",
")",
"await",
"response",
".",
"event",
"(",
"'post_request'",
")",
".",
"waiter",
"(",
")",
"if",
"response",
".",
"status_code",
"!=",
"200",
":",
"raise",
"ConnectionRefusedError",
"(",
"'Cannot connect to tunnel: status code %s'",
"%",
"response",
".",
"status_code",
")",
"raw_sock",
"=",
"connection",
".",
"transport",
".",
"get_extra_info",
"(",
"'socket'",
")",
"if",
"raw_sock",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'Transport without socket'",
")",
"# duplicate socket so we can close transport",
"raw_sock",
"=",
"raw_sock",
".",
"dup",
"(",
")",
"connection",
".",
"transport",
".",
"close",
"(",
")",
"await",
"connection",
".",
"event",
"(",
"'connection_lost'",
")",
".",
"waiter",
"(",
")",
"self",
".",
"sessions",
"-=",
"1",
"self",
".",
"requests_processed",
"-=",
"1",
"#",
"connection",
"=",
"await",
"self",
".",
"create_connection",
"(",
"sock",
"=",
"raw_sock",
",",
"ssl",
"=",
"req",
".",
"ssl",
"(",
"self",
")",
",",
"server_hostname",
"=",
"req",
".",
"netloc",
")",
"return",
"connection"
] | Create a tunnel connection | [
"Create",
"a",
"tunnel",
"connection"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L1004-L1032 |
231,394 | quantmind/pulsar | pulsar/apps/__init__.py | Configurator.python_path | def python_path(self, script):
"""Called during initialisation to obtain the ``script`` name.
If ``script`` does not evaluate to ``True`` it is evaluated from
the ``__main__`` import. Returns the real path of the python
script which runs the application.
"""
if not script:
try:
import __main__
script = getfile(__main__)
except Exception: # pragma nocover
return
script = os.path.realpath(script)
if self.cfg.get('python_path', True):
path = os.path.dirname(script)
if path not in sys.path:
sys.path.insert(0, path)
return script | python | def python_path(self, script):
"""Called during initialisation to obtain the ``script`` name.
If ``script`` does not evaluate to ``True`` it is evaluated from
the ``__main__`` import. Returns the real path of the python
script which runs the application.
"""
if not script:
try:
import __main__
script = getfile(__main__)
except Exception: # pragma nocover
return
script = os.path.realpath(script)
if self.cfg.get('python_path', True):
path = os.path.dirname(script)
if path not in sys.path:
sys.path.insert(0, path)
return script | [
"def",
"python_path",
"(",
"self",
",",
"script",
")",
":",
"if",
"not",
"script",
":",
"try",
":",
"import",
"__main__",
"script",
"=",
"getfile",
"(",
"__main__",
")",
"except",
"Exception",
":",
"# pragma nocover",
"return",
"script",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"script",
")",
"if",
"self",
".",
"cfg",
".",
"get",
"(",
"'python_path'",
",",
"True",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"script",
")",
"if",
"path",
"not",
"in",
"sys",
".",
"path",
":",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"path",
")",
"return",
"script"
] | Called during initialisation to obtain the ``script`` name.
If ``script`` does not evaluate to ``True`` it is evaluated from
the ``__main__`` import. Returns the real path of the python
script which runs the application. | [
"Called",
"during",
"initialisation",
"to",
"obtain",
"the",
"script",
"name",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/__init__.py#L291-L309 |
231,395 | quantmind/pulsar | pulsar/apps/__init__.py | Configurator.start | def start(self, exit=True):
"""Invoked the application callable method and start
the ``arbiter`` if it wasn't already started.
It returns a :class:`~asyncio.Future` called back once the
application/applications are running. It returns ``None`` if
called more than once.
"""
on_start = self()
actor = arbiter()
if actor and on_start:
actor.start(exit=exit)
if actor.exit_code is not None:
return actor.exit_code
return on_start | python | def start(self, exit=True):
"""Invoked the application callable method and start
the ``arbiter`` if it wasn't already started.
It returns a :class:`~asyncio.Future` called back once the
application/applications are running. It returns ``None`` if
called more than once.
"""
on_start = self()
actor = arbiter()
if actor and on_start:
actor.start(exit=exit)
if actor.exit_code is not None:
return actor.exit_code
return on_start | [
"def",
"start",
"(",
"self",
",",
"exit",
"=",
"True",
")",
":",
"on_start",
"=",
"self",
"(",
")",
"actor",
"=",
"arbiter",
"(",
")",
"if",
"actor",
"and",
"on_start",
":",
"actor",
".",
"start",
"(",
"exit",
"=",
"exit",
")",
"if",
"actor",
".",
"exit_code",
"is",
"not",
"None",
":",
"return",
"actor",
".",
"exit_code",
"return",
"on_start"
] | Invoked the application callable method and start
the ``arbiter`` if it wasn't already started.
It returns a :class:`~asyncio.Future` called back once the
application/applications are running. It returns ``None`` if
called more than once. | [
"Invoked",
"the",
"application",
"callable",
"method",
"and",
"start",
"the",
"arbiter",
"if",
"it",
"wasn",
"t",
"already",
"started",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/__init__.py#L355-L369 |
231,396 | quantmind/pulsar | pulsar/apps/__init__.py | Application.stop | def stop(self, actor=None):
"""Stop the application
"""
if actor is None:
actor = get_actor()
if actor and actor.is_arbiter():
monitor = actor.get_actor(self.name)
if monitor:
return monitor.stop()
raise RuntimeError('Cannot stop application') | python | def stop(self, actor=None):
"""Stop the application
"""
if actor is None:
actor = get_actor()
if actor and actor.is_arbiter():
monitor = actor.get_actor(self.name)
if monitor:
return monitor.stop()
raise RuntimeError('Cannot stop application') | [
"def",
"stop",
"(",
"self",
",",
"actor",
"=",
"None",
")",
":",
"if",
"actor",
"is",
"None",
":",
"actor",
"=",
"get_actor",
"(",
")",
"if",
"actor",
"and",
"actor",
".",
"is_arbiter",
"(",
")",
":",
"monitor",
"=",
"actor",
".",
"get_actor",
"(",
"self",
".",
"name",
")",
"if",
"monitor",
":",
"return",
"monitor",
".",
"stop",
"(",
")",
"raise",
"RuntimeError",
"(",
"'Cannot stop application'",
")"
] | Stop the application | [
"Stop",
"the",
"application"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/__init__.py#L493-L502 |
231,397 | quantmind/pulsar | pulsar/utils/system/posixsystem.py | set_owner_process | def set_owner_process(uid, gid):
""" set user and group of workers processes """
if gid:
try:
os.setgid(gid)
except OverflowError:
# versions of python < 2.6.2 don't manage unsigned int for
# groups like on osx or fedora
os.setgid(-ctypes.c_int(-gid).value)
if uid:
os.setuid(uid) | python | def set_owner_process(uid, gid):
""" set user and group of workers processes """
if gid:
try:
os.setgid(gid)
except OverflowError:
# versions of python < 2.6.2 don't manage unsigned int for
# groups like on osx or fedora
os.setgid(-ctypes.c_int(-gid).value)
if uid:
os.setuid(uid) | [
"def",
"set_owner_process",
"(",
"uid",
",",
"gid",
")",
":",
"if",
"gid",
":",
"try",
":",
"os",
".",
"setgid",
"(",
"gid",
")",
"except",
"OverflowError",
":",
"# versions of python < 2.6.2 don't manage unsigned int for",
"# groups like on osx or fedora",
"os",
".",
"setgid",
"(",
"-",
"ctypes",
".",
"c_int",
"(",
"-",
"gid",
")",
".",
"value",
")",
"if",
"uid",
":",
"os",
".",
"setuid",
"(",
"uid",
")"
] | set user and group of workers processes | [
"set",
"user",
"and",
"group",
"of",
"workers",
"processes"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/system/posixsystem.py#L77-L87 |
231,398 | quantmind/pulsar | pulsar/apps/greenio/utils.py | wait | def wait(value, must_be_child=False):
'''Wait for a possible asynchronous value to complete.
'''
current = getcurrent()
parent = current.parent
if must_be_child and not parent:
raise MustBeInChildGreenlet('Cannot wait on main greenlet')
return parent.switch(value) if parent else value | python | def wait(value, must_be_child=False):
'''Wait for a possible asynchronous value to complete.
'''
current = getcurrent()
parent = current.parent
if must_be_child and not parent:
raise MustBeInChildGreenlet('Cannot wait on main greenlet')
return parent.switch(value) if parent else value | [
"def",
"wait",
"(",
"value",
",",
"must_be_child",
"=",
"False",
")",
":",
"current",
"=",
"getcurrent",
"(",
")",
"parent",
"=",
"current",
".",
"parent",
"if",
"must_be_child",
"and",
"not",
"parent",
":",
"raise",
"MustBeInChildGreenlet",
"(",
"'Cannot wait on main greenlet'",
")",
"return",
"parent",
".",
"switch",
"(",
"value",
")",
"if",
"parent",
"else",
"value"
] | Wait for a possible asynchronous value to complete. | [
"Wait",
"for",
"a",
"possible",
"asynchronous",
"value",
"to",
"complete",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/greenio/utils.py#L17-L24 |
231,399 | quantmind/pulsar | pulsar/apps/greenio/utils.py | run_in_greenlet | def run_in_greenlet(callable):
"""Decorator to run a ``callable`` on a new greenlet.
A ``callable`` decorated with this decorator returns a coroutine
"""
@wraps(callable)
async def _(*args, **kwargs):
green = greenlet(callable)
# switch to the new greenlet
result = green.switch(*args, **kwargs)
# back to the parent
while isawaitable(result):
# keep on switching back to the greenlet if we get an awaitable
try:
result = green.switch((await result))
except Exception:
exc_info = sys.exc_info()
result = green.throw(*exc_info)
return green.switch(result)
return _ | python | def run_in_greenlet(callable):
"""Decorator to run a ``callable`` on a new greenlet.
A ``callable`` decorated with this decorator returns a coroutine
"""
@wraps(callable)
async def _(*args, **kwargs):
green = greenlet(callable)
# switch to the new greenlet
result = green.switch(*args, **kwargs)
# back to the parent
while isawaitable(result):
# keep on switching back to the greenlet if we get an awaitable
try:
result = green.switch((await result))
except Exception:
exc_info = sys.exc_info()
result = green.throw(*exc_info)
return green.switch(result)
return _ | [
"def",
"run_in_greenlet",
"(",
"callable",
")",
":",
"@",
"wraps",
"(",
"callable",
")",
"async",
"def",
"_",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"green",
"=",
"greenlet",
"(",
"callable",
")",
"# switch to the new greenlet",
"result",
"=",
"green",
".",
"switch",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# back to the parent",
"while",
"isawaitable",
"(",
"result",
")",
":",
"# keep on switching back to the greenlet if we get an awaitable",
"try",
":",
"result",
"=",
"green",
".",
"switch",
"(",
"(",
"await",
"result",
")",
")",
"except",
"Exception",
":",
"exc_info",
"=",
"sys",
".",
"exc_info",
"(",
")",
"result",
"=",
"green",
".",
"throw",
"(",
"*",
"exc_info",
")",
"return",
"green",
".",
"switch",
"(",
"result",
")",
"return",
"_"
] | Decorator to run a ``callable`` on a new greenlet.
A ``callable`` decorated with this decorator returns a coroutine | [
"Decorator",
"to",
"run",
"a",
"callable",
"on",
"a",
"new",
"greenlet",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/greenio/utils.py#L27-L48 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.