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
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
245,100
quantmind/pulsar
pulsar/utils/config.py
Config.copy_globals
def copy_globals(self, cfg): """Copy global settings from ``cfg`` to this config. The settings are copied only if they were not already modified. """ for name, setting in cfg.settings.items(): csetting = self.settings.get(name) if (setting.is_global and csetting is not None and not csetting.modified): csetting.set(setting.get())
python
def copy_globals(self, cfg): for name, setting in cfg.settings.items(): csetting = self.settings.get(name) if (setting.is_global and csetting is not None and not csetting.modified): csetting.set(setting.get())
[ "def", "copy_globals", "(", "self", ",", "cfg", ")", ":", "for", "name", ",", "setting", "in", "cfg", ".", "settings", ".", "items", "(", ")", ":", "csetting", "=", "self", ".", "settings", ".", "get", "(", "name", ")", "if", "(", "setting", ".", ...
Copy global settings from ``cfg`` to this config. The settings are copied only if they were not already modified.
[ "Copy", "global", "settings", "from", "cfg", "to", "this", "config", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/config.py#L197-L206
245,101
quantmind/pulsar
pulsar/utils/config.py
Config.parse_command_line
def parse_command_line(self, argv=None): """Parse the command line """ if self.config: parser = argparse.ArgumentParser(add_help=False) self.settings['config'].add_argument(parser) opts, _ = parser.parse_known_args(argv) if opts.config is not None: self.set('config', opts.config) self.params.update(self.import_from_module()) parser = self.parser() opts = parser.parse_args(argv) for k, v in opts.__dict__.items(): if v is None: continue self.set(k.lower(), v)
python
def parse_command_line(self, argv=None): if self.config: parser = argparse.ArgumentParser(add_help=False) self.settings['config'].add_argument(parser) opts, _ = parser.parse_known_args(argv) if opts.config is not None: self.set('config', opts.config) self.params.update(self.import_from_module()) parser = self.parser() opts = parser.parse_args(argv) for k, v in opts.__dict__.items(): if v is None: continue self.set(k.lower(), v)
[ "def", "parse_command_line", "(", "self", ",", "argv", "=", "None", ")", ":", "if", "self", ".", "config", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "add_help", "=", "False", ")", "self", ".", "settings", "[", "'config'", "]", ".", "a...
Parse the command line
[ "Parse", "the", "command", "line" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/config.py#L291-L308
245,102
quantmind/pulsar
pulsar/utils/tools/text.py
num2eng
def num2eng(num): '''English representation of a number up to a trillion. ''' num = str(int(num)) # Convert to string, throw if bad number if (len(num) / 3 >= len(_PRONOUNCE)): # Sanity check return num elif num == '0': # Zero is a special case return 'zero' pron = [] # Result accumulator first = True for pr, bits in zip(_PRONOUNCE, grouper(3, reversed(num), '')): num = ''.join(reversed(bits)) n = int(num) bits = [] if n > 99: # Got hundred bits.append('%s hundred' % _SMALL[num[0]]) num = num[1:] n = int(num) num = str(n) if (n > 20) and (n != (n // 10 * 10)): bits.append('%s %s' % (_SMALL[num[0] + '0'], _SMALL[num[1]])) elif n: bits.append(_SMALL[num]) if len(bits) == 2 and first: first = False p = ' and '.join(bits) else: p = ' '.join(bits) if p and pr: p = '%s %s' % (p, pr) pron.append(p) return ', '.join(reversed(pron))
python
def num2eng(num): '''English representation of a number up to a trillion. ''' num = str(int(num)) # Convert to string, throw if bad number if (len(num) / 3 >= len(_PRONOUNCE)): # Sanity check return num elif num == '0': # Zero is a special case return 'zero' pron = [] # Result accumulator first = True for pr, bits in zip(_PRONOUNCE, grouper(3, reversed(num), '')): num = ''.join(reversed(bits)) n = int(num) bits = [] if n > 99: # Got hundred bits.append('%s hundred' % _SMALL[num[0]]) num = num[1:] n = int(num) num = str(n) if (n > 20) and (n != (n // 10 * 10)): bits.append('%s %s' % (_SMALL[num[0] + '0'], _SMALL[num[1]])) elif n: bits.append(_SMALL[num]) if len(bits) == 2 and first: first = False p = ' and '.join(bits) else: p = ' '.join(bits) if p and pr: p = '%s %s' % (p, pr) pron.append(p) return ', '.join(reversed(pron))
[ "def", "num2eng", "(", "num", ")", ":", "num", "=", "str", "(", "int", "(", "num", ")", ")", "# Convert to string, throw if bad number", "if", "(", "len", "(", "num", ")", "/", "3", ">=", "len", "(", "_PRONOUNCE", ")", ")", ":", "# Sanity check", "retu...
English representation of a number up to a trillion.
[ "English", "representation", "of", "a", "number", "up", "to", "a", "trillion", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/tools/text.py#L48-L79
245,103
quantmind/pulsar
pulsar/apps/rpc/jsonrpc.py
JsonProxy.get_params
def get_params(self, *args, **kwargs): ''' Create an array or positional or named parameters Mixing positional and named parameters in one call is not possible. ''' kwargs.update(self._data) if args and kwargs: raise ValueError('Cannot mix positional and named parameters') if args: return list(args) else: return kwargs
python
def get_params(self, *args, **kwargs): ''' Create an array or positional or named parameters Mixing positional and named parameters in one call is not possible. ''' kwargs.update(self._data) if args and kwargs: raise ValueError('Cannot mix positional and named parameters') if args: return list(args) else: return kwargs
[ "def", "get_params", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "self", ".", "_data", ")", "if", "args", "and", "kwargs", ":", "raise", "ValueError", "(", "'Cannot mix positional and named parameters'", ...
Create an array or positional or named parameters Mixing positional and named parameters in one call is not possible.
[ "Create", "an", "array", "or", "positional", "or", "named", "parameters", "Mixing", "positional", "and", "named", "parameters", "in", "one", "call", "is", "not", "possible", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/rpc/jsonrpc.py#L253-L265
245,104
quantmind/pulsar
pulsar/async/mailbox.py
MessageConsumer.send
def send(self, command, sender, target, args, kwargs): """Used by the server to send messages to the client. Returns a future. """ command = get_command(command) data = {'command': command.__name__, 'id': create_aid(), 'sender': actor_identity(sender), 'target': actor_identity(target), 'args': args if args is not None else (), 'kwargs': kwargs if kwargs is not None else {}} waiter = self._loop.create_future() ack = None if command.ack: ack = create_aid() data['ack'] = ack self.pending_responses[ack] = waiter try: self.write(data) except Exception as exc: waiter.set_exception(exc) if ack: self.pending_responses.pop(ack, None) else: if not ack: waiter.set_result(None) return waiter
python
def send(self, command, sender, target, args, kwargs): command = get_command(command) data = {'command': command.__name__, 'id': create_aid(), 'sender': actor_identity(sender), 'target': actor_identity(target), 'args': args if args is not None else (), 'kwargs': kwargs if kwargs is not None else {}} waiter = self._loop.create_future() ack = None if command.ack: ack = create_aid() data['ack'] = ack self.pending_responses[ack] = waiter try: self.write(data) except Exception as exc: waiter.set_exception(exc) if ack: self.pending_responses.pop(ack, None) else: if not ack: waiter.set_result(None) return waiter
[ "def", "send", "(", "self", ",", "command", ",", "sender", ",", "target", ",", "args", ",", "kwargs", ")", ":", "command", "=", "get_command", "(", "command", ")", "data", "=", "{", "'command'", ":", "command", ".", "__name__", ",", "'id'", ":", "cre...
Used by the server to send messages to the client. Returns a future.
[ "Used", "by", "the", "server", "to", "send", "messages", "to", "the", "client", ".", "Returns", "a", "future", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/mailbox.py#L156-L184
245,105
quantmind/pulsar
pulsar/utils/tools/pidfile.py
Pidfile.read
def read(self): """ Validate pidfile and make it stale if needed""" if not self.fname: return try: with open(self.fname, "r") as f: wpid = int(f.read() or 0) if wpid <= 0: return return wpid except IOError: return
python
def read(self): if not self.fname: return try: with open(self.fname, "r") as f: wpid = int(f.read() or 0) if wpid <= 0: return return wpid except IOError: return
[ "def", "read", "(", "self", ")", ":", "if", "not", "self", ".", "fname", ":", "return", "try", ":", "with", "open", "(", "self", ".", "fname", ",", "\"r\"", ")", "as", "f", ":", "wpid", "=", "int", "(", "f", ".", "read", "(", ")", "or", "0", ...
Validate pidfile and make it stale if needed
[ "Validate", "pidfile", "and", "make", "it", "stale", "if", "needed" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/tools/pidfile.py#L54-L65
245,106
quantmind/pulsar
pulsar/apps/greenio/lock.py
GreenLock.acquire
def acquire(self, timeout=None): """Acquires the lock if in the unlocked state otherwise switch back to the parent coroutine. """ green = getcurrent() parent = green.parent if parent is None: raise MustBeInChildGreenlet('GreenLock.acquire in main greenlet') if self._local.locked: future = create_future(self._loop) self._queue.append(future) parent.switch(future) self._local.locked = green return self.locked()
python
def acquire(self, timeout=None): green = getcurrent() parent = green.parent if parent is None: raise MustBeInChildGreenlet('GreenLock.acquire in main greenlet') if self._local.locked: future = create_future(self._loop) self._queue.append(future) parent.switch(future) self._local.locked = green return self.locked()
[ "def", "acquire", "(", "self", ",", "timeout", "=", "None", ")", ":", "green", "=", "getcurrent", "(", ")", "parent", "=", "green", ".", "parent", "if", "parent", "is", "None", ":", "raise", "MustBeInChildGreenlet", "(", "'GreenLock.acquire in main greenlet'",...
Acquires the lock if in the unlocked state otherwise switch back to the parent coroutine.
[ "Acquires", "the", "lock", "if", "in", "the", "unlocked", "state", "otherwise", "switch", "back", "to", "the", "parent", "coroutine", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/greenio/lock.py#L38-L53
245,107
quantmind/pulsar
pulsar/apps/wsgi/wrappers.py
WsgiRequest.cookies
def cookies(self): """Container of request cookies """ cookies = SimpleCookie() cookie = self.environ.get('HTTP_COOKIE') if cookie: cookies.load(cookie) return cookies
python
def cookies(self): cookies = SimpleCookie() cookie = self.environ.get('HTTP_COOKIE') if cookie: cookies.load(cookie) return cookies
[ "def", "cookies", "(", "self", ")", ":", "cookies", "=", "SimpleCookie", "(", ")", "cookie", "=", "self", ".", "environ", ".", "get", "(", "'HTTP_COOKIE'", ")", "if", "cookie", ":", "cookies", ".", "load", "(", "cookie", ")", "return", "cookies" ]
Container of request cookies
[ "Container", "of", "request", "cookies" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/wrappers.py#L172-L179
245,108
quantmind/pulsar
pulsar/apps/wsgi/wrappers.py
WsgiRequest.data_and_files
def data_and_files(self, data=True, files=True, stream=None): """Retrieve body data. Returns a two-elements tuple of a :class:`~.MultiValueDict` containing data from the request body, and data from uploaded files. If the body data is not ready, return a :class:`~asyncio.Future` which results in the tuple. The result is cached. """ if self.method in ENCODE_URL_METHODS: value = {}, None else: value = self.cache.get('data_and_files') if not value: return self._data_and_files(data, files, stream) elif data and files: return value elif data: return value[0] elif files: return value[1] else: return None
python
def data_and_files(self, data=True, files=True, stream=None): if self.method in ENCODE_URL_METHODS: value = {}, None else: value = self.cache.get('data_and_files') if not value: return self._data_and_files(data, files, stream) elif data and files: return value elif data: return value[0] elif files: return value[1] else: return None
[ "def", "data_and_files", "(", "self", ",", "data", "=", "True", ",", "files", "=", "True", ",", "stream", "=", "None", ")", ":", "if", "self", ".", "method", "in", "ENCODE_URL_METHODS", ":", "value", "=", "{", "}", ",", "None", "else", ":", "value", ...
Retrieve body data. Returns a two-elements tuple of a :class:`~.MultiValueDict` containing data from the request body, and data from uploaded files. If the body data is not ready, return a :class:`~asyncio.Future` which results in the tuple. The result is cached.
[ "Retrieve", "body", "data", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/wrappers.py#L266-L292
245,109
quantmind/pulsar
pulsar/apps/wsgi/wrappers.py
WsgiRequest.get_host
def get_host(self, use_x_forwarded=True): """Returns the HTTP host using the environment or request headers.""" # We try three options, in order of decreasing preference. if use_x_forwarded and ('HTTP_X_FORWARDED_HOST' in self.environ): host = self.environ['HTTP_X_FORWARDED_HOST'] port = self.environ.get('HTTP_X_FORWARDED_PORT') if port and port != ('443' if self.is_secure else '80'): host = '%s:%s' % (host, port) return host elif 'HTTP_HOST' in self.environ: host = self.environ['HTTP_HOST'] else: # Reconstruct the host using the algorithm from PEP 333. host = self.environ['SERVER_NAME'] server_port = str(self.environ['SERVER_PORT']) if server_port != ('443' if self.is_secure else '80'): host = '%s:%s' % (host, server_port) return host
python
def get_host(self, use_x_forwarded=True): # We try three options, in order of decreasing preference. if use_x_forwarded and ('HTTP_X_FORWARDED_HOST' in self.environ): host = self.environ['HTTP_X_FORWARDED_HOST'] port = self.environ.get('HTTP_X_FORWARDED_PORT') if port and port != ('443' if self.is_secure else '80'): host = '%s:%s' % (host, port) return host elif 'HTTP_HOST' in self.environ: host = self.environ['HTTP_HOST'] else: # Reconstruct the host using the algorithm from PEP 333. host = self.environ['SERVER_NAME'] server_port = str(self.environ['SERVER_PORT']) if server_port != ('443' if self.is_secure else '80'): host = '%s:%s' % (host, server_port) return host
[ "def", "get_host", "(", "self", ",", "use_x_forwarded", "=", "True", ")", ":", "# We try three options, in order of decreasing preference.", "if", "use_x_forwarded", "and", "(", "'HTTP_X_FORWARDED_HOST'", "in", "self", ".", "environ", ")", ":", "host", "=", "self", ...
Returns the HTTP host using the environment or request headers.
[ "Returns", "the", "HTTP", "host", "using", "the", "environment", "or", "request", "headers", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/wrappers.py#L325-L342
245,110
quantmind/pulsar
pulsar/apps/wsgi/wrappers.py
WsgiRequest.get_client_address
def get_client_address(self, use_x_forwarded=True): """Obtain the client IP address """ xfor = self.environ.get('HTTP_X_FORWARDED_FOR') if use_x_forwarded and xfor: return xfor.split(',')[-1].strip() else: return self.environ['REMOTE_ADDR']
python
def get_client_address(self, use_x_forwarded=True): xfor = self.environ.get('HTTP_X_FORWARDED_FOR') if use_x_forwarded and xfor: return xfor.split(',')[-1].strip() else: return self.environ['REMOTE_ADDR']
[ "def", "get_client_address", "(", "self", ",", "use_x_forwarded", "=", "True", ")", ":", "xfor", "=", "self", ".", "environ", ".", "get", "(", "'HTTP_X_FORWARDED_FOR'", ")", "if", "use_x_forwarded", "and", "xfor", ":", "return", "xfor", ".", "split", "(", ...
Obtain the client IP address
[ "Obtain", "the", "client", "IP", "address" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/wrappers.py#L344-L351
245,111
quantmind/pulsar
pulsar/apps/wsgi/wrappers.py
WsgiRequest.full_path
def full_path(self, *args, **query): """Return a full path""" path = None if args: if len(args) > 1: raise TypeError("full_url() takes exactly 1 argument " "(%s given)" % len(args)) path = args[0] if not path: path = self.path elif not path.startswith('/'): path = remove_double_slash('%s/%s' % (self.path, path)) return iri_to_uri(path, query)
python
def full_path(self, *args, **query): path = None if args: if len(args) > 1: raise TypeError("full_url() takes exactly 1 argument " "(%s given)" % len(args)) path = args[0] if not path: path = self.path elif not path.startswith('/'): path = remove_double_slash('%s/%s' % (self.path, path)) return iri_to_uri(path, query)
[ "def", "full_path", "(", "self", ",", "*", "args", ",", "*", "*", "query", ")", ":", "path", "=", "None", "if", "args", ":", "if", "len", "(", "args", ")", ">", "1", ":", "raise", "TypeError", "(", "\"full_url() takes exactly 1 argument \"", "\"(%s given...
Return a full path
[ "Return", "a", "full", "path" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/wrappers.py#L353-L365
245,112
quantmind/pulsar
pulsar/apps/wsgi/wrappers.py
WsgiRequest.absolute_uri
def absolute_uri(self, location=None, scheme=None, **query): """Builds an absolute URI from ``location`` and variables available in this request. If no ``location`` is specified, the relative URI is built from :meth:`full_path`. """ if not is_absolute_uri(location): if location or location is None: location = self.full_path(location, **query) if not scheme: scheme = self.is_secure and 'https' or 'http' base = '%s://%s' % (scheme, self.get_host()) return '%s%s' % (base, location) elif not scheme: return iri_to_uri(location) else: raise ValueError('Absolute location with scheme not valid')
python
def absolute_uri(self, location=None, scheme=None, **query): if not is_absolute_uri(location): if location or location is None: location = self.full_path(location, **query) if not scheme: scheme = self.is_secure and 'https' or 'http' base = '%s://%s' % (scheme, self.get_host()) return '%s%s' % (base, location) elif not scheme: return iri_to_uri(location) else: raise ValueError('Absolute location with scheme not valid')
[ "def", "absolute_uri", "(", "self", ",", "location", "=", "None", ",", "scheme", "=", "None", ",", "*", "*", "query", ")", ":", "if", "not", "is_absolute_uri", "(", "location", ")", ":", "if", "location", "or", "location", "is", "None", ":", "location"...
Builds an absolute URI from ``location`` and variables available in this request. If no ``location`` is specified, the relative URI is built from :meth:`full_path`.
[ "Builds", "an", "absolute", "URI", "from", "location", "and", "variables", "available", "in", "this", "request", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/wrappers.py#L367-L384
245,113
quantmind/pulsar
pulsar/apps/wsgi/wrappers.py
WsgiRequest.set_response_content_type
def set_response_content_type(self, response_content_types=None): '''Evaluate the content type for the response to a client ``request``. The method uses the :attr:`response_content_types` parameter of accepted content types and the content types accepted by the client ``request`` and figures out the best match. ''' request_content_types = self.content_types if request_content_types: ct = request_content_types.best_match(response_content_types) if ct and '*' in ct: ct = None if not ct and response_content_types: raise HttpException(status=415, msg=request_content_types) self.response.content_type = ct
python
def set_response_content_type(self, response_content_types=None): '''Evaluate the content type for the response to a client ``request``. The method uses the :attr:`response_content_types` parameter of accepted content types and the content types accepted by the client ``request`` and figures out the best match. ''' request_content_types = self.content_types if request_content_types: ct = request_content_types.best_match(response_content_types) if ct and '*' in ct: ct = None if not ct and response_content_types: raise HttpException(status=415, msg=request_content_types) self.response.content_type = ct
[ "def", "set_response_content_type", "(", "self", ",", "response_content_types", "=", "None", ")", ":", "request_content_types", "=", "self", ".", "content_types", "if", "request_content_types", ":", "ct", "=", "request_content_types", ".", "best_match", "(", "response...
Evaluate the content type for the response to a client ``request``. The method uses the :attr:`response_content_types` parameter of accepted content types and the content types accepted by the client ``request`` and figures out the best match.
[ "Evaluate", "the", "content", "type", "for", "the", "response", "to", "a", "client", "request", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/wrappers.py#L391-L405
245,114
quantmind/pulsar
pulsar/utils/tools/arity.py
checkarity
def checkarity(func, args, kwargs, discount=0): '''Check if arguments respect a given function arity and return an error message if the check did not pass, otherwise it returns ``None``. :parameter func: the function. :parameter args: function arguments. :parameter kwargs: function key-valued parameters. :parameter discount: optional integer which discount the number of positional argument to check. Default ``0``. ''' spec = inspect.getargspec(func) self = getattr(func, '__self__', None) if self and spec.args: discount += 1 args = list(args) defaults = list(spec.defaults or ()) len_defaults = len(defaults) len_args = len(spec.args) - discount len_args_input = len(args) minlen = len_args - len_defaults totlen = len_args_input + len(kwargs) maxlen = len_args if spec.varargs or spec.keywords: maxlen = None if not minlen: return if not spec.defaults and maxlen: start = '"{0}" takes'.format(func.__name__) else: if maxlen and totlen > maxlen: start = '"{0}" takes at most'.format(func.__name__) else: start = '"{0}" takes at least'.format(func.__name__) if totlen < minlen: return '{0} {1} parameters. {2} given.'.format(start, minlen, totlen) elif maxlen and totlen > maxlen: return '{0} {1} parameters. {2} given.'.format(start, maxlen, totlen) # Length of parameter OK, check names if len_args_input < len_args: le = minlen - len_args_input for arg in spec.args[discount:]: if args: args.pop(0) else: if le > 0: if defaults: defaults.pop(0) elif arg not in kwargs: return ('"{0}" has missing "{1}" parameter.' .format(func.__name__, arg)) kwargs.pop(arg, None) le -= 1 if kwargs and maxlen: s = '' if len(kwargs) > 1: s = 's' p = ', '.join('"{0}"'.format(p) for p in kwargs) return ('"{0}" does not accept {1} parameter{2}.' .format(func.__name__, p, s)) elif len_args_input > len_args + len_defaults: n = len_args + len_defaults start = '"{0}" takes'.format(func.__name__) return ('{0} {1} positional parameters. {2} given.' .format(start, n, len_args_input))
python
def checkarity(func, args, kwargs, discount=0): '''Check if arguments respect a given function arity and return an error message if the check did not pass, otherwise it returns ``None``. :parameter func: the function. :parameter args: function arguments. :parameter kwargs: function key-valued parameters. :parameter discount: optional integer which discount the number of positional argument to check. Default ``0``. ''' spec = inspect.getargspec(func) self = getattr(func, '__self__', None) if self and spec.args: discount += 1 args = list(args) defaults = list(spec.defaults or ()) len_defaults = len(defaults) len_args = len(spec.args) - discount len_args_input = len(args) minlen = len_args - len_defaults totlen = len_args_input + len(kwargs) maxlen = len_args if spec.varargs or spec.keywords: maxlen = None if not minlen: return if not spec.defaults and maxlen: start = '"{0}" takes'.format(func.__name__) else: if maxlen and totlen > maxlen: start = '"{0}" takes at most'.format(func.__name__) else: start = '"{0}" takes at least'.format(func.__name__) if totlen < minlen: return '{0} {1} parameters. {2} given.'.format(start, minlen, totlen) elif maxlen and totlen > maxlen: return '{0} {1} parameters. {2} given.'.format(start, maxlen, totlen) # Length of parameter OK, check names if len_args_input < len_args: le = minlen - len_args_input for arg in spec.args[discount:]: if args: args.pop(0) else: if le > 0: if defaults: defaults.pop(0) elif arg not in kwargs: return ('"{0}" has missing "{1}" parameter.' .format(func.__name__, arg)) kwargs.pop(arg, None) le -= 1 if kwargs and maxlen: s = '' if len(kwargs) > 1: s = 's' p = ', '.join('"{0}"'.format(p) for p in kwargs) return ('"{0}" does not accept {1} parameter{2}.' .format(func.__name__, p, s)) elif len_args_input > len_args + len_defaults: n = len_args + len_defaults start = '"{0}" takes'.format(func.__name__) return ('{0} {1} positional parameters. {2} given.' .format(start, n, len_args_input))
[ "def", "checkarity", "(", "func", ",", "args", ",", "kwargs", ",", "discount", "=", "0", ")", ":", "spec", "=", "inspect", ".", "getargspec", "(", "func", ")", "self", "=", "getattr", "(", "func", ",", "'__self__'", ",", "None", ")", "if", "self", ...
Check if arguments respect a given function arity and return an error message if the check did not pass, otherwise it returns ``None``. :parameter func: the function. :parameter args: function arguments. :parameter kwargs: function key-valued parameters. :parameter discount: optional integer which discount the number of positional argument to check. Default ``0``.
[ "Check", "if", "arguments", "respect", "a", "given", "function", "arity", "and", "return", "an", "error", "message", "if", "the", "check", "did", "not", "pass", "otherwise", "it", "returns", "None", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/tools/arity.py#L6-L73
245,115
quantmind/pulsar
docs/_ext/sphinxtogithub.py
sphinx_extension
def sphinx_extension(app, exception): "Wrapped up as a Sphinx Extension" if not app.builder.name in ("html", "dirhtml"): return if not app.config.sphinx_to_github: if app.config.sphinx_to_github_verbose: print("Sphinx-to-github: Disabled, doing nothing.") return if exception: if app.config.sphinx_to_github_verbose: print("Sphinx-to-github: Exception raised in main build, doing nothing.") return dir_helper = DirHelper( os.path.isdir, os.listdir, os.walk, shutil.rmtree ) file_helper = FileSystemHelper( open, os.path.join, shutil.move, os.path.exists ) operations_factory = OperationsFactory() handler_factory = HandlerFactory() layout_factory = LayoutFactory( operations_factory, handler_factory, file_helper, dir_helper, app.config.sphinx_to_github_verbose, sys.stdout, force=True ) layout = layout_factory.create_layout(app.outdir) layout.process()
python
def sphinx_extension(app, exception): "Wrapped up as a Sphinx Extension" if not app.builder.name in ("html", "dirhtml"): return if not app.config.sphinx_to_github: if app.config.sphinx_to_github_verbose: print("Sphinx-to-github: Disabled, doing nothing.") return if exception: if app.config.sphinx_to_github_verbose: print("Sphinx-to-github: Exception raised in main build, doing nothing.") return dir_helper = DirHelper( os.path.isdir, os.listdir, os.walk, shutil.rmtree ) file_helper = FileSystemHelper( open, os.path.join, shutil.move, os.path.exists ) operations_factory = OperationsFactory() handler_factory = HandlerFactory() layout_factory = LayoutFactory( operations_factory, handler_factory, file_helper, dir_helper, app.config.sphinx_to_github_verbose, sys.stdout, force=True ) layout = layout_factory.create_layout(app.outdir) layout.process()
[ "def", "sphinx_extension", "(", "app", ",", "exception", ")", ":", "if", "not", "app", ".", "builder", ".", "name", "in", "(", "\"html\"", ",", "\"dirhtml\"", ")", ":", "return", "if", "not", "app", ".", "config", ".", "sphinx_to_github", ":", "if", "a...
Wrapped up as a Sphinx Extension
[ "Wrapped", "up", "as", "a", "Sphinx", "Extension" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/docs/_ext/sphinxtogithub.py#L242-L285
245,116
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", "(", "\...
Setup function for Sphinx Extension
[ "Setup", "function", "for", "Sphinx", "Extension" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/docs/_ext/sphinxtogithub.py#L288-L292
245,117
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", "=", "'/'", ".", ...
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
245,118
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", ...
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
245,119
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", ":", "re...
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
245,120
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): 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"...
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
245,121
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
245,122
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", "-",...
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
245,123
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", "=", "op...
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
245,124
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
245,125
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
245,126
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
245,127
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('&', '&amp;').replace( '<', '&lt;').replace('>', '&gt;').replace("'", '&#39;').replace( '"', '&quot;')
python
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('&', '&amp;').replace( '<', '&lt;').replace('>', '&gt;').replace("'", '&#39;').replace( '"', '&quot;')
[ "def", "escape", "(", "html", ",", "force", "=", "False", ")", ":", "if", "hasattr", "(", "html", ",", "'__html__'", ")", "and", "not", "force", ":", "return", "html", "if", "html", "in", "NOTHING", ":", "return", "''", "else", ":", "return", "to_str...
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
245,128
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", ":", ...
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
245,129
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", "(", "'_'", ",", "' '", ")", ".", "spli...
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
245,130
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): 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", "=", "{"...
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
245,131
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): 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'", ")", ...
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
245,132
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", ")", ...
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
245,133
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", ...
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
245,134
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", ...
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
245,135
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", ...
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
245,136
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", "=", ...
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
245,137
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", ")", ...
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
245,138
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 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
245,139
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", ...
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
245,140
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", ":", ...
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
245,141
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", ".", "m...
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
245,142
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", "=", "'styleshee...
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
245,143
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...
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
245,144
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", ")", "a...
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
245,145
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", "...
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
245,146
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"...
Lists of random walks.
[ "Lists", "of", "random", "walks", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/calculator/manage.py#L22-L32
245,147
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",...
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
245,148
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
245,149
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", "(", ")", "ret...
Encode a message when publishing.
[ "Encode", "a", "message", "when", "publishing", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/chat/manage.py#L70-L75
245,150
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", ":", "lin...
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
245,151
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
245,152
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", ...
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
245,153
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): 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", "...
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
245,154
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"...
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
245,155
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", "(", "\"/+\"", ",", "'/'", ",",...
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
245,156
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", ...
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
245,157
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", "(", ...
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
245,158
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", ...
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
245,159
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", ".", "logge...
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
245,160
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/p...
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
245,161
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): 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", ...
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", ...
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/formdata.py#L372-L389
245,162
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"...
``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
245,163
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
245,164
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): 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", ":...
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
245,165
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...
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
245,166
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", ...
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
245,167
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): 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-lengt...
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
245,168
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): 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", ".", "...
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
245,169
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): 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", "(...
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
245,170
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", "=", "{", ...
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
245,171
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(): 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", ".", "envi...
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
245,172
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): 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'", "]", ")", "e...
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
245,173
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_INF...
Execute a new ``request``.
[ "Execute", "a", "new", "request", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/ds/client.py#L65-L83
245,174
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", ".", "_c...
Handle response cookies.
[ "Handle", "response", "cookies", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/plugins.py#L191-L206
245,175
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", "=", "r...
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
245,176
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", "(", "mod...
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
245,177
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", ...
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
245,178
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"...
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
245,179
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", "=", "pr...
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
245,180
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", ")",...
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
245,181
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", "]", "*", "SK...
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
245,182
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
245,183
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", ...
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
245,184
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", "]", "*",...
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
245,185
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", ...
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
245,186
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): 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
245,187
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): 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", "(",...
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
245,188
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): 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", ...
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", "fi...
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/structures.py#L121-L141
245,189
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", ")", ...
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
245,190
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", "(", "pi...
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
245,191
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): 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 servi...
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
245,192
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): 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", "(", "...
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
245,193
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): 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", ...
create the server endpoint.
[ "create", "the", "server", "endpoint", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/protocols.py#L333-L351
245,194
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", "(", ...
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
245,195
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_reques...
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
245,196
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", ".", "e...
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
245,197
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): 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
245,198
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): 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", ...
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
245,199
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): 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", "(", ...
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