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
226,000
marshmallow-code/webargs
src/webargs/core.py
Parser.use_kwargs
def use_kwargs(self, *args, **kwargs): """Decorator that injects parsed arguments into a view function or method as keyword arguments. This is a shortcut to :meth:`use_args` with ``as_kwargs=True``. Example usage with Flask: :: @app.route('/echo', methods=['get', 'post']) @parser.use_kwargs({'name': fields.Str()}) def greet(name): return 'Hello ' + name Receives the same ``args`` and ``kwargs`` as :meth:`use_args`. """ kwargs["as_kwargs"] = True return self.use_args(*args, **kwargs)
python
def use_kwargs(self, *args, **kwargs): kwargs["as_kwargs"] = True return self.use_args(*args, **kwargs)
[ "def", "use_kwargs", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "\"as_kwargs\"", "]", "=", "True", "return", "self", ".", "use_args", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Decorator that injects parsed arguments into a view function or method as keyword arguments. This is a shortcut to :meth:`use_args` with ``as_kwargs=True``. Example usage with Flask: :: @app.route('/echo', methods=['get', 'post']) @parser.use_kwargs({'name': fields.Str()}) def greet(name): return 'Hello ' + name Receives the same ``args`` and ``kwargs`` as :meth:`use_args`.
[ "Decorator", "that", "injects", "parsed", "arguments", "into", "a", "view", "function", "or", "method", "as", "keyword", "arguments", "." ]
40cc2d25421d15d9630b1a819f1dcefbbf01ed95
https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/src/webargs/core.py#L479-L495
226,001
marshmallow-code/webargs
src/webargs/core.py
Parser.handle_error
def handle_error( self, error, req, schema, error_status_code=None, error_headers=None ): """Called if an error occurs while parsing args. By default, just logs and raises ``error``. """ logger.error(error) raise error
python
def handle_error( self, error, req, schema, error_status_code=None, error_headers=None ): logger.error(error) raise error
[ "def", "handle_error", "(", "self", ",", "error", ",", "req", ",", "schema", ",", "error_status_code", "=", "None", ",", "error_headers", "=", "None", ")", ":", "logger", ".", "error", "(", "error", ")", "raise", "error" ]
Called if an error occurs while parsing args. By default, just logs and raises ``error``.
[ "Called", "if", "an", "error", "occurs", "while", "parsing", "args", ".", "By", "default", "just", "logs", "and", "raises", "error", "." ]
40cc2d25421d15d9630b1a819f1dcefbbf01ed95
https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/src/webargs/core.py#L585-L592
226,002
marshmallow-code/webargs
src/webargs/tornadoparser.py
parse_json_body
def parse_json_body(req): """Return the decoded JSON body from the request.""" content_type = req.headers.get("Content-Type") if content_type and core.is_json(content_type): try: return core.parse_json(req.body) except TypeError: pass except json.JSONDecodeError as e: if e.doc == "": return core.missing else: raise return {}
python
def parse_json_body(req): content_type = req.headers.get("Content-Type") if content_type and core.is_json(content_type): try: return core.parse_json(req.body) except TypeError: pass except json.JSONDecodeError as e: if e.doc == "": return core.missing else: raise return {}
[ "def", "parse_json_body", "(", "req", ")", ":", "content_type", "=", "req", ".", "headers", ".", "get", "(", "\"Content-Type\"", ")", "if", "content_type", "and", "core", ".", "is_json", "(", "content_type", ")", ":", "try", ":", "return", "core", ".", "...
Return the decoded JSON body from the request.
[ "Return", "the", "decoded", "JSON", "body", "from", "the", "request", "." ]
40cc2d25421d15d9630b1a819f1dcefbbf01ed95
https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/src/webargs/tornadoparser.py#L34-L47
226,003
marshmallow-code/webargs
src/webargs/tornadoparser.py
get_value
def get_value(d, name, field): """Handle gets from 'multidicts' made of lists It handles cases: ``{"key": [value]}`` and ``{"key": value}`` """ multiple = core.is_multiple(field) value = d.get(name, core.missing) if value is core.missing: return core.missing if multiple and value is not core.missing: return [ decode_argument(v, name) if isinstance(v, basestring) else v for v in value ] ret = value if value and isinstance(value, (list, tuple)): ret = value[0] if isinstance(ret, basestring): return decode_argument(ret, name) else: return ret
python
def get_value(d, name, field): multiple = core.is_multiple(field) value = d.get(name, core.missing) if value is core.missing: return core.missing if multiple and value is not core.missing: return [ decode_argument(v, name) if isinstance(v, basestring) else v for v in value ] ret = value if value and isinstance(value, (list, tuple)): ret = value[0] if isinstance(ret, basestring): return decode_argument(ret, name) else: return ret
[ "def", "get_value", "(", "d", ",", "name", ",", "field", ")", ":", "multiple", "=", "core", ".", "is_multiple", "(", "field", ")", "value", "=", "d", ".", "get", "(", "name", ",", "core", ".", "missing", ")", "if", "value", "is", "core", ".", "mi...
Handle gets from 'multidicts' made of lists It handles cases: ``{"key": [value]}`` and ``{"key": value}``
[ "Handle", "gets", "from", "multidicts", "made", "of", "lists" ]
40cc2d25421d15d9630b1a819f1dcefbbf01ed95
https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/src/webargs/tornadoparser.py#L60-L79
226,004
marshmallow-code/webargs
src/webargs/tornadoparser.py
TornadoParser.handle_error
def handle_error(self, error, req, schema, error_status_code, error_headers): """Handles errors during parsing. Raises a `tornado.web.HTTPError` with a 400 error. """ status_code = error_status_code or self.DEFAULT_VALIDATION_STATUS if status_code == 422: reason = "Unprocessable Entity" else: reason = None raise HTTPError( status_code, log_message=str(error.messages), reason=reason, messages=error.messages, headers=error_headers, )
python
def handle_error(self, error, req, schema, error_status_code, error_headers): status_code = error_status_code or self.DEFAULT_VALIDATION_STATUS if status_code == 422: reason = "Unprocessable Entity" else: reason = None raise HTTPError( status_code, log_message=str(error.messages), reason=reason, messages=error.messages, headers=error_headers, )
[ "def", "handle_error", "(", "self", ",", "error", ",", "req", ",", "schema", ",", "error_status_code", ",", "error_headers", ")", ":", "status_code", "=", "error_status_code", "or", "self", ".", "DEFAULT_VALIDATION_STATUS", "if", "status_code", "==", "422", ":",...
Handles errors during parsing. Raises a `tornado.web.HTTPError` with a 400 error.
[ "Handles", "errors", "during", "parsing", ".", "Raises", "a", "tornado", ".", "web", ".", "HTTPError", "with", "a", "400", "error", "." ]
40cc2d25421d15d9630b1a819f1dcefbbf01ed95
https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/src/webargs/tornadoparser.py#L122-L137
226,005
marshmallow-code/webargs
src/webargs/pyramidparser.py
PyramidParser.parse_matchdict
def parse_matchdict(self, req, name, field): """Pull a value from the request's `matchdict`.""" return core.get_value(req.matchdict, name, field)
python
def parse_matchdict(self, req, name, field): return core.get_value(req.matchdict, name, field)
[ "def", "parse_matchdict", "(", "self", ",", "req", ",", "name", ",", "field", ")", ":", "return", "core", ".", "get_value", "(", "req", ".", "matchdict", ",", "name", ",", "field", ")" ]
Pull a value from the request's `matchdict`.
[ "Pull", "a", "value", "from", "the", "request", "s", "matchdict", "." ]
40cc2d25421d15d9630b1a819f1dcefbbf01ed95
https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/src/webargs/pyramidparser.py#L84-L86
226,006
marshmallow-code/webargs
src/webargs/pyramidparser.py
PyramidParser.handle_error
def handle_error(self, error, req, schema, error_status_code, error_headers): """Handles errors during parsing. Aborts the current HTTP request and responds with a 400 error. """ status_code = error_status_code or self.DEFAULT_VALIDATION_STATUS response = exception_response( status_code, detail=text_type(error), headers=error_headers, content_type="application/json", ) body = json.dumps(error.messages) response.body = body.encode("utf-8") if isinstance(body, text_type) else body raise response
python
def handle_error(self, error, req, schema, error_status_code, error_headers): status_code = error_status_code or self.DEFAULT_VALIDATION_STATUS response = exception_response( status_code, detail=text_type(error), headers=error_headers, content_type="application/json", ) body = json.dumps(error.messages) response.body = body.encode("utf-8") if isinstance(body, text_type) else body raise response
[ "def", "handle_error", "(", "self", ",", "error", ",", "req", ",", "schema", ",", "error_status_code", ",", "error_headers", ")", ":", "status_code", "=", "error_status_code", "or", "self", ".", "DEFAULT_VALIDATION_STATUS", "response", "=", "exception_response", "...
Handles errors during parsing. Aborts the current HTTP request and responds with a 400 error.
[ "Handles", "errors", "during", "parsing", ".", "Aborts", "the", "current", "HTTP", "request", "and", "responds", "with", "a", "400", "error", "." ]
40cc2d25421d15d9630b1a819f1dcefbbf01ed95
https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/src/webargs/pyramidparser.py#L88-L101
226,007
marshmallow-code/webargs
examples/annotations_example.py
route
def route(*args, response_formatter=jsonify, **kwargs): """Combines `Flask.route` and webargs parsing. Allows arguments to be specified as function annotations. An output schema can optionally be specified by a return annotation. """ def decorator(func): @app.route(*args, **kwargs) @functools.wraps(func) def wrapped_view(*a, **kw): annotations = getattr(func, "__annotations__", {}) reqargs = { name: value for name, value in annotations.items() if isinstance(value, fields.Field) and name != "return" } response_schema = annotations.get("return") parsed = parser.parse(reqargs, request) kw.update(parsed) response_data = func(*a, **kw) if response_schema: return response_formatter(response_schema.dump(response_data).data) else: return response_formatter(func(*a, **kw)) return wrapped_view return decorator
python
def route(*args, response_formatter=jsonify, **kwargs): def decorator(func): @app.route(*args, **kwargs) @functools.wraps(func) def wrapped_view(*a, **kw): annotations = getattr(func, "__annotations__", {}) reqargs = { name: value for name, value in annotations.items() if isinstance(value, fields.Field) and name != "return" } response_schema = annotations.get("return") parsed = parser.parse(reqargs, request) kw.update(parsed) response_data = func(*a, **kw) if response_schema: return response_formatter(response_schema.dump(response_data).data) else: return response_formatter(func(*a, **kw)) return wrapped_view return decorator
[ "def", "route", "(", "*", "args", ",", "response_formatter", "=", "jsonify", ",", "*", "*", "kwargs", ")", ":", "def", "decorator", "(", "func", ")", ":", "@", "app", ".", "route", "(", "*", "args", ",", "*", "*", "kwargs", ")", "@", "functools", ...
Combines `Flask.route` and webargs parsing. Allows arguments to be specified as function annotations. An output schema can optionally be specified by a return annotation.
[ "Combines", "Flask", ".", "route", "and", "webargs", "parsing", ".", "Allows", "arguments", "to", "be", "specified", "as", "function", "annotations", ".", "An", "output", "schema", "can", "optionally", "be", "specified", "by", "a", "return", "annotation", "." ...
40cc2d25421d15d9630b1a819f1dcefbbf01ed95
https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/examples/annotations_example.py#L15-L42
226,008
marshmallow-code/webargs
examples/tornado_example.py
BaseRequestHandler.write_error
def write_error(self, status_code, **kwargs): """Write errors as JSON.""" self.set_header("Content-Type", "application/json") if "exc_info" in kwargs: etype, exc, traceback = kwargs["exc_info"] if hasattr(exc, "messages"): self.write({"errors": exc.messages}) if getattr(exc, "headers", None): for name, val in exc.headers.items(): self.set_header(name, val) self.finish()
python
def write_error(self, status_code, **kwargs): self.set_header("Content-Type", "application/json") if "exc_info" in kwargs: etype, exc, traceback = kwargs["exc_info"] if hasattr(exc, "messages"): self.write({"errors": exc.messages}) if getattr(exc, "headers", None): for name, val in exc.headers.items(): self.set_header(name, val) self.finish()
[ "def", "write_error", "(", "self", ",", "status_code", ",", "*", "*", "kwargs", ")", ":", "self", ".", "set_header", "(", "\"Content-Type\"", ",", "\"application/json\"", ")", "if", "\"exc_info\"", "in", "kwargs", ":", "etype", ",", "exc", ",", "traceback", ...
Write errors as JSON.
[ "Write", "errors", "as", "JSON", "." ]
40cc2d25421d15d9630b1a819f1dcefbbf01ed95
https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/examples/tornado_example.py#L24-L34
226,009
marshmallow-code/webargs
src/webargs/falconparser.py
HTTPError.to_dict
def to_dict(self, *args, **kwargs): """Override `falcon.HTTPError` to include error messages in responses.""" ret = super(HTTPError, self).to_dict(*args, **kwargs) if self.errors is not None: ret["errors"] = self.errors return ret
python
def to_dict(self, *args, **kwargs): ret = super(HTTPError, self).to_dict(*args, **kwargs) if self.errors is not None: ret["errors"] = self.errors return ret
[ "def", "to_dict", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "super", "(", "HTTPError", ",", "self", ")", ".", "to_dict", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "self", ".", "errors", "is", "not...
Override `falcon.HTTPError` to include error messages in responses.
[ "Override", "falcon", ".", "HTTPError", "to", "include", "error", "messages", "in", "responses", "." ]
40cc2d25421d15d9630b1a819f1dcefbbf01ed95
https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/src/webargs/falconparser.py#L83-L88
226,010
marshmallow-code/webargs
src/webargs/falconparser.py
FalconParser.parse_headers
def parse_headers(self, req, name, field): """Pull a header value from the request.""" # Use req.get_headers rather than req.headers for performance return req.get_header(name, required=False) or core.missing
python
def parse_headers(self, req, name, field): # Use req.get_headers rather than req.headers for performance return req.get_header(name, required=False) or core.missing
[ "def", "parse_headers", "(", "self", ",", "req", ",", "name", ",", "field", ")", ":", "# Use req.get_headers rather than req.headers for performance", "return", "req", ".", "get_header", "(", "name", ",", "required", "=", "False", ")", "or", "core", ".", "missin...
Pull a header value from the request.
[ "Pull", "a", "header", "value", "from", "the", "request", "." ]
40cc2d25421d15d9630b1a819f1dcefbbf01ed95
https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/src/webargs/falconparser.py#L125-L128
226,011
marshmallow-code/webargs
src/webargs/falconparser.py
FalconParser.parse_cookies
def parse_cookies(self, req, name, field): """Pull a cookie value from the request.""" cookies = self._cache.get("cookies") if cookies is None: self._cache["cookies"] = cookies = req.cookies return core.get_value(cookies, name, field)
python
def parse_cookies(self, req, name, field): cookies = self._cache.get("cookies") if cookies is None: self._cache["cookies"] = cookies = req.cookies return core.get_value(cookies, name, field)
[ "def", "parse_cookies", "(", "self", ",", "req", ",", "name", ",", "field", ")", ":", "cookies", "=", "self", ".", "_cache", ".", "get", "(", "\"cookies\"", ")", "if", "cookies", "is", "None", ":", "self", ".", "_cache", "[", "\"cookies\"", "]", "=",...
Pull a cookie value from the request.
[ "Pull", "a", "cookie", "value", "from", "the", "request", "." ]
40cc2d25421d15d9630b1a819f1dcefbbf01ed95
https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/src/webargs/falconparser.py#L130-L135
226,012
marshmallow-code/webargs
src/webargs/falconparser.py
FalconParser.get_request_from_view_args
def get_request_from_view_args(self, view, args, kwargs): """Get request from a resource method's arguments. Assumes that request is the second argument. """ req = args[1] assert isinstance(req, falcon.Request), "Argument is not a falcon.Request" return req
python
def get_request_from_view_args(self, view, args, kwargs): req = args[1] assert isinstance(req, falcon.Request), "Argument is not a falcon.Request" return req
[ "def", "get_request_from_view_args", "(", "self", ",", "view", ",", "args", ",", "kwargs", ")", ":", "req", "=", "args", "[", "1", "]", "assert", "isinstance", "(", "req", ",", "falcon", ".", "Request", ")", ",", "\"Argument is not a falcon.Request\"", "retu...
Get request from a resource method's arguments. Assumes that request is the second argument.
[ "Get", "request", "from", "a", "resource", "method", "s", "arguments", ".", "Assumes", "that", "request", "is", "the", "second", "argument", "." ]
40cc2d25421d15d9630b1a819f1dcefbbf01ed95
https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/src/webargs/falconparser.py#L137-L143
226,013
marshmallow-code/webargs
src/webargs/falconparser.py
FalconParser.handle_error
def handle_error(self, error, req, schema, error_status_code, error_headers): """Handles errors during parsing.""" status = status_map.get(error_status_code or self.DEFAULT_VALIDATION_STATUS) if status is None: raise LookupError("Status code {0} not supported".format(error_status_code)) raise HTTPError(status, errors=error.messages, headers=error_headers)
python
def handle_error(self, error, req, schema, error_status_code, error_headers): status = status_map.get(error_status_code or self.DEFAULT_VALIDATION_STATUS) if status is None: raise LookupError("Status code {0} not supported".format(error_status_code)) raise HTTPError(status, errors=error.messages, headers=error_headers)
[ "def", "handle_error", "(", "self", ",", "error", ",", "req", ",", "schema", ",", "error_status_code", ",", "error_headers", ")", ":", "status", "=", "status_map", ".", "get", "(", "error_status_code", "or", "self", ".", "DEFAULT_VALIDATION_STATUS", ")", "if",...
Handles errors during parsing.
[ "Handles", "errors", "during", "parsing", "." ]
40cc2d25421d15d9630b1a819f1dcefbbf01ed95
https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/src/webargs/falconparser.py#L150-L155
226,014
marshmallow-code/webargs
src/webargs/asyncparser.py
AsyncParser.parse
async def parse( self, argmap: ArgMap, req: Request = None, locations: typing.Iterable = None, validate: Validate = None, error_status_code: typing.Union[int, None] = None, error_headers: typing.Union[typing.Mapping[str, str], None] = None, ) -> typing.Union[typing.Mapping, None]: """Coroutine variant of `webargs.core.Parser`. Receives the same arguments as `webargs.core.Parser.parse`. """ self.clear_cache() # in case someone used `parse_*()` req = req if req is not None else self.get_default_request() assert req is not None, "Must pass req object" data = None validators = core._ensure_list_of_callables(validate) schema = self._get_schema(argmap, req) try: parsed = await self._parse_request( schema=schema, req=req, locations=locations or self.locations ) result = schema.load(parsed) data = result.data if core.MARSHMALLOW_VERSION_INFO[0] < 3 else result self._validate_arguments(data, validators) except ma.exceptions.ValidationError as error: await self._on_validation_error( error, req, schema, error_status_code, error_headers ) return data
python
async def parse( self, argmap: ArgMap, req: Request = None, locations: typing.Iterable = None, validate: Validate = None, error_status_code: typing.Union[int, None] = None, error_headers: typing.Union[typing.Mapping[str, str], None] = None, ) -> typing.Union[typing.Mapping, None]: self.clear_cache() # in case someone used `parse_*()` req = req if req is not None else self.get_default_request() assert req is not None, "Must pass req object" data = None validators = core._ensure_list_of_callables(validate) schema = self._get_schema(argmap, req) try: parsed = await self._parse_request( schema=schema, req=req, locations=locations or self.locations ) result = schema.load(parsed) data = result.data if core.MARSHMALLOW_VERSION_INFO[0] < 3 else result self._validate_arguments(data, validators) except ma.exceptions.ValidationError as error: await self._on_validation_error( error, req, schema, error_status_code, error_headers ) return data
[ "async", "def", "parse", "(", "self", ",", "argmap", ":", "ArgMap", ",", "req", ":", "Request", "=", "None", ",", "locations", ":", "typing", ".", "Iterable", "=", "None", ",", "validate", ":", "Validate", "=", "None", ",", "error_status_code", ":", "t...
Coroutine variant of `webargs.core.Parser`. Receives the same arguments as `webargs.core.Parser.parse`.
[ "Coroutine", "variant", "of", "webargs", ".", "core", ".", "Parser", "." ]
40cc2d25421d15d9630b1a819f1dcefbbf01ed95
https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/src/webargs/asyncparser.py#L67-L97
226,015
marshmallow-code/webargs
src/webargs/aiohttpparser.py
AIOHTTPParser.parse_cookies
def parse_cookies(self, req: Request, name: str, field: Field) -> typing.Any: """Pull a value from the cookiejar.""" return core.get_value(req.cookies, name, field)
python
def parse_cookies(self, req: Request, name: str, field: Field) -> typing.Any: return core.get_value(req.cookies, name, field)
[ "def", "parse_cookies", "(", "self", ",", "req", ":", "Request", ",", "name", ":", "str", ",", "field", ":", "Field", ")", "->", "typing", ".", "Any", ":", "return", "core", ".", "get_value", "(", "req", ".", "cookies", ",", "name", ",", "field", "...
Pull a value from the cookiejar.
[ "Pull", "a", "value", "from", "the", "cookiejar", "." ]
40cc2d25421d15d9630b1a819f1dcefbbf01ed95
https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/src/webargs/aiohttpparser.py#L112-L114
226,016
marshmallow-code/webargs
src/webargs/aiohttpparser.py
AIOHTTPParser.parse_match_info
def parse_match_info(self, req: Request, name: str, field: Field) -> typing.Any: """Pull a value from the request's ``match_info``.""" return core.get_value(req.match_info, name, field)
python
def parse_match_info(self, req: Request, name: str, field: Field) -> typing.Any: return core.get_value(req.match_info, name, field)
[ "def", "parse_match_info", "(", "self", ",", "req", ":", "Request", ",", "name", ":", "str", ",", "field", ":", "Field", ")", "->", "typing", ".", "Any", ":", "return", "core", ".", "get_value", "(", "req", ".", "match_info", ",", "name", ",", "field...
Pull a value from the request's ``match_info``.
[ "Pull", "a", "value", "from", "the", "request", "s", "match_info", "." ]
40cc2d25421d15d9630b1a819f1dcefbbf01ed95
https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/src/webargs/aiohttpparser.py#L122-L124
226,017
marshmallow-code/webargs
src/webargs/aiohttpparser.py
AIOHTTPParser.handle_error
def handle_error( self, error: ValidationError, req: Request, schema: Schema, error_status_code: typing.Union[int, None] = None, error_headers: typing.Union[typing.Mapping[str, str], None] = None, ) -> "typing.NoReturn": """Handle ValidationErrors and return a JSON response of error messages to the client. """ error_class = exception_map.get( error_status_code or self.DEFAULT_VALIDATION_STATUS ) if not error_class: raise LookupError("No exception for {0}".format(error_status_code)) headers = error_headers raise error_class( body=json.dumps(error.messages).encode("utf-8"), headers=headers, content_type="application/json", )
python
def handle_error( self, error: ValidationError, req: Request, schema: Schema, error_status_code: typing.Union[int, None] = None, error_headers: typing.Union[typing.Mapping[str, str], None] = None, ) -> "typing.NoReturn": error_class = exception_map.get( error_status_code or self.DEFAULT_VALIDATION_STATUS ) if not error_class: raise LookupError("No exception for {0}".format(error_status_code)) headers = error_headers raise error_class( body=json.dumps(error.messages).encode("utf-8"), headers=headers, content_type="application/json", )
[ "def", "handle_error", "(", "self", ",", "error", ":", "ValidationError", ",", "req", ":", "Request", ",", "schema", ":", "Schema", ",", "error_status_code", ":", "typing", ".", "Union", "[", "int", ",", "None", "]", "=", "None", ",", "error_headers", ":...
Handle ValidationErrors and return a JSON response of error messages to the client.
[ "Handle", "ValidationErrors", "and", "return", "a", "JSON", "response", "of", "error", "messages", "to", "the", "client", "." ]
40cc2d25421d15d9630b1a819f1dcefbbf01ed95
https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/src/webargs/aiohttpparser.py#L143-L164
226,018
marshmallow-code/webargs
src/webargs/bottleparser.py
BottleParser.handle_error
def handle_error(self, error, req, schema, error_status_code, error_headers): """Handles errors during parsing. Aborts the current request with a 400 error. """ status_code = error_status_code or self.DEFAULT_VALIDATION_STATUS raise bottle.HTTPError( status=status_code, body=error.messages, headers=error_headers, exception=error, )
python
def handle_error(self, error, req, schema, error_status_code, error_headers): status_code = error_status_code or self.DEFAULT_VALIDATION_STATUS raise bottle.HTTPError( status=status_code, body=error.messages, headers=error_headers, exception=error, )
[ "def", "handle_error", "(", "self", ",", "error", ",", "req", ",", "schema", ",", "error_status_code", ",", "error_headers", ")", ":", "status_code", "=", "error_status_code", "or", "self", ".", "DEFAULT_VALIDATION_STATUS", "raise", "bottle", ".", "HTTPError", "...
Handles errors during parsing. Aborts the current request with a 400 error.
[ "Handles", "errors", "during", "parsing", ".", "Aborts", "the", "current", "request", "with", "a", "400", "error", "." ]
40cc2d25421d15d9630b1a819f1dcefbbf01ed95
https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/src/webargs/bottleparser.py#L66-L76
226,019
marshmallow-code/webargs
examples/flaskrestful_example.py
handle_request_parsing_error
def handle_request_parsing_error(err, req, schema, error_status_code, error_headers): """webargs error handler that uses Flask-RESTful's abort function to return a JSON error response to the client. """ abort(error_status_code, errors=err.messages)
python
def handle_request_parsing_error(err, req, schema, error_status_code, error_headers): abort(error_status_code, errors=err.messages)
[ "def", "handle_request_parsing_error", "(", "err", ",", "req", ",", "schema", ",", "error_status_code", ",", "error_headers", ")", ":", "abort", "(", "error_status_code", ",", "errors", "=", "err", ".", "messages", ")" ]
webargs error handler that uses Flask-RESTful's abort function to return a JSON error response to the client.
[ "webargs", "error", "handler", "that", "uses", "Flask", "-", "RESTful", "s", "abort", "function", "to", "return", "a", "JSON", "error", "response", "to", "the", "client", "." ]
40cc2d25421d15d9630b1a819f1dcefbbf01ed95
https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/examples/flaskrestful_example.py#L73-L77
226,020
marshmallow-code/webargs
examples/flaskrestful_example.py
DateAddResource.post
def post(self, value, addend, unit): """A date adder endpoint.""" value = value or dt.datetime.utcnow() if unit == "minutes": delta = dt.timedelta(minutes=addend) else: delta = dt.timedelta(days=addend) result = value + delta return {"result": result.isoformat()}
python
def post(self, value, addend, unit): value = value or dt.datetime.utcnow() if unit == "minutes": delta = dt.timedelta(minutes=addend) else: delta = dt.timedelta(days=addend) result = value + delta return {"result": result.isoformat()}
[ "def", "post", "(", "self", ",", "value", ",", "addend", ",", "unit", ")", ":", "value", "=", "value", "or", "dt", ".", "datetime", ".", "utcnow", "(", ")", "if", "unit", "==", "\"minutes\"", ":", "delta", "=", "dt", ".", "timedelta", "(", "minutes...
A date adder endpoint.
[ "A", "date", "adder", "endpoint", "." ]
40cc2d25421d15d9630b1a819f1dcefbbf01ed95
https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/examples/flaskrestful_example.py#L60-L68
226,021
addisonlynch/iexfinance
iexfinance/iexdata/__init__.py
get_stats_daily
def get_stats_daily(start=None, end=None, last=None, **kwargs): """ Stats Historical Daily This call will return daily stats for a given month or day. .. warning:: This endpoint is marked as "in development" by the provider. Reference: https://iexcloud.io/docs/api/#stats-historical-daily-in-dev Data Weighting: ``Free`` Parameters ---------- start: datetime.datetime, default None, optional Start of data retrieval period end: datetime.datetime, default None, optional End of data retrieval period last: int, default None, optional Used in place of date range to retrieve previous number of trading days (up to 90) kwargs: Additional Request Parameters (see base class) """ start, end = _sanitize_dates(start, end) return DailySummaryReader(start=start, end=end, last=last, **kwargs).fetch()
python
def get_stats_daily(start=None, end=None, last=None, **kwargs): start, end = _sanitize_dates(start, end) return DailySummaryReader(start=start, end=end, last=last, **kwargs).fetch()
[ "def", "get_stats_daily", "(", "start", "=", "None", ",", "end", "=", "None", ",", "last", "=", "None", ",", "*", "*", "kwargs", ")", ":", "start", ",", "end", "=", "_sanitize_dates", "(", "start", ",", "end", ")", "return", "DailySummaryReader", "(", ...
Stats Historical Daily This call will return daily stats for a given month or day. .. warning:: This endpoint is marked as "in development" by the provider. Reference: https://iexcloud.io/docs/api/#stats-historical-daily-in-dev Data Weighting: ``Free`` Parameters ---------- start: datetime.datetime, default None, optional Start of data retrieval period end: datetime.datetime, default None, optional End of data retrieval period last: int, default None, optional Used in place of date range to retrieve previous number of trading days (up to 90) kwargs: Additional Request Parameters (see base class)
[ "Stats", "Historical", "Daily" ]
40f0bdcc51b329031d06178020fd774494250456
https://github.com/addisonlynch/iexfinance/blob/40f0bdcc51b329031d06178020fd774494250456/iexfinance/iexdata/__init__.py#L148-L173
226,022
addisonlynch/iexfinance
iexfinance/iexdata/__init__.py
get_stats_summary
def get_stats_summary(start=None, end=None, **kwargs): """ Stats Historical Summary Reference: https://iexcloud.io/docs/api/#stats-historical-summary Data Weighting: ``Free`` Parameters ---------- start: datetime.datetime, default None, optional Start of data retrieval period end: datetime.datetime, default None, optional End of data retrieval period kwargs: Additional Request Parameters (see base class) """ return MonthlySummaryReader(start=start, end=end, **kwargs).fetch()
python
def get_stats_summary(start=None, end=None, **kwargs): return MonthlySummaryReader(start=start, end=end, **kwargs).fetch()
[ "def", "get_stats_summary", "(", "start", "=", "None", ",", "end", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "MonthlySummaryReader", "(", "start", "=", "start", ",", "end", "=", "end", ",", "*", "*", "kwargs", ")", ".", "fetch", "(", ...
Stats Historical Summary Reference: https://iexcloud.io/docs/api/#stats-historical-summary Data Weighting: ``Free`` Parameters ---------- start: datetime.datetime, default None, optional Start of data retrieval period end: datetime.datetime, default None, optional End of data retrieval period kwargs: Additional Request Parameters (see base class)
[ "Stats", "Historical", "Summary" ]
40f0bdcc51b329031d06178020fd774494250456
https://github.com/addisonlynch/iexfinance/blob/40f0bdcc51b329031d06178020fd774494250456/iexfinance/iexdata/__init__.py#L176-L192
226,023
addisonlynch/iexfinance
iexfinance/__init__.py
get_market_gainers
def get_market_gainers(*args, **kwargs): """ MOVED to iexfinance.stocks.get_market_gainers """ import warnings warnings.warn(WNG_MSG, ("get_market_gainers", "stocks.get_market_gainers")) return stocks.get_market_gainers(*args, **kwargs)
python
def get_market_gainers(*args, **kwargs): import warnings warnings.warn(WNG_MSG, ("get_market_gainers", "stocks.get_market_gainers")) return stocks.get_market_gainers(*args, **kwargs)
[ "def", "get_market_gainers", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "import", "warnings", "warnings", ".", "warn", "(", "WNG_MSG", ",", "(", "\"get_market_gainers\"", ",", "\"stocks.get_market_gainers\"", ")", ")", "return", "stocks", ".", "get_m...
MOVED to iexfinance.stocks.get_market_gainers
[ "MOVED", "to", "iexfinance", ".", "stocks", ".", "get_market_gainers" ]
40f0bdcc51b329031d06178020fd774494250456
https://github.com/addisonlynch/iexfinance/blob/40f0bdcc51b329031d06178020fd774494250456/iexfinance/__init__.py#L25-L31
226,024
addisonlynch/iexfinance
iexfinance/__init__.py
get_market_losers
def get_market_losers(*args, **kwargs): """ MOVED to iexfinance.stocks.get_market_losers """ import warnings warnings.warn(WNG_MSG, ("get_market_losers", "stocks.get_market_losers")) return stocks.get_market_losers(*args, **kwargs)
python
def get_market_losers(*args, **kwargs): import warnings warnings.warn(WNG_MSG, ("get_market_losers", "stocks.get_market_losers")) return stocks.get_market_losers(*args, **kwargs)
[ "def", "get_market_losers", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "import", "warnings", "warnings", ".", "warn", "(", "WNG_MSG", ",", "(", "\"get_market_losers\"", ",", "\"stocks.get_market_losers\"", ")", ")", "return", "stocks", ".", "get_mark...
MOVED to iexfinance.stocks.get_market_losers
[ "MOVED", "to", "iexfinance", ".", "stocks", ".", "get_market_losers" ]
40f0bdcc51b329031d06178020fd774494250456
https://github.com/addisonlynch/iexfinance/blob/40f0bdcc51b329031d06178020fd774494250456/iexfinance/__init__.py#L34-L40
226,025
addisonlynch/iexfinance
iexfinance/__init__.py
get_market_most_active
def get_market_most_active(*args, **kwargs): """ MOVED to iexfinance.stocks.get_market_most_active """ import warnings warnings.warn(WNG_MSG, ("get_market_most_active", "stocks.get_market_most_active")) return stocks.get_market_most_active(*args, **kwargs)
python
def get_market_most_active(*args, **kwargs): import warnings warnings.warn(WNG_MSG, ("get_market_most_active", "stocks.get_market_most_active")) return stocks.get_market_most_active(*args, **kwargs)
[ "def", "get_market_most_active", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "import", "warnings", "warnings", ".", "warn", "(", "WNG_MSG", ",", "(", "\"get_market_most_active\"", ",", "\"stocks.get_market_most_active\"", ")", ")", "return", "stocks", "...
MOVED to iexfinance.stocks.get_market_most_active
[ "MOVED", "to", "iexfinance", ".", "stocks", ".", "get_market_most_active" ]
40f0bdcc51b329031d06178020fd774494250456
https://github.com/addisonlynch/iexfinance/blob/40f0bdcc51b329031d06178020fd774494250456/iexfinance/__init__.py#L43-L50
226,026
addisonlynch/iexfinance
iexfinance/__init__.py
get_market_iex_volume
def get_market_iex_volume(*args, **kwargs): """ MOVED to iexfinance.stocks.get_market_iex_volume """ import warnings warnings.warn(WNG_MSG, ("get_market_iex_volume", "stocks.get_market_iex_volume")) return stocks.get_market_iex_volume(*args, **kwargs)
python
def get_market_iex_volume(*args, **kwargs): import warnings warnings.warn(WNG_MSG, ("get_market_iex_volume", "stocks.get_market_iex_volume")) return stocks.get_market_iex_volume(*args, **kwargs)
[ "def", "get_market_iex_volume", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "import", "warnings", "warnings", ".", "warn", "(", "WNG_MSG", ",", "(", "\"get_market_iex_volume\"", ",", "\"stocks.get_market_iex_volume\"", ")", ")", "return", "stocks", ".",...
MOVED to iexfinance.stocks.get_market_iex_volume
[ "MOVED", "to", "iexfinance", ".", "stocks", ".", "get_market_iex_volume" ]
40f0bdcc51b329031d06178020fd774494250456
https://github.com/addisonlynch/iexfinance/blob/40f0bdcc51b329031d06178020fd774494250456/iexfinance/__init__.py#L53-L60
226,027
addisonlynch/iexfinance
iexfinance/__init__.py
get_market_iex_percent
def get_market_iex_percent(*args, **kwargs): """ MOVED to iexfinance.stocks.get_market_iex_percent """ import warnings warnings.warn(WNG_MSG, ("get_market_iex_percent", "stocks.get_market_iex_percent")) return stocks.get_market_iex_percent(*args, **kwargs)
python
def get_market_iex_percent(*args, **kwargs): import warnings warnings.warn(WNG_MSG, ("get_market_iex_percent", "stocks.get_market_iex_percent")) return stocks.get_market_iex_percent(*args, **kwargs)
[ "def", "get_market_iex_percent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "import", "warnings", "warnings", ".", "warn", "(", "WNG_MSG", ",", "(", "\"get_market_iex_percent\"", ",", "\"stocks.get_market_iex_percent\"", ")", ")", "return", "stocks", "...
MOVED to iexfinance.stocks.get_market_iex_percent
[ "MOVED", "to", "iexfinance", ".", "stocks", ".", "get_market_iex_percent" ]
40f0bdcc51b329031d06178020fd774494250456
https://github.com/addisonlynch/iexfinance/blob/40f0bdcc51b329031d06178020fd774494250456/iexfinance/__init__.py#L63-L70
226,028
addisonlynch/iexfinance
iexfinance/__init__.py
get_available_symbols
def get_available_symbols(**kwargs): """ MOVED to iexfinance.refdata.get_symbols """ import warnings warnings.warn(WNG_MSG % ("get_available_symbols", "refdata.get_symbols")) _ALL_SYMBOLS_URL = "https://api.iextrading.com/1.0/ref-data/symbols" handler = _IEXBase(**kwargs) response = handler._execute_iex_query(_ALL_SYMBOLS_URL) if not response: raise IEXQueryError("Could not download all symbols") else: return response
python
def get_available_symbols(**kwargs): import warnings warnings.warn(WNG_MSG % ("get_available_symbols", "refdata.get_symbols")) _ALL_SYMBOLS_URL = "https://api.iextrading.com/1.0/ref-data/symbols" handler = _IEXBase(**kwargs) response = handler._execute_iex_query(_ALL_SYMBOLS_URL) if not response: raise IEXQueryError("Could not download all symbols") else: return response
[ "def", "get_available_symbols", "(", "*", "*", "kwargs", ")", ":", "import", "warnings", "warnings", ".", "warn", "(", "WNG_MSG", "%", "(", "\"get_available_symbols\"", ",", "\"refdata.get_symbols\"", ")", ")", "_ALL_SYMBOLS_URL", "=", "\"https://api.iextrading.com/1....
MOVED to iexfinance.refdata.get_symbols
[ "MOVED", "to", "iexfinance", ".", "refdata", ".", "get_symbols" ]
40f0bdcc51b329031d06178020fd774494250456
https://github.com/addisonlynch/iexfinance/blob/40f0bdcc51b329031d06178020fd774494250456/iexfinance/__init__.py#L73-L85
226,029
addisonlynch/iexfinance
iexfinance/__init__.py
get_iex_corporate_actions
def get_iex_corporate_actions(start=None, **kwargs): """ MOVED to iexfinance.refdata.get_iex_corporate_actions """ import warnings warnings.warn(WNG_MSG % ("get_iex_corporate_actions", "refdata.get_iex_corporate_actions")) return CorporateActions(start=start, **kwargs).fetch()
python
def get_iex_corporate_actions(start=None, **kwargs): import warnings warnings.warn(WNG_MSG % ("get_iex_corporate_actions", "refdata.get_iex_corporate_actions")) return CorporateActions(start=start, **kwargs).fetch()
[ "def", "get_iex_corporate_actions", "(", "start", "=", "None", ",", "*", "*", "kwargs", ")", ":", "import", "warnings", "warnings", ".", "warn", "(", "WNG_MSG", "%", "(", "\"get_iex_corporate_actions\"", ",", "\"refdata.get_iex_corporate_actions\"", ")", ")", "ret...
MOVED to iexfinance.refdata.get_iex_corporate_actions
[ "MOVED", "to", "iexfinance", ".", "refdata", ".", "get_iex_corporate_actions" ]
40f0bdcc51b329031d06178020fd774494250456
https://github.com/addisonlynch/iexfinance/blob/40f0bdcc51b329031d06178020fd774494250456/iexfinance/__init__.py#L88-L95
226,030
addisonlynch/iexfinance
iexfinance/__init__.py
get_iex_dividends
def get_iex_dividends(start=None, **kwargs): """ MOVED to iexfinance.refdata.get_iex_dividends """ import warnings warnings.warn(WNG_MSG % ("get_iex_dividends", "refdata.get_iex_dividends")) return Dividends(start=start, **kwargs).fetch()
python
def get_iex_dividends(start=None, **kwargs): import warnings warnings.warn(WNG_MSG % ("get_iex_dividends", "refdata.get_iex_dividends")) return Dividends(start=start, **kwargs).fetch()
[ "def", "get_iex_dividends", "(", "start", "=", "None", ",", "*", "*", "kwargs", ")", ":", "import", "warnings", "warnings", ".", "warn", "(", "WNG_MSG", "%", "(", "\"get_iex_dividends\"", ",", "\"refdata.get_iex_dividends\"", ")", ")", "return", "Dividends", "...
MOVED to iexfinance.refdata.get_iex_dividends
[ "MOVED", "to", "iexfinance", ".", "refdata", ".", "get_iex_dividends" ]
40f0bdcc51b329031d06178020fd774494250456
https://github.com/addisonlynch/iexfinance/blob/40f0bdcc51b329031d06178020fd774494250456/iexfinance/__init__.py#L98-L104
226,031
addisonlynch/iexfinance
iexfinance/__init__.py
get_iex_next_day_ex_date
def get_iex_next_day_ex_date(start=None, **kwargs): """ MOVED to iexfinance.refdata.get_iex_next_day_ex_date """ import warnings warnings.warn(WNG_MSG % ("get_iex_next_day_ex_date", "refdata.get_iex_next_day_ex_date")) return NextDay(start=start, **kwargs).fetch()
python
def get_iex_next_day_ex_date(start=None, **kwargs): import warnings warnings.warn(WNG_MSG % ("get_iex_next_day_ex_date", "refdata.get_iex_next_day_ex_date")) return NextDay(start=start, **kwargs).fetch()
[ "def", "get_iex_next_day_ex_date", "(", "start", "=", "None", ",", "*", "*", "kwargs", ")", ":", "import", "warnings", "warnings", ".", "warn", "(", "WNG_MSG", "%", "(", "\"get_iex_next_day_ex_date\"", ",", "\"refdata.get_iex_next_day_ex_date\"", ")", ")", "return...
MOVED to iexfinance.refdata.get_iex_next_day_ex_date
[ "MOVED", "to", "iexfinance", ".", "refdata", ".", "get_iex_next_day_ex_date" ]
40f0bdcc51b329031d06178020fd774494250456
https://github.com/addisonlynch/iexfinance/blob/40f0bdcc51b329031d06178020fd774494250456/iexfinance/__init__.py#L107-L114
226,032
addisonlynch/iexfinance
iexfinance/__init__.py
get_iex_listed_symbol_dir
def get_iex_listed_symbol_dir(start=None, **kwargs): """ MOVED to iexfinance.refdata.get_listed_symbol_dir """ import warnings warnings.warn(WNG_MSG % ("get_iex_listed_symbol_dir", "refdata.get_iex_listed_symbol_dir")) return ListedSymbolDir(start=start, **kwargs)
python
def get_iex_listed_symbol_dir(start=None, **kwargs): import warnings warnings.warn(WNG_MSG % ("get_iex_listed_symbol_dir", "refdata.get_iex_listed_symbol_dir")) return ListedSymbolDir(start=start, **kwargs)
[ "def", "get_iex_listed_symbol_dir", "(", "start", "=", "None", ",", "*", "*", "kwargs", ")", ":", "import", "warnings", "warnings", ".", "warn", "(", "WNG_MSG", "%", "(", "\"get_iex_listed_symbol_dir\"", ",", "\"refdata.get_iex_listed_symbol_dir\"", ")", ")", "ret...
MOVED to iexfinance.refdata.get_listed_symbol_dir
[ "MOVED", "to", "iexfinance", ".", "refdata", ".", "get_listed_symbol_dir" ]
40f0bdcc51b329031d06178020fd774494250456
https://github.com/addisonlynch/iexfinance/blob/40f0bdcc51b329031d06178020fd774494250456/iexfinance/__init__.py#L117-L124
226,033
addisonlynch/iexfinance
iexfinance/__init__.py
get_market_tops
def get_market_tops(symbols=None, **kwargs): """ MOVED to iexfinance.iexdata.get_tops """ import warnings warnings.warn(WNG_MSG % ("get_market_tops", "iexdata.get_tops")) return TOPS(symbols, **kwargs).fetch()
python
def get_market_tops(symbols=None, **kwargs): import warnings warnings.warn(WNG_MSG % ("get_market_tops", "iexdata.get_tops")) return TOPS(symbols, **kwargs).fetch()
[ "def", "get_market_tops", "(", "symbols", "=", "None", ",", "*", "*", "kwargs", ")", ":", "import", "warnings", "warnings", ".", "warn", "(", "WNG_MSG", "%", "(", "\"get_market_tops\"", ",", "\"iexdata.get_tops\"", ")", ")", "return", "TOPS", "(", "symbols",...
MOVED to iexfinance.iexdata.get_tops
[ "MOVED", "to", "iexfinance", ".", "iexdata", ".", "get_tops" ]
40f0bdcc51b329031d06178020fd774494250456
https://github.com/addisonlynch/iexfinance/blob/40f0bdcc51b329031d06178020fd774494250456/iexfinance/__init__.py#L127-L133
226,034
addisonlynch/iexfinance
iexfinance/__init__.py
get_market_last
def get_market_last(symbols=None, **kwargs): """ MOVED to iexfinance.iexdata.get_last """ import warnings warnings.warn(WNG_MSG % ("get_market_last", "iexdata.get_last")) return Last(symbols, **kwargs).fetch()
python
def get_market_last(symbols=None, **kwargs): import warnings warnings.warn(WNG_MSG % ("get_market_last", "iexdata.get_last")) return Last(symbols, **kwargs).fetch()
[ "def", "get_market_last", "(", "symbols", "=", "None", ",", "*", "*", "kwargs", ")", ":", "import", "warnings", "warnings", ".", "warn", "(", "WNG_MSG", "%", "(", "\"get_market_last\"", ",", "\"iexdata.get_last\"", ")", ")", "return", "Last", "(", "symbols",...
MOVED to iexfinance.iexdata.get_last
[ "MOVED", "to", "iexfinance", ".", "iexdata", ".", "get_last" ]
40f0bdcc51b329031d06178020fd774494250456
https://github.com/addisonlynch/iexfinance/blob/40f0bdcc51b329031d06178020fd774494250456/iexfinance/__init__.py#L136-L142
226,035
addisonlynch/iexfinance
iexfinance/__init__.py
get_market_deep
def get_market_deep(symbols=None, **kwargs): """ MOVED to iexfinance.iexdata.get_deep """ import warnings warnings.warn(WNG_MSG % ("get_market_deep", "iexdata.get_deep")) return DEEP(symbols, **kwargs).fetch()
python
def get_market_deep(symbols=None, **kwargs): import warnings warnings.warn(WNG_MSG % ("get_market_deep", "iexdata.get_deep")) return DEEP(symbols, **kwargs).fetch()
[ "def", "get_market_deep", "(", "symbols", "=", "None", ",", "*", "*", "kwargs", ")", ":", "import", "warnings", "warnings", ".", "warn", "(", "WNG_MSG", "%", "(", "\"get_market_deep\"", ",", "\"iexdata.get_deep\"", ")", ")", "return", "DEEP", "(", "symbols",...
MOVED to iexfinance.iexdata.get_deep
[ "MOVED", "to", "iexfinance", ".", "iexdata", ".", "get_deep" ]
40f0bdcc51b329031d06178020fd774494250456
https://github.com/addisonlynch/iexfinance/blob/40f0bdcc51b329031d06178020fd774494250456/iexfinance/__init__.py#L145-L151
226,036
addisonlynch/iexfinance
iexfinance/__init__.py
get_market_book
def get_market_book(symbols=None, **kwargs): """ MOVED to iexfinance.iexdata.get_deep_book """ import warnings warnings.warn(WNG_MSG % ("get_market_book", "iexdata.get_deep_book")) return Book(symbols, **kwargs).fetch()
python
def get_market_book(symbols=None, **kwargs): import warnings warnings.warn(WNG_MSG % ("get_market_book", "iexdata.get_deep_book")) return Book(symbols, **kwargs).fetch()
[ "def", "get_market_book", "(", "symbols", "=", "None", ",", "*", "*", "kwargs", ")", ":", "import", "warnings", "warnings", ".", "warn", "(", "WNG_MSG", "%", "(", "\"get_market_book\"", ",", "\"iexdata.get_deep_book\"", ")", ")", "return", "Book", "(", "symb...
MOVED to iexfinance.iexdata.get_deep_book
[ "MOVED", "to", "iexfinance", ".", "iexdata", ".", "get_deep_book" ]
40f0bdcc51b329031d06178020fd774494250456
https://github.com/addisonlynch/iexfinance/blob/40f0bdcc51b329031d06178020fd774494250456/iexfinance/__init__.py#L154-L160
226,037
addisonlynch/iexfinance
iexfinance/__init__.py
get_stats_daily
def get_stats_daily(start=None, end=None, last=None, **kwargs): """ MOVED to iexfinance.iexdata.get_stats_daily """ import warnings warnings.warn(WNG_MSG % ("get_stats_daily", "iexdata.get_stats_daily")) start, end = _sanitize_dates(start, end) return DailySummaryReader(start=start, end=end, last=last, **kwargs).fetch()
python
def get_stats_daily(start=None, end=None, last=None, **kwargs): import warnings warnings.warn(WNG_MSG % ("get_stats_daily", "iexdata.get_stats_daily")) start, end = _sanitize_dates(start, end) return DailySummaryReader(start=start, end=end, last=last, **kwargs).fetch()
[ "def", "get_stats_daily", "(", "start", "=", "None", ",", "end", "=", "None", ",", "last", "=", "None", ",", "*", "*", "kwargs", ")", ":", "import", "warnings", "warnings", ".", "warn", "(", "WNG_MSG", "%", "(", "\"get_stats_daily\"", ",", "\"iexdata.get...
MOVED to iexfinance.iexdata.get_stats_daily
[ "MOVED", "to", "iexfinance", ".", "iexdata", ".", "get_stats_daily" ]
40f0bdcc51b329031d06178020fd774494250456
https://github.com/addisonlynch/iexfinance/blob/40f0bdcc51b329031d06178020fd774494250456/iexfinance/__init__.py#L191-L199
226,038
addisonlynch/iexfinance
iexfinance/__init__.py
get_stats_monthly
def get_stats_monthly(start=None, end=None, **kwargs): """ MOVED to iexfinance.iexdata.get_stats_summary """ import warnings warnings.warn(WNG_MSG % ("get_stats_monthly", "iexdata.get_stats_summary")) return MonthlySummaryReader(start=start, end=end, **kwargs).fetch()
python
def get_stats_monthly(start=None, end=None, **kwargs): import warnings warnings.warn(WNG_MSG % ("get_stats_monthly", "iexdata.get_stats_summary")) return MonthlySummaryReader(start=start, end=end, **kwargs).fetch()
[ "def", "get_stats_monthly", "(", "start", "=", "None", ",", "end", "=", "None", ",", "*", "*", "kwargs", ")", ":", "import", "warnings", "warnings", ".", "warn", "(", "WNG_MSG", "%", "(", "\"get_stats_monthly\"", ",", "\"iexdata.get_stats_summary\"", ")", ")...
MOVED to iexfinance.iexdata.get_stats_summary
[ "MOVED", "to", "iexfinance", ".", "iexdata", ".", "get_stats_summary" ]
40f0bdcc51b329031d06178020fd774494250456
https://github.com/addisonlynch/iexfinance/blob/40f0bdcc51b329031d06178020fd774494250456/iexfinance/__init__.py#L202-L208
226,039
addisonlynch/iexfinance
iexfinance/base.py
_IEXBase._handle_error
def _handle_error(self, response): """ Handles all responses which return an error status code """ auth_msg = "The query could not be completed. Invalid auth token." status_code = response.status_code if 400 <= status_code < 500: if status_code == 400: raise auth_error(auth_msg) else: raise auth_error("The query could not be completed. " "There was a client-side error with your " "request.") elif 500 <= status_code < 600: raise auth_error("The query could not be completed. " "There was a server-side error with " "your request.") else: raise auth_error("The query could not be completed.")
python
def _handle_error(self, response): auth_msg = "The query could not be completed. Invalid auth token." status_code = response.status_code if 400 <= status_code < 500: if status_code == 400: raise auth_error(auth_msg) else: raise auth_error("The query could not be completed. " "There was a client-side error with your " "request.") elif 500 <= status_code < 600: raise auth_error("The query could not be completed. " "There was a server-side error with " "your request.") else: raise auth_error("The query could not be completed.")
[ "def", "_handle_error", "(", "self", ",", "response", ")", ":", "auth_msg", "=", "\"The query could not be completed. Invalid auth token.\"", "status_code", "=", "response", ".", "status_code", "if", "400", "<=", "status_code", "<", "500", ":", "if", "status_code", ...
Handles all responses which return an error status code
[ "Handles", "all", "responses", "which", "return", "an", "error", "status", "code" ]
40f0bdcc51b329031d06178020fd774494250456
https://github.com/addisonlynch/iexfinance/blob/40f0bdcc51b329031d06178020fd774494250456/iexfinance/base.py#L149-L168
226,040
addisonlynch/iexfinance
iexfinance/base.py
_IEXBase._output_format
def _output_format(self, out, fmt_j=None, fmt_p=None): """ Output formatting handler """ if self.output_format == 'pandas': if fmt_p is not None: return fmt_p(out) else: return self._convert_output(out) if fmt_j: return fmt_j(out) return out
python
def _output_format(self, out, fmt_j=None, fmt_p=None): if self.output_format == 'pandas': if fmt_p is not None: return fmt_p(out) else: return self._convert_output(out) if fmt_j: return fmt_j(out) return out
[ "def", "_output_format", "(", "self", ",", "out", ",", "fmt_j", "=", "None", ",", "fmt_p", "=", "None", ")", ":", "if", "self", ".", "output_format", "==", "'pandas'", ":", "if", "fmt_p", "is", "not", "None", ":", "return", "fmt_p", "(", "out", ")", ...
Output formatting handler
[ "Output", "formatting", "handler" ]
40f0bdcc51b329031d06178020fd774494250456
https://github.com/addisonlynch/iexfinance/blob/40f0bdcc51b329031d06178020fd774494250456/iexfinance/base.py#L198-L209
226,041
addisonlynch/iexfinance
iexfinance/stocks/__init__.py
get_historical_data
def get_historical_data(symbols, start=None, end=None, **kwargs): """ Function to obtain historical date for a symbol or list of symbols. Return an instance of HistoricalReader Parameters ---------- symbols: str or list A symbol or list of symbols start: datetime.datetime, default None Beginning of desired date range end: datetime.datetime, default None End of required date range kwargs: Additional Request Parameters (see base class) Returns ------- list or DataFrame Historical stock prices over date range, start to end """ start, end = _sanitize_dates(start, end) return HistoricalReader(symbols, start=start, end=end, **kwargs).fetch()
python
def get_historical_data(symbols, start=None, end=None, **kwargs): start, end = _sanitize_dates(start, end) return HistoricalReader(symbols, start=start, end=end, **kwargs).fetch()
[ "def", "get_historical_data", "(", "symbols", ",", "start", "=", "None", ",", "end", "=", "None", ",", "*", "*", "kwargs", ")", ":", "start", ",", "end", "=", "_sanitize_dates", "(", "start", ",", "end", ")", "return", "HistoricalReader", "(", "symbols",...
Function to obtain historical date for a symbol or list of symbols. Return an instance of HistoricalReader Parameters ---------- symbols: str or list A symbol or list of symbols start: datetime.datetime, default None Beginning of desired date range end: datetime.datetime, default None End of required date range kwargs: Additional Request Parameters (see base class) Returns ------- list or DataFrame Historical stock prices over date range, start to end
[ "Function", "to", "obtain", "historical", "date", "for", "a", "symbol", "or", "list", "of", "symbols", ".", "Return", "an", "instance", "of", "HistoricalReader" ]
40f0bdcc51b329031d06178020fd774494250456
https://github.com/addisonlynch/iexfinance/blob/40f0bdcc51b329031d06178020fd774494250456/iexfinance/stocks/__init__.py#L17-L39
226,042
sunscrapers/djoser
djoser/conf.py
LazySettings.get
def get(self, key): """ This function is here only to provide backwards compatibility in case anyone uses old settings interface. It is strongly encouraged to use dot notation. """ warnings.warn( 'The settings.get(key) is superseded by the dot attribute access.', PendingDeprecationWarning ) try: return getattr(self, key) except AttributeError: raise ImproperlyConfigured('Missing settings: {}[\'{}\']'.format( DJOSER_SETTINGS_NAMESPACE, key) )
python
def get(self, key): warnings.warn( 'The settings.get(key) is superseded by the dot attribute access.', PendingDeprecationWarning ) try: return getattr(self, key) except AttributeError: raise ImproperlyConfigured('Missing settings: {}[\'{}\']'.format( DJOSER_SETTINGS_NAMESPACE, key) )
[ "def", "get", "(", "self", ",", "key", ")", ":", "warnings", ".", "warn", "(", "'The settings.get(key) is superseded by the dot attribute access.'", ",", "PendingDeprecationWarning", ")", "try", ":", "return", "getattr", "(", "self", ",", "key", ")", "except", "At...
This function is here only to provide backwards compatibility in case anyone uses old settings interface. It is strongly encouraged to use dot notation.
[ "This", "function", "is", "here", "only", "to", "provide", "backwards", "compatibility", "in", "case", "anyone", "uses", "old", "settings", "interface", ".", "It", "is", "strongly", "encouraged", "to", "use", "dot", "notation", "." ]
91053fe54b4b65c3b546aa86e358c74446f3a5f7
https://github.com/sunscrapers/djoser/blob/91053fe54b4b65c3b546aa86e358c74446f3a5f7/djoser/conf.py#L132-L147
226,043
acrisci/i3ipc-python
i3ipc/i3ipc.py
Connection._pack
def _pack(self, msg_type, payload): """ Packs the given message type and payload. Turns the resulting message into a byte string. """ pb = payload.encode('utf-8') s = struct.pack('=II', len(pb), msg_type.value) return self.MAGIC.encode('utf-8') + s + pb
python
def _pack(self, msg_type, payload): pb = payload.encode('utf-8') s = struct.pack('=II', len(pb), msg_type.value) return self.MAGIC.encode('utf-8') + s + pb
[ "def", "_pack", "(", "self", ",", "msg_type", ",", "payload", ")", ":", "pb", "=", "payload", ".", "encode", "(", "'utf-8'", ")", "s", "=", "struct", ".", "pack", "(", "'=II'", ",", "len", "(", "pb", ")", ",", "msg_type", ".", "value", ")", "retu...
Packs the given message type and payload. Turns the resulting message into a byte string.
[ "Packs", "the", "given", "message", "type", "and", "payload", ".", "Turns", "the", "resulting", "message", "into", "a", "byte", "string", "." ]
243d353434cdd2a93a9ca917c6bbf07b865c39af
https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L401-L408
226,044
acrisci/i3ipc-python
i3ipc/i3ipc.py
Connection._unpack
def _unpack(self, data): """ Unpacks the given byte string and parses the result from JSON. Returns None on failure and saves data into "self.buffer". """ msg_magic, msg_length, msg_type = self._unpack_header(data) msg_size = self._struct_header_size + msg_length # XXX: Message shouldn't be any longer than the data payload = data[self._struct_header_size:msg_size] return payload.decode('utf-8', 'replace')
python
def _unpack(self, data): msg_magic, msg_length, msg_type = self._unpack_header(data) msg_size = self._struct_header_size + msg_length # XXX: Message shouldn't be any longer than the data payload = data[self._struct_header_size:msg_size] return payload.decode('utf-8', 'replace')
[ "def", "_unpack", "(", "self", ",", "data", ")", ":", "msg_magic", ",", "msg_length", ",", "msg_type", "=", "self", ".", "_unpack_header", "(", "data", ")", "msg_size", "=", "self", ".", "_struct_header_size", "+", "msg_length", "# XXX: Message shouldn't be any ...
Unpacks the given byte string and parses the result from JSON. Returns None on failure and saves data into "self.buffer".
[ "Unpacks", "the", "given", "byte", "string", "and", "parses", "the", "result", "from", "JSON", ".", "Returns", "None", "on", "failure", "and", "saves", "data", "into", "self", ".", "buffer", "." ]
243d353434cdd2a93a9ca917c6bbf07b865c39af
https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L410-L419
226,045
acrisci/i3ipc-python
i3ipc/i3ipc.py
Connection._unpack_header
def _unpack_header(self, data): """ Unpacks the header of given byte string. """ return struct.unpack(self._struct_header, data[:self._struct_header_size])
python
def _unpack_header(self, data): return struct.unpack(self._struct_header, data[:self._struct_header_size])
[ "def", "_unpack_header", "(", "self", ",", "data", ")", ":", "return", "struct", ".", "unpack", "(", "self", ".", "_struct_header", ",", "data", "[", ":", "self", ".", "_struct_header_size", "]", ")" ]
Unpacks the header of given byte string.
[ "Unpacks", "the", "header", "of", "given", "byte", "string", "." ]
243d353434cdd2a93a9ca917c6bbf07b865c39af
https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L421-L426
226,046
acrisci/i3ipc-python
i3ipc/i3ipc.py
Connection.get_bar_config_list
def get_bar_config_list(self): """ Get list of bar IDs as active in the connected i3 session. :rtype: List of strings that can be fed as ``bar_id`` into :meth:`get_bar_config`. """ data = self.message(MessageType.GET_BAR_CONFIG, '') return json.loads(data)
python
def get_bar_config_list(self): data = self.message(MessageType.GET_BAR_CONFIG, '') return json.loads(data)
[ "def", "get_bar_config_list", "(", "self", ")", ":", "data", "=", "self", ".", "message", "(", "MessageType", ".", "GET_BAR_CONFIG", ",", "''", ")", "return", "json", ".", "loads", "(", "data", ")" ]
Get list of bar IDs as active in the connected i3 session. :rtype: List of strings that can be fed as ``bar_id`` into :meth:`get_bar_config`.
[ "Get", "list", "of", "bar", "IDs", "as", "active", "in", "the", "connected", "i3", "session", "." ]
243d353434cdd2a93a9ca917c6bbf07b865c39af
https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L551-L559
226,047
acrisci/i3ipc-python
i3ipc/i3ipc.py
Connection.get_workspaces
def get_workspaces(self): """ Get a list of workspaces. Returns JSON-like data, not a Con instance. You might want to try the :meth:`Con.workspaces` instead if the info contained here is too little. :rtype: List of :class:`WorkspaceReply`. """ data = self.message(MessageType.GET_WORKSPACES, '') return json.loads(data, object_hook=WorkspaceReply)
python
def get_workspaces(self): data = self.message(MessageType.GET_WORKSPACES, '') return json.loads(data, object_hook=WorkspaceReply)
[ "def", "get_workspaces", "(", "self", ")", ":", "data", "=", "self", ".", "message", "(", "MessageType", ".", "GET_WORKSPACES", ",", "''", ")", "return", "json", ".", "loads", "(", "data", ",", "object_hook", "=", "WorkspaceReply", ")" ]
Get a list of workspaces. Returns JSON-like data, not a Con instance. You might want to try the :meth:`Con.workspaces` instead if the info contained here is too little. :rtype: List of :class:`WorkspaceReply`.
[ "Get", "a", "list", "of", "workspaces", ".", "Returns", "JSON", "-", "like", "data", "not", "a", "Con", "instance", "." ]
243d353434cdd2a93a9ca917c6bbf07b865c39af
https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L586-L597
226,048
acrisci/i3ipc-python
i3ipc/i3ipc.py
Connection.get_marks
def get_marks(self): """ Get a list of the names of all currently set marks. :rtype: list """ data = self.message(MessageType.GET_MARKS, '') return json.loads(data)
python
def get_marks(self): data = self.message(MessageType.GET_MARKS, '') return json.loads(data)
[ "def", "get_marks", "(", "self", ")", ":", "data", "=", "self", ".", "message", "(", "MessageType", ".", "GET_MARKS", ",", "''", ")", "return", "json", ".", "loads", "(", "data", ")" ]
Get a list of the names of all currently set marks. :rtype: list
[ "Get", "a", "list", "of", "the", "names", "of", "all", "currently", "set", "marks", "." ]
243d353434cdd2a93a9ca917c6bbf07b865c39af
https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L609-L616
226,049
acrisci/i3ipc-python
i3ipc/i3ipc.py
Connection.get_binding_modes
def get_binding_modes(self): """ Returns all currently configured binding modes. :rtype: list """ data = self.message(MessageType.GET_BINDING_MODES, '') return json.loads(data)
python
def get_binding_modes(self): data = self.message(MessageType.GET_BINDING_MODES, '') return json.loads(data)
[ "def", "get_binding_modes", "(", "self", ")", ":", "data", "=", "self", ".", "message", "(", "MessageType", ".", "GET_BINDING_MODES", ",", "''", ")", "return", "json", ".", "loads", "(", "data", ")" ]
Returns all currently configured binding modes. :rtype: list
[ "Returns", "all", "currently", "configured", "binding", "modes", "." ]
243d353434cdd2a93a9ca917c6bbf07b865c39af
https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L618-L625
226,050
acrisci/i3ipc-python
i3ipc/i3ipc.py
Connection.get_config
def get_config(self): """ Currently only contains the "config" member, which is a string containing the config file as loaded by i3 most recently. :rtype: ConfigReply """ data = self.message(MessageType.GET_CONFIG, '') return json.loads(data, object_hook=ConfigReply)
python
def get_config(self): data = self.message(MessageType.GET_CONFIG, '') return json.loads(data, object_hook=ConfigReply)
[ "def", "get_config", "(", "self", ")", ":", "data", "=", "self", ".", "message", "(", "MessageType", ".", "GET_CONFIG", ",", "''", ")", "return", "json", ".", "loads", "(", "data", ",", "object_hook", "=", "ConfigReply", ")" ]
Currently only contains the "config" member, which is a string containing the config file as loaded by i3 most recently. :rtype: ConfigReply
[ "Currently", "only", "contains", "the", "config", "member", "which", "is", "a", "string", "containing", "the", "config", "file", "as", "loaded", "by", "i3", "most", "recently", "." ]
243d353434cdd2a93a9ca917c6bbf07b865c39af
https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L627-L635
226,051
acrisci/i3ipc-python
i3ipc/i3ipc.py
Connection.send_tick
def send_tick(self, payload=""): """ Sends a tick event with the specified payload. After the reply was received, the tick event has been written to all IPC connections which subscribe to tick events. :rtype: TickReply """ data = self.message(MessageType.SEND_TICK, payload) return json.loads(data, object_hook=TickReply)
python
def send_tick(self, payload=""): data = self.message(MessageType.SEND_TICK, payload) return json.loads(data, object_hook=TickReply)
[ "def", "send_tick", "(", "self", ",", "payload", "=", "\"\"", ")", ":", "data", "=", "self", ".", "message", "(", "MessageType", ".", "SEND_TICK", ",", "payload", ")", "return", "json", ".", "loads", "(", "data", ",", "object_hook", "=", "TickReply", "...
Sends a tick event with the specified payload. After the reply was received, the tick event has been written to all IPC connections which subscribe to tick events. :rtype: TickReply
[ "Sends", "a", "tick", "event", "with", "the", "specified", "payload", ".", "After", "the", "reply", "was", "received", "the", "tick", "event", "has", "been", "written", "to", "all", "IPC", "connections", "which", "subscribe", "to", "tick", "events", "." ]
243d353434cdd2a93a9ca917c6bbf07b865c39af
https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L637-L646
226,052
acrisci/i3ipc-python
i3ipc/i3ipc.py
Con.root
def root(self): """ Retrieves the root container. :rtype: :class:`Con`. """ if not self.parent: return self con = self.parent while con.parent: con = con.parent return con
python
def root(self): if not self.parent: return self con = self.parent while con.parent: con = con.parent return con
[ "def", "root", "(", "self", ")", ":", "if", "not", "self", ".", "parent", ":", "return", "self", "con", "=", "self", ".", "parent", "while", "con", ".", "parent", ":", "con", "=", "con", ".", "parent", "return", "con" ]
Retrieves the root container. :rtype: :class:`Con`.
[ "Retrieves", "the", "root", "container", "." ]
243d353434cdd2a93a9ca917c6bbf07b865c39af
https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L1074-L1089
226,053
acrisci/i3ipc-python
i3ipc/i3ipc.py
Con.leaves
def leaves(self): """ Retrieve a list of windows that delineate from the currently selected container. Only lists client windows, no intermediate containers. :rtype: List of :class:`Con`. """ leaves = [] for c in self: if not c.nodes and c.type == "con" and c.parent.type != "dockarea": leaves.append(c) return leaves
python
def leaves(self): leaves = [] for c in self: if not c.nodes and c.type == "con" and c.parent.type != "dockarea": leaves.append(c) return leaves
[ "def", "leaves", "(", "self", ")", ":", "leaves", "=", "[", "]", "for", "c", "in", "self", ":", "if", "not", "c", ".", "nodes", "and", "c", ".", "type", "==", "\"con\"", "and", "c", ".", "parent", ".", "type", "!=", "\"dockarea\"", ":", "leaves",...
Retrieve a list of windows that delineate from the currently selected container. Only lists client windows, no intermediate containers. :rtype: List of :class:`Con`.
[ "Retrieve", "a", "list", "of", "windows", "that", "delineate", "from", "the", "currently", "selected", "container", ".", "Only", "lists", "client", "windows", "no", "intermediate", "containers", "." ]
243d353434cdd2a93a9ca917c6bbf07b865c39af
https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L1100-L1114
226,054
acrisci/i3ipc-python
i3ipc/i3ipc.py
Con.command
def command(self, command): """ Run a command on the currently active container. :rtype: CommandReply """ return self._conn.command('[con_id="{}"] {}'.format(self.id, command))
python
def command(self, command): return self._conn.command('[con_id="{}"] {}'.format(self.id, command))
[ "def", "command", "(", "self", ",", "command", ")", ":", "return", "self", ".", "_conn", ".", "command", "(", "'[con_id=\"{}\"] {}'", ".", "format", "(", "self", ".", "id", ",", "command", ")", ")" ]
Run a command on the currently active container. :rtype: CommandReply
[ "Run", "a", "command", "on", "the", "currently", "active", "container", "." ]
243d353434cdd2a93a9ca917c6bbf07b865c39af
https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L1116-L1122
226,055
acrisci/i3ipc-python
i3ipc/i3ipc.py
Con.command_children
def command_children(self, command): """ Run a command on the direct children of the currently selected container. :rtype: List of CommandReply???? """ if not len(self.nodes): return commands = [] for c in self.nodes: commands.append('[con_id="{}"] {};'.format(c.id, command)) self._conn.command(' '.join(commands))
python
def command_children(self, command): if not len(self.nodes): return commands = [] for c in self.nodes: commands.append('[con_id="{}"] {};'.format(c.id, command)) self._conn.command(' '.join(commands))
[ "def", "command_children", "(", "self", ",", "command", ")", ":", "if", "not", "len", "(", "self", ".", "nodes", ")", ":", "return", "commands", "=", "[", "]", "for", "c", "in", "self", ".", "nodes", ":", "commands", ".", "append", "(", "'[con_id=\"{...
Run a command on the direct children of the currently selected container. :rtype: List of CommandReply????
[ "Run", "a", "command", "on", "the", "direct", "children", "of", "the", "currently", "selected", "container", "." ]
243d353434cdd2a93a9ca917c6bbf07b865c39af
https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L1124-L1138
226,056
acrisci/i3ipc-python
i3ipc/i3ipc.py
Con.workspaces
def workspaces(self): """ Retrieve a list of currently active workspaces. :rtype: List of :class:`Con`. """ workspaces = [] def collect_workspaces(con): if con.type == "workspace" and not con.name.startswith('__'): workspaces.append(con) return for c in con.nodes: collect_workspaces(c) collect_workspaces(self.root()) return workspaces
python
def workspaces(self): workspaces = [] def collect_workspaces(con): if con.type == "workspace" and not con.name.startswith('__'): workspaces.append(con) return for c in con.nodes: collect_workspaces(c) collect_workspaces(self.root()) return workspaces
[ "def", "workspaces", "(", "self", ")", ":", "workspaces", "=", "[", "]", "def", "collect_workspaces", "(", "con", ")", ":", "if", "con", ".", "type", "==", "\"workspace\"", "and", "not", "con", ".", "name", ".", "startswith", "(", "'__'", ")", ":", "...
Retrieve a list of currently active workspaces. :rtype: List of :class:`Con`.
[ "Retrieve", "a", "list", "of", "currently", "active", "workspaces", "." ]
243d353434cdd2a93a9ca917c6bbf07b865c39af
https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L1140-L1157
226,057
michaelliao/sinaweibopy
snspy.py
_parse_json
def _parse_json(s): ''' Parse json string into JsonDict. >>> r = _parse_json(r'{"name":"Michael","score":95}') >>> r.name u'Michael' >>> r['score'] 95 ''' return json.loads(s, object_hook=lambda pairs: JsonDict(pairs.iteritems()))
python
def _parse_json(s): ''' Parse json string into JsonDict. >>> r = _parse_json(r'{"name":"Michael","score":95}') >>> r.name u'Michael' >>> r['score'] 95 ''' return json.loads(s, object_hook=lambda pairs: JsonDict(pairs.iteritems()))
[ "def", "_parse_json", "(", "s", ")", ":", "return", "json", ".", "loads", "(", "s", ",", "object_hook", "=", "lambda", "pairs", ":", "JsonDict", "(", "pairs", ".", "iteritems", "(", ")", ")", ")" ]
Parse json string into JsonDict. >>> r = _parse_json(r'{"name":"Michael","score":95}') >>> r.name u'Michael' >>> r['score'] 95
[ "Parse", "json", "string", "into", "JsonDict", "." ]
0f19dd71c1fbd16ee539620c7e9e986887f5c665
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/snspy.py#L77-L87
226,058
michaelliao/sinaweibopy
snspy.py
_encode_params
def _encode_params(**kw): ''' Do url-encode parameters >>> _encode_params(a=1, b='R&D') 'a=1&b=R%26D' >>> _encode_params(a=u'\u4e2d\u6587', b=['A', 'B', 123]) 'a=%E4%B8%AD%E6%96%87&b=A&b=B&b=123' ''' def _encode(L, k, v): if isinstance(v, unicode): L.append('%s=%s' % (k, urllib.quote(v.encode('utf-8')))) elif isinstance(v, str): L.append('%s=%s' % (k, urllib.quote(v))) elif isinstance(v, collections.Iterable): for x in v: _encode(L, k, x) else: L.append('%s=%s' % (k, urllib.quote(str(v)))) args = [] for k, v in kw.iteritems(): _encode(args, k, v) return '&'.join(args)
python
def _encode_params(**kw): ''' Do url-encode parameters >>> _encode_params(a=1, b='R&D') 'a=1&b=R%26D' >>> _encode_params(a=u'\u4e2d\u6587', b=['A', 'B', 123]) 'a=%E4%B8%AD%E6%96%87&b=A&b=B&b=123' ''' def _encode(L, k, v): if isinstance(v, unicode): L.append('%s=%s' % (k, urllib.quote(v.encode('utf-8')))) elif isinstance(v, str): L.append('%s=%s' % (k, urllib.quote(v))) elif isinstance(v, collections.Iterable): for x in v: _encode(L, k, x) else: L.append('%s=%s' % (k, urllib.quote(str(v)))) args = [] for k, v in kw.iteritems(): _encode(args, k, v) return '&'.join(args)
[ "def", "_encode_params", "(", "*", "*", "kw", ")", ":", "def", "_encode", "(", "L", ",", "k", ",", "v", ")", ":", "if", "isinstance", "(", "v", ",", "unicode", ")", ":", "L", ".", "append", "(", "'%s=%s'", "%", "(", "k", ",", "urllib", ".", "...
Do url-encode parameters >>> _encode_params(a=1, b='R&D') 'a=1&b=R%26D' >>> _encode_params(a=u'\u4e2d\u6587', b=['A', 'B', 123]) 'a=%E4%B8%AD%E6%96%87&b=A&b=B&b=123'
[ "Do", "url", "-", "encode", "parameters" ]
0f19dd71c1fbd16ee539620c7e9e986887f5c665
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/snspy.py#L90-L112
226,059
michaelliao/sinaweibopy
snspy.py
_guess_content_type
def _guess_content_type(url): ''' Guess content type by url. >>> _guess_content_type('http://test/A.HTML') 'text/html' >>> _guess_content_type('http://test/a.jpg') 'image/jpeg' >>> _guess_content_type('/path.txt/aaa') 'application/octet-stream' ''' OCTET_STREAM = 'application/octet-stream' n = url.rfind('.') if n == -1: return OCTET_STREAM return mimetypes.types_map.get(url[n:].lower(), OCTET_STREAM)
python
def _guess_content_type(url): ''' Guess content type by url. >>> _guess_content_type('http://test/A.HTML') 'text/html' >>> _guess_content_type('http://test/a.jpg') 'image/jpeg' >>> _guess_content_type('/path.txt/aaa') 'application/octet-stream' ''' OCTET_STREAM = 'application/octet-stream' n = url.rfind('.') if n == -1: return OCTET_STREAM return mimetypes.types_map.get(url[n:].lower(), OCTET_STREAM)
[ "def", "_guess_content_type", "(", "url", ")", ":", "OCTET_STREAM", "=", "'application/octet-stream'", "n", "=", "url", ".", "rfind", "(", "'.'", ")", "if", "n", "==", "-", "1", ":", "return", "OCTET_STREAM", "return", "mimetypes", ".", "types_map", ".", "...
Guess content type by url. >>> _guess_content_type('http://test/A.HTML') 'text/html' >>> _guess_content_type('http://test/a.jpg') 'image/jpeg' >>> _guess_content_type('/path.txt/aaa') 'application/octet-stream'
[ "Guess", "content", "type", "by", "url", "." ]
0f19dd71c1fbd16ee539620c7e9e986887f5c665
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/snspy.py#L136-L151
226,060
michaelliao/sinaweibopy
snspy.py
_http
def _http(method, url, headers=None, **kw): ''' Send http request and return response text. ''' params = None boundary = None if method == 'UPLOAD': params, boundary = _encode_multipart(**kw) else: params = _encode_params(**kw) http_url = '%s?%s' % (url, params) if method == _HTTP_GET else url http_body = None if method == 'GET' else params logging.error('%s: %s' % (method, http_url)) req = urllib2.Request(http_url, data=http_body) req.add_header('Accept-Encoding', 'gzip') if headers: for k, v in headers.iteritems(): req.add_header(k, v) if boundary: req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary) try: resp = urllib2.urlopen(req, timeout=5) return _read_http_body(resp) finally: pass
python
def _http(method, url, headers=None, **kw): ''' Send http request and return response text. ''' params = None boundary = None if method == 'UPLOAD': params, boundary = _encode_multipart(**kw) else: params = _encode_params(**kw) http_url = '%s?%s' % (url, params) if method == _HTTP_GET else url http_body = None if method == 'GET' else params logging.error('%s: %s' % (method, http_url)) req = urllib2.Request(http_url, data=http_body) req.add_header('Accept-Encoding', 'gzip') if headers: for k, v in headers.iteritems(): req.add_header(k, v) if boundary: req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary) try: resp = urllib2.urlopen(req, timeout=5) return _read_http_body(resp) finally: pass
[ "def", "_http", "(", "method", ",", "url", ",", "headers", "=", "None", ",", "*", "*", "kw", ")", ":", "params", "=", "None", "boundary", "=", "None", "if", "method", "==", "'UPLOAD'", ":", "params", ",", "boundary", "=", "_encode_multipart", "(", "*...
Send http request and return response text.
[ "Send", "http", "request", "and", "return", "response", "text", "." ]
0f19dd71c1fbd16ee539620c7e9e986887f5c665
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/snspy.py#L169-L193
226,061
michaelliao/sinaweibopy
snspy.py
SinaWeiboMixin._prepare_api
def _prepare_api(self, method, path, access_token, **kw): ''' Get api url. ''' headers = None if access_token: headers = {'Authorization': 'OAuth2 %s' % access_token} if '/remind/' in path: # sina remind api url is different: return method, 'https://rm.api.weibo.com/2/%s.json' % path, headers, kw if method == 'POST' and 'pic' in kw: # if 'pic' in parameter, set to UPLOAD mode: return 'UPLOAD', 'https://api.weibo.com/2/%s.json' % path, headers, kw return method, 'https://api.weibo.com/2/%s.json' % path, headers, kw
python
def _prepare_api(self, method, path, access_token, **kw): ''' Get api url. ''' headers = None if access_token: headers = {'Authorization': 'OAuth2 %s' % access_token} if '/remind/' in path: # sina remind api url is different: return method, 'https://rm.api.weibo.com/2/%s.json' % path, headers, kw if method == 'POST' and 'pic' in kw: # if 'pic' in parameter, set to UPLOAD mode: return 'UPLOAD', 'https://api.weibo.com/2/%s.json' % path, headers, kw return method, 'https://api.weibo.com/2/%s.json' % path, headers, kw
[ "def", "_prepare_api", "(", "self", ",", "method", ",", "path", ",", "access_token", ",", "*", "*", "kw", ")", ":", "headers", "=", "None", "if", "access_token", ":", "headers", "=", "{", "'Authorization'", ":", "'OAuth2 %s'", "%", "access_token", "}", "...
Get api url.
[ "Get", "api", "url", "." ]
0f19dd71c1fbd16ee539620c7e9e986887f5c665
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/snspy.py#L231-L244
226,062
michaelliao/sinaweibopy
snspy.py
SinaWeiboMixin.parse_signed_request
def parse_signed_request(self, signed_request): ''' parse signed request when using in-site app. Returns: dict object like { 'uid': 12345, 'access_token': 'ABC123XYZ', 'expires': unix-timestamp }, or None if parse failed. ''' def _b64_normalize(s): appendix = '=' * (4 - len(s) % 4) return s.replace('-', '+').replace('_', '/') + appendix sr = str(signed_request) logging.info('parse signed request: %s' % sr) enc_sig, enc_payload = sr.split('.', 1) sig = base64.b64decode(_b64_normalize(enc_sig)) data = _parse_json(base64.b64decode(_b64_normalize(enc_payload))) if data['algorithm'] != u'HMAC-SHA256': return None expected_sig = hmac.new(self.client_secret, enc_payload, hashlib.sha256).digest() if expected_sig == sig: data.user_id = data.uid = data.get('user_id', None) data.access_token = data.get('oauth_token', None) expires = data.get('expires', None) if expires: data.expires = data.expires_in = time.time() + expires return data return None
python
def parse_signed_request(self, signed_request): ''' parse signed request when using in-site app. Returns: dict object like { 'uid': 12345, 'access_token': 'ABC123XYZ', 'expires': unix-timestamp }, or None if parse failed. ''' def _b64_normalize(s): appendix = '=' * (4 - len(s) % 4) return s.replace('-', '+').replace('_', '/') + appendix sr = str(signed_request) logging.info('parse signed request: %s' % sr) enc_sig, enc_payload = sr.split('.', 1) sig = base64.b64decode(_b64_normalize(enc_sig)) data = _parse_json(base64.b64decode(_b64_normalize(enc_payload))) if data['algorithm'] != u'HMAC-SHA256': return None expected_sig = hmac.new(self.client_secret, enc_payload, hashlib.sha256).digest() if expected_sig == sig: data.user_id = data.uid = data.get('user_id', None) data.access_token = data.get('oauth_token', None) expires = data.get('expires', None) if expires: data.expires = data.expires_in = time.time() + expires return data return None
[ "def", "parse_signed_request", "(", "self", ",", "signed_request", ")", ":", "def", "_b64_normalize", "(", "s", ")", ":", "appendix", "=", "'='", "*", "(", "4", "-", "len", "(", "s", ")", "%", "4", ")", "return", "s", ".", "replace", "(", "'-'", ",...
parse signed request when using in-site app. Returns: dict object like { 'uid': 12345, 'access_token': 'ABC123XYZ', 'expires': unix-timestamp }, or None if parse failed.
[ "parse", "signed", "request", "when", "using", "in", "-", "site", "app", "." ]
0f19dd71c1fbd16ee539620c7e9e986887f5c665
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/snspy.py#L264-L291
226,063
michaelliao/sinaweibopy
snspy.py
QQMixin.refresh_access_token
def refresh_access_token(self, refresh_token, redirect_uri=None): ''' Refresh access token. ''' redirect = redirect_uri or self._redirect_uri resp_text = _http('POST', 'https://graph.qq.com/oauth2.0/token', refresh_token=refresh_token, client_id=self._client_id, client_secret=self._client_secret, redirect_uri=redirect, grant_type='refresh_token') return self._parse_access_token(resp_text)
python
def refresh_access_token(self, refresh_token, redirect_uri=None): ''' Refresh access token. ''' redirect = redirect_uri or self._redirect_uri resp_text = _http('POST', 'https://graph.qq.com/oauth2.0/token', refresh_token=refresh_token, client_id=self._client_id, client_secret=self._client_secret, redirect_uri=redirect, grant_type='refresh_token') return self._parse_access_token(resp_text)
[ "def", "refresh_access_token", "(", "self", ",", "refresh_token", ",", "redirect_uri", "=", "None", ")", ":", "redirect", "=", "redirect_uri", "or", "self", ".", "_redirect_uri", "resp_text", "=", "_http", "(", "'POST'", ",", "'https://graph.qq.com/oauth2.0/token'",...
Refresh access token.
[ "Refresh", "access", "token", "." ]
0f19dd71c1fbd16ee539620c7e9e986887f5c665
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/snspy.py#L324-L333
226,064
michaelliao/sinaweibopy
snspy.py
QQMixin._parse_access_token
def _parse_access_token(self, resp_text): ' parse access token from urlencoded str like access_token=abcxyz&expires_in=123000&other=true ' r = self._qs2dict(resp_text) access_token = r.pop('access_token') expires = time.time() + float(r.pop('expires_in')) return JsonDict(access_token=access_token, expires=expires, **r)
python
def _parse_access_token(self, resp_text): ' parse access token from urlencoded str like access_token=abcxyz&expires_in=123000&other=true ' r = self._qs2dict(resp_text) access_token = r.pop('access_token') expires = time.time() + float(r.pop('expires_in')) return JsonDict(access_token=access_token, expires=expires, **r)
[ "def", "_parse_access_token", "(", "self", ",", "resp_text", ")", ":", "r", "=", "self", ".", "_qs2dict", "(", "resp_text", ")", "access_token", "=", "r", ".", "pop", "(", "'access_token'", ")", "expires", "=", "time", ".", "time", "(", ")", "+", "floa...
parse access token from urlencoded str like access_token=abcxyz&expires_in=123000&other=true
[ "parse", "access", "token", "from", "urlencoded", "str", "like", "access_token", "=", "abcxyz&expires_in", "=", "123000&other", "=", "true" ]
0f19dd71c1fbd16ee539620c7e9e986887f5c665
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/snspy.py#L336-L341
226,065
michaelliao/sinaweibopy
weibo.py
_parse_json
def _parse_json(s): ' parse str into JsonDict ' def _obj_hook(pairs): ' convert json object to python object ' o = JsonDict() for k, v in pairs.iteritems(): o[str(k)] = v return o return json.loads(s, object_hook=_obj_hook)
python
def _parse_json(s): ' parse str into JsonDict ' def _obj_hook(pairs): ' convert json object to python object ' o = JsonDict() for k, v in pairs.iteritems(): o[str(k)] = v return o return json.loads(s, object_hook=_obj_hook)
[ "def", "_parse_json", "(", "s", ")", ":", "def", "_obj_hook", "(", "pairs", ")", ":", "' convert json object to python object '", "o", "=", "JsonDict", "(", ")", "for", "k", ",", "v", "in", "pairs", ".", "iteritems", "(", ")", ":", "o", "[", "str", "("...
parse str into JsonDict
[ "parse", "str", "into", "JsonDict" ]
0f19dd71c1fbd16ee539620c7e9e986887f5c665
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/weibo.py#L46-L55
226,066
michaelliao/sinaweibopy
weibo.py
_encode_params
def _encode_params(**kw): ''' do url-encode parameters >>> _encode_params(a=1, b='R&D') 'a=1&b=R%26D' >>> _encode_params(a=u'\u4e2d\u6587', b=['A', 'B', 123]) 'a=%E4%B8%AD%E6%96%87&b=A&b=B&b=123' ''' args = [] for k, v in kw.iteritems(): if isinstance(v, basestring): qv = v.encode('utf-8') if isinstance(v, unicode) else v args.append('%s=%s' % (k, urllib.quote(qv))) elif isinstance(v, collections.Iterable): for i in v: qv = i.encode('utf-8') if isinstance(i, unicode) else str(i) args.append('%s=%s' % (k, urllib.quote(qv))) else: qv = str(v) args.append('%s=%s' % (k, urllib.quote(qv))) return '&'.join(args)
python
def _encode_params(**kw): ''' do url-encode parameters >>> _encode_params(a=1, b='R&D') 'a=1&b=R%26D' >>> _encode_params(a=u'\u4e2d\u6587', b=['A', 'B', 123]) 'a=%E4%B8%AD%E6%96%87&b=A&b=B&b=123' ''' args = [] for k, v in kw.iteritems(): if isinstance(v, basestring): qv = v.encode('utf-8') if isinstance(v, unicode) else v args.append('%s=%s' % (k, urllib.quote(qv))) elif isinstance(v, collections.Iterable): for i in v: qv = i.encode('utf-8') if isinstance(i, unicode) else str(i) args.append('%s=%s' % (k, urllib.quote(qv))) else: qv = str(v) args.append('%s=%s' % (k, urllib.quote(qv))) return '&'.join(args)
[ "def", "_encode_params", "(", "*", "*", "kw", ")", ":", "args", "=", "[", "]", "for", "k", ",", "v", "in", "kw", ".", "iteritems", "(", ")", ":", "if", "isinstance", "(", "v", ",", "basestring", ")", ":", "qv", "=", "v", ".", "encode", "(", "...
do url-encode parameters >>> _encode_params(a=1, b='R&D') 'a=1&b=R%26D' >>> _encode_params(a=u'\u4e2d\u6587', b=['A', 'B', 123]) 'a=%E4%B8%AD%E6%96%87&b=A&b=B&b=123'
[ "do", "url", "-", "encode", "parameters" ]
0f19dd71c1fbd16ee539620c7e9e986887f5c665
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/weibo.py#L71-L92
226,067
michaelliao/sinaweibopy
weibo.py
_http_call
def _http_call(the_url, method, authorization, **kw): ''' send an http request and return a json object if no error occurred. ''' params = None boundary = None if method == _HTTP_UPLOAD: # fix sina upload url: the_url = the_url.replace('https://api.', 'https://upload.api.') params, boundary = _encode_multipart(**kw) else: params = _encode_params(**kw) if '/remind/' in the_url: # fix sina remind api: the_url = the_url.replace('https://api.', 'https://rm.api.') http_url = '%s?%s' % (the_url, params) if method == _HTTP_GET else the_url http_body = None if method == _HTTP_GET else params req = urllib2.Request(http_url, data=http_body) req.add_header('Accept-Encoding', 'gzip') if authorization: req.add_header('Authorization', 'OAuth2 %s' % authorization) if boundary: req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary) try: resp = urllib2.urlopen(req, timeout=5) body = _read_body(resp) r = _parse_json(body) if hasattr(r, 'error_code'): raise APIError(r.error_code, r.get('error', ''), r.get('request', '')) return r except urllib2.HTTPError as e: try: r = _parse_json(_read_body(e)) except: r = None if hasattr(r, 'error_code'): raise APIError(r.error_code, r.get('error', ''), r.get('request', '')) raise e
python
def _http_call(the_url, method, authorization, **kw): ''' send an http request and return a json object if no error occurred. ''' params = None boundary = None if method == _HTTP_UPLOAD: # fix sina upload url: the_url = the_url.replace('https://api.', 'https://upload.api.') params, boundary = _encode_multipart(**kw) else: params = _encode_params(**kw) if '/remind/' in the_url: # fix sina remind api: the_url = the_url.replace('https://api.', 'https://rm.api.') http_url = '%s?%s' % (the_url, params) if method == _HTTP_GET else the_url http_body = None if method == _HTTP_GET else params req = urllib2.Request(http_url, data=http_body) req.add_header('Accept-Encoding', 'gzip') if authorization: req.add_header('Authorization', 'OAuth2 %s' % authorization) if boundary: req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary) try: resp = urllib2.urlopen(req, timeout=5) body = _read_body(resp) r = _parse_json(body) if hasattr(r, 'error_code'): raise APIError(r.error_code, r.get('error', ''), r.get('request', '')) return r except urllib2.HTTPError as e: try: r = _parse_json(_read_body(e)) except: r = None if hasattr(r, 'error_code'): raise APIError(r.error_code, r.get('error', ''), r.get('request', '')) raise e
[ "def", "_http_call", "(", "the_url", ",", "method", ",", "authorization", ",", "*", "*", "kw", ")", ":", "params", "=", "None", "boundary", "=", "None", "if", "method", "==", "_HTTP_UPLOAD", ":", "# fix sina upload url:", "the_url", "=", "the_url", ".", "r...
send an http request and return a json object if no error occurred.
[ "send", "an", "http", "request", "and", "return", "a", "json", "object", "if", "no", "error", "occurred", "." ]
0f19dd71c1fbd16ee539620c7e9e986887f5c665
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/weibo.py#L154-L191
226,068
Blizzard/s2client-proto
setup.py
proto_files
def proto_files(root): """Yields the path of all .proto files under the root.""" for (dirpath, _, filenames) in os.walk(root): for filename in filenames: if filename.endswith('.proto'): yield os.path.join(dirpath, filename)
python
def proto_files(root): for (dirpath, _, filenames) in os.walk(root): for filename in filenames: if filename.endswith('.proto'): yield os.path.join(dirpath, filename)
[ "def", "proto_files", "(", "root", ")", ":", "for", "(", "dirpath", ",", "_", ",", "filenames", ")", "in", "os", ".", "walk", "(", "root", ")", ":", "for", "filename", "in", "filenames", ":", "if", "filename", ".", "endswith", "(", "'.proto'", ")", ...
Yields the path of all .proto files under the root.
[ "Yields", "the", "path", "of", "all", ".", "proto", "files", "under", "the", "root", "." ]
e38efed74c03bec90f74b330ea1adda9215e655f
https://github.com/Blizzard/s2client-proto/blob/e38efed74c03bec90f74b330ea1adda9215e655f/setup.py#L28-L33
226,069
Blizzard/s2client-proto
setup.py
compile_proto
def compile_proto(source, python_out, proto_path): """Invoke Protocol Compiler to generate python from given source .proto.""" if not protoc: sys.exit('protoc not found. Is the protobuf-compiler installed?\n') protoc_command = [ protoc, '--proto_path', proto_path, '--python_out', python_out, source, ] if subprocess.call(protoc_command) != 0: sys.exit('Make sure your protoc version >= 2.6. You can use a custom ' 'protoc by setting the PROTOC environment variable.')
python
def compile_proto(source, python_out, proto_path): if not protoc: sys.exit('protoc not found. Is the protobuf-compiler installed?\n') protoc_command = [ protoc, '--proto_path', proto_path, '--python_out', python_out, source, ] if subprocess.call(protoc_command) != 0: sys.exit('Make sure your protoc version >= 2.6. You can use a custom ' 'protoc by setting the PROTOC environment variable.')
[ "def", "compile_proto", "(", "source", ",", "python_out", ",", "proto_path", ")", ":", "if", "not", "protoc", ":", "sys", ".", "exit", "(", "'protoc not found. Is the protobuf-compiler installed?\\n'", ")", "protoc_command", "=", "[", "protoc", ",", "'--proto_path'"...
Invoke Protocol Compiler to generate python from given source .proto.
[ "Invoke", "Protocol", "Compiler", "to", "generate", "python", "from", "given", "source", ".", "proto", "." ]
e38efed74c03bec90f74b330ea1adda9215e655f
https://github.com/Blizzard/s2client-proto/blob/e38efed74c03bec90f74b330ea1adda9215e655f/setup.py#L36-L49
226,070
kronenthaler/mod-pbxproj
pbxproj/pbxextensions/ProjectFiles.py
ProjectFiles.add_folder
def add_folder(self, path, parent=None, excludes=None, recursive=True, create_groups=True, target_name=None, file_options=FileOptions()): """ Given a directory, it will create the equivalent group structure and add all files in the process. If groups matching the logical path already exist, it will use them instead of creating a new one. Same apply for file within a group, if the file name already exists it will be ignored. :param path: OS path to the directory to be added. :param parent: Parent group to be added under :param excludes: list of regexs to ignore :param recursive: add folders recursively or stop in the first level :param create_groups: add folders recursively as groups or references :param target_name: Target name or list of target names where the file should be added (none for every target) :param file_options: FileOptions object to be used during the addition of the file to the project. :return: a list of elements that were added to the project successfully as PBXBuildFile objects """ if not os.path.isdir(path): return None if not excludes: excludes = [] results = [] # add the top folder as a group, make it the new parent path = os.path.abspath(path) if not create_groups and os.path.splitext(path)[1] not in ProjectFiles._SPECIAL_FOLDERS: return self.add_file(path, parent, target_name=target_name, force=False, file_options=file_options) parent = self.get_or_create_group(os.path.split(path)[1], path, parent) # iterate over the objects in the directory for child in os.listdir(path): # exclude dirs or files matching any of the expressions if [pattern for pattern in excludes if re.match(pattern, child)]: continue full_path = os.path.join(path, child) children = [] if os.path.isfile(full_path) or os.path.splitext(child)[1] in ProjectFiles._SPECIAL_FOLDERS or \ not create_groups: # check if the file exists already, if not add it children = self.add_file(full_path, parent, target_name=target_name, force=False, file_options=file_options) else: # if recursive is true, go deeper, otherwise create the group here. if recursive: children = self.add_folder(full_path, parent, excludes, recursive, target_name=target_name, file_options=file_options) else: self.get_or_create_group(child, child, parent) results.extend(children) return results
python
def add_folder(self, path, parent=None, excludes=None, recursive=True, create_groups=True, target_name=None, file_options=FileOptions()): if not os.path.isdir(path): return None if not excludes: excludes = [] results = [] # add the top folder as a group, make it the new parent path = os.path.abspath(path) if not create_groups and os.path.splitext(path)[1] not in ProjectFiles._SPECIAL_FOLDERS: return self.add_file(path, parent, target_name=target_name, force=False, file_options=file_options) parent = self.get_or_create_group(os.path.split(path)[1], path, parent) # iterate over the objects in the directory for child in os.listdir(path): # exclude dirs or files matching any of the expressions if [pattern for pattern in excludes if re.match(pattern, child)]: continue full_path = os.path.join(path, child) children = [] if os.path.isfile(full_path) or os.path.splitext(child)[1] in ProjectFiles._SPECIAL_FOLDERS or \ not create_groups: # check if the file exists already, if not add it children = self.add_file(full_path, parent, target_name=target_name, force=False, file_options=file_options) else: # if recursive is true, go deeper, otherwise create the group here. if recursive: children = self.add_folder(full_path, parent, excludes, recursive, target_name=target_name, file_options=file_options) else: self.get_or_create_group(child, child, parent) results.extend(children) return results
[ "def", "add_folder", "(", "self", ",", "path", ",", "parent", "=", "None", ",", "excludes", "=", "None", ",", "recursive", "=", "True", ",", "create_groups", "=", "True", ",", "target_name", "=", "None", ",", "file_options", "=", "FileOptions", "(", ")",...
Given a directory, it will create the equivalent group structure and add all files in the process. If groups matching the logical path already exist, it will use them instead of creating a new one. Same apply for file within a group, if the file name already exists it will be ignored. :param path: OS path to the directory to be added. :param parent: Parent group to be added under :param excludes: list of regexs to ignore :param recursive: add folders recursively or stop in the first level :param create_groups: add folders recursively as groups or references :param target_name: Target name or list of target names where the file should be added (none for every target) :param file_options: FileOptions object to be used during the addition of the file to the project. :return: a list of elements that were added to the project successfully as PBXBuildFile objects
[ "Given", "a", "directory", "it", "will", "create", "the", "equivalent", "group", "structure", "and", "add", "all", "files", "in", "the", "process", ".", "If", "groups", "matching", "the", "logical", "path", "already", "exist", "it", "will", "use", "them", ...
8de3cbdd3210480ddbb1fa0f50a4f4ea87de6e71
https://github.com/kronenthaler/mod-pbxproj/blob/8de3cbdd3210480ddbb1fa0f50a4f4ea87de6e71/pbxproj/pbxextensions/ProjectFiles.py#L342-L396
226,071
kronenthaler/mod-pbxproj
pbxproj/pbxextensions/ProjectFlags.py
ProjectFlags.add_code_sign
def add_code_sign(self, code_sign_identity, development_team, provisioning_profile_uuid, provisioning_profile_specifier, target_name=None, configuration_name=None): """ Adds the code sign information to the project and creates the appropriate flags in the configuration. In xcode 8+ the provisioning_profile_uuid becomes optional, and the provisioning_profile_specifier becomes mandatory. Contrariwise, in xcode 8< provisioning_profile_uuid becomes mandatory and provisioning_profile_specifier becomes optional. :param code_sign_identity: Code sign identity name. Usually formatted as: 'iPhone Distribution[: <Company name> (MAAYFEXXXX)]' :param development_team: Development team identifier string. Usually formatted as: 'MAAYFEXXXX' :param provisioning_profile_uuid: Provisioning profile UUID string. Usually formatted as: '6f1ffc4d-xxxx-xxxx-xxxx-6dc186280e1e' :param provisioning_profile_specifier: Provisioning profile specifier (a.k.a. name) string. :param target_name: Target name or list of target names to add the flag to or None for every target :param configuration_name: Configuration name to add the flag to or None for every configuration :return: """ self.set_flags(u'CODE_SIGN_IDENTITY[sdk=iphoneos*]', code_sign_identity, target_name, configuration_name) self.set_flags(u'DEVELOPMENT_TEAM', development_team, target_name, configuration_name) self.set_flags(u'PROVISIONING_PROFILE', provisioning_profile_uuid, target_name, configuration_name) self.set_flags(u'PROVISIONING_PROFILE_SPECIFIER', provisioning_profile_specifier, target_name, configuration_name) for target in self.objects.get_targets(target_name): self.objects[self.rootObject].set_provisioning_style(PBXProvioningTypes.MANUAL, target)
python
def add_code_sign(self, code_sign_identity, development_team, provisioning_profile_uuid, provisioning_profile_specifier, target_name=None, configuration_name=None): self.set_flags(u'CODE_SIGN_IDENTITY[sdk=iphoneos*]', code_sign_identity, target_name, configuration_name) self.set_flags(u'DEVELOPMENT_TEAM', development_team, target_name, configuration_name) self.set_flags(u'PROVISIONING_PROFILE', provisioning_profile_uuid, target_name, configuration_name) self.set_flags(u'PROVISIONING_PROFILE_SPECIFIER', provisioning_profile_specifier, target_name, configuration_name) for target in self.objects.get_targets(target_name): self.objects[self.rootObject].set_provisioning_style(PBXProvioningTypes.MANUAL, target)
[ "def", "add_code_sign", "(", "self", ",", "code_sign_identity", ",", "development_team", ",", "provisioning_profile_uuid", ",", "provisioning_profile_specifier", ",", "target_name", "=", "None", ",", "configuration_name", "=", "None", ")", ":", "self", ".", "set_flags...
Adds the code sign information to the project and creates the appropriate flags in the configuration. In xcode 8+ the provisioning_profile_uuid becomes optional, and the provisioning_profile_specifier becomes mandatory. Contrariwise, in xcode 8< provisioning_profile_uuid becomes mandatory and provisioning_profile_specifier becomes optional. :param code_sign_identity: Code sign identity name. Usually formatted as: 'iPhone Distribution[: <Company name> (MAAYFEXXXX)]' :param development_team: Development team identifier string. Usually formatted as: 'MAAYFEXXXX' :param provisioning_profile_uuid: Provisioning profile UUID string. Usually formatted as: '6f1ffc4d-xxxx-xxxx-xxxx-6dc186280e1e' :param provisioning_profile_specifier: Provisioning profile specifier (a.k.a. name) string. :param target_name: Target name or list of target names to add the flag to or None for every target :param configuration_name: Configuration name to add the flag to or None for every configuration :return:
[ "Adds", "the", "code", "sign", "information", "to", "the", "project", "and", "creates", "the", "appropriate", "flags", "in", "the", "configuration", ".", "In", "xcode", "8", "+", "the", "provisioning_profile_uuid", "becomes", "optional", "and", "the", "provision...
8de3cbdd3210480ddbb1fa0f50a4f4ea87de6e71
https://github.com/kronenthaler/mod-pbxproj/blob/8de3cbdd3210480ddbb1fa0f50a4f4ea87de6e71/pbxproj/pbxextensions/ProjectFlags.py#L218-L240
226,072
django-notifications/django-notifications
notifications/models.py
notify_handler
def notify_handler(verb, **kwargs): """ Handler function to create Notification instance upon action signal call. """ # Pull the options out of kwargs kwargs.pop('signal', None) recipient = kwargs.pop('recipient') actor = kwargs.pop('sender') optional_objs = [ (kwargs.pop(opt, None), opt) for opt in ('target', 'action_object') ] public = bool(kwargs.pop('public', True)) description = kwargs.pop('description', None) timestamp = kwargs.pop('timestamp', timezone.now()) level = kwargs.pop('level', Notification.LEVELS.info) # Check if User or Group if isinstance(recipient, Group): recipients = recipient.user_set.all() elif isinstance(recipient, (QuerySet, list)): recipients = recipient else: recipients = [recipient] new_notifications = [] for recipient in recipients: newnotify = Notification( recipient=recipient, actor_content_type=ContentType.objects.get_for_model(actor), actor_object_id=actor.pk, verb=text_type(verb), public=public, description=description, timestamp=timestamp, level=level, ) # Set optional objects for obj, opt in optional_objs: if obj is not None: setattr(newnotify, '%s_object_id' % opt, obj.pk) setattr(newnotify, '%s_content_type' % opt, ContentType.objects.get_for_model(obj)) if kwargs and EXTRA_DATA: newnotify.data = kwargs newnotify.save() new_notifications.append(newnotify) return new_notifications
python
def notify_handler(verb, **kwargs): # Pull the options out of kwargs kwargs.pop('signal', None) recipient = kwargs.pop('recipient') actor = kwargs.pop('sender') optional_objs = [ (kwargs.pop(opt, None), opt) for opt in ('target', 'action_object') ] public = bool(kwargs.pop('public', True)) description = kwargs.pop('description', None) timestamp = kwargs.pop('timestamp', timezone.now()) level = kwargs.pop('level', Notification.LEVELS.info) # Check if User or Group if isinstance(recipient, Group): recipients = recipient.user_set.all() elif isinstance(recipient, (QuerySet, list)): recipients = recipient else: recipients = [recipient] new_notifications = [] for recipient in recipients: newnotify = Notification( recipient=recipient, actor_content_type=ContentType.objects.get_for_model(actor), actor_object_id=actor.pk, verb=text_type(verb), public=public, description=description, timestamp=timestamp, level=level, ) # Set optional objects for obj, opt in optional_objs: if obj is not None: setattr(newnotify, '%s_object_id' % opt, obj.pk) setattr(newnotify, '%s_content_type' % opt, ContentType.objects.get_for_model(obj)) if kwargs and EXTRA_DATA: newnotify.data = kwargs newnotify.save() new_notifications.append(newnotify) return new_notifications
[ "def", "notify_handler", "(", "verb", ",", "*", "*", "kwargs", ")", ":", "# Pull the options out of kwargs", "kwargs", ".", "pop", "(", "'signal'", ",", "None", ")", "recipient", "=", "kwargs", ".", "pop", "(", "'recipient'", ")", "actor", "=", "kwargs", "...
Handler function to create Notification instance upon action signal call.
[ "Handler", "function", "to", "create", "Notification", "instance", "upon", "action", "signal", "call", "." ]
c271193215a053d6477d5ceca6f2524793bf9cb1
https://github.com/django-notifications/django-notifications/blob/c271193215a053d6477d5ceca6f2524793bf9cb1/notifications/models.py#L255-L308
226,073
django-notifications/django-notifications
notifications/models.py
NotificationQuerySet.unread
def unread(self, include_deleted=False): """Return only unread items in the current queryset""" if is_soft_delete() and not include_deleted: return self.filter(unread=True, deleted=False) # When SOFT_DELETE=False, developers are supposed NOT to touch 'deleted' field. # In this case, to improve query performance, don't filter by 'deleted' field return self.filter(unread=True)
python
def unread(self, include_deleted=False): if is_soft_delete() and not include_deleted: return self.filter(unread=True, deleted=False) # When SOFT_DELETE=False, developers are supposed NOT to touch 'deleted' field. # In this case, to improve query performance, don't filter by 'deleted' field return self.filter(unread=True)
[ "def", "unread", "(", "self", ",", "include_deleted", "=", "False", ")", ":", "if", "is_soft_delete", "(", ")", "and", "not", "include_deleted", ":", "return", "self", ".", "filter", "(", "unread", "=", "True", ",", "deleted", "=", "False", ")", "# When ...
Return only unread items in the current queryset
[ "Return", "only", "unread", "items", "in", "the", "current", "queryset" ]
c271193215a053d6477d5ceca6f2524793bf9cb1
https://github.com/django-notifications/django-notifications/blob/c271193215a053d6477d5ceca6f2524793bf9cb1/notifications/models.py#L50-L57
226,074
django-notifications/django-notifications
notifications/models.py
NotificationQuerySet.read
def read(self, include_deleted=False): """Return only read items in the current queryset""" if is_soft_delete() and not include_deleted: return self.filter(unread=False, deleted=False) # When SOFT_DELETE=False, developers are supposed NOT to touch 'deleted' field. # In this case, to improve query performance, don't filter by 'deleted' field return self.filter(unread=False)
python
def read(self, include_deleted=False): if is_soft_delete() and not include_deleted: return self.filter(unread=False, deleted=False) # When SOFT_DELETE=False, developers are supposed NOT to touch 'deleted' field. # In this case, to improve query performance, don't filter by 'deleted' field return self.filter(unread=False)
[ "def", "read", "(", "self", ",", "include_deleted", "=", "False", ")", ":", "if", "is_soft_delete", "(", ")", "and", "not", "include_deleted", ":", "return", "self", ".", "filter", "(", "unread", "=", "False", ",", "deleted", "=", "False", ")", "# When S...
Return only read items in the current queryset
[ "Return", "only", "read", "items", "in", "the", "current", "queryset" ]
c271193215a053d6477d5ceca6f2524793bf9cb1
https://github.com/django-notifications/django-notifications/blob/c271193215a053d6477d5ceca6f2524793bf9cb1/notifications/models.py#L59-L66
226,075
django-notifications/django-notifications
notifications/models.py
NotificationQuerySet.mark_all_as_read
def mark_all_as_read(self, recipient=None): """Mark as read any unread messages in the current queryset. Optionally, filter these by recipient first. """ # We want to filter out read ones, as later we will store # the time they were marked as read. qset = self.unread(True) if recipient: qset = qset.filter(recipient=recipient) return qset.update(unread=False)
python
def mark_all_as_read(self, recipient=None): # We want to filter out read ones, as later we will store # the time they were marked as read. qset = self.unread(True) if recipient: qset = qset.filter(recipient=recipient) return qset.update(unread=False)
[ "def", "mark_all_as_read", "(", "self", ",", "recipient", "=", "None", ")", ":", "# We want to filter out read ones, as later we will store", "# the time they were marked as read.", "qset", "=", "self", ".", "unread", "(", "True", ")", "if", "recipient", ":", "qset", ...
Mark as read any unread messages in the current queryset. Optionally, filter these by recipient first.
[ "Mark", "as", "read", "any", "unread", "messages", "in", "the", "current", "queryset", "." ]
c271193215a053d6477d5ceca6f2524793bf9cb1
https://github.com/django-notifications/django-notifications/blob/c271193215a053d6477d5ceca6f2524793bf9cb1/notifications/models.py#L68-L79
226,076
django-notifications/django-notifications
notifications/models.py
NotificationQuerySet.mark_all_as_unread
def mark_all_as_unread(self, recipient=None): """Mark as unread any read messages in the current queryset. Optionally, filter these by recipient first. """ qset = self.read(True) if recipient: qset = qset.filter(recipient=recipient) return qset.update(unread=True)
python
def mark_all_as_unread(self, recipient=None): qset = self.read(True) if recipient: qset = qset.filter(recipient=recipient) return qset.update(unread=True)
[ "def", "mark_all_as_unread", "(", "self", ",", "recipient", "=", "None", ")", ":", "qset", "=", "self", ".", "read", "(", "True", ")", "if", "recipient", ":", "qset", "=", "qset", ".", "filter", "(", "recipient", "=", "recipient", ")", "return", "qset"...
Mark as unread any read messages in the current queryset. Optionally, filter these by recipient first.
[ "Mark", "as", "unread", "any", "read", "messages", "in", "the", "current", "queryset", "." ]
c271193215a053d6477d5ceca6f2524793bf9cb1
https://github.com/django-notifications/django-notifications/blob/c271193215a053d6477d5ceca6f2524793bf9cb1/notifications/models.py#L81-L91
226,077
django-notifications/django-notifications
notifications/models.py
NotificationQuerySet.mark_all_as_deleted
def mark_all_as_deleted(self, recipient=None): """Mark current queryset as deleted. Optionally, filter by recipient first. """ assert_soft_delete() qset = self.active() if recipient: qset = qset.filter(recipient=recipient) return qset.update(deleted=True)
python
def mark_all_as_deleted(self, recipient=None): assert_soft_delete() qset = self.active() if recipient: qset = qset.filter(recipient=recipient) return qset.update(deleted=True)
[ "def", "mark_all_as_deleted", "(", "self", ",", "recipient", "=", "None", ")", ":", "assert_soft_delete", "(", ")", "qset", "=", "self", ".", "active", "(", ")", "if", "recipient", ":", "qset", "=", "qset", ".", "filter", "(", "recipient", "=", "recipien...
Mark current queryset as deleted. Optionally, filter by recipient first.
[ "Mark", "current", "queryset", "as", "deleted", ".", "Optionally", "filter", "by", "recipient", "first", "." ]
c271193215a053d6477d5ceca6f2524793bf9cb1
https://github.com/django-notifications/django-notifications/blob/c271193215a053d6477d5ceca6f2524793bf9cb1/notifications/models.py#L103-L112
226,078
django-notifications/django-notifications
notifications/views.py
live_unread_notification_list
def live_unread_notification_list(request): ''' Return a json with a unread notification list ''' try: user_is_authenticated = request.user.is_authenticated() except TypeError: # Django >= 1.11 user_is_authenticated = request.user.is_authenticated if not user_is_authenticated: data = { 'unread_count': 0, 'unread_list': [] } return JsonResponse(data) default_num_to_fetch = get_config()['NUM_TO_FETCH'] try: # If they don't specify, make it 5. num_to_fetch = request.GET.get('max', default_num_to_fetch) num_to_fetch = int(num_to_fetch) if not (1 <= num_to_fetch <= 100): num_to_fetch = default_num_to_fetch except ValueError: # If casting to an int fails. num_to_fetch = default_num_to_fetch unread_list = [] for notification in request.user.notifications.unread()[0:num_to_fetch]: struct = model_to_dict(notification) struct['slug'] = id2slug(notification.id) if notification.actor: struct['actor'] = str(notification.actor) if notification.target: struct['target'] = str(notification.target) if notification.action_object: struct['action_object'] = str(notification.action_object) if notification.data: struct['data'] = notification.data unread_list.append(struct) if request.GET.get('mark_as_read'): notification.mark_as_read() data = { 'unread_count': request.user.notifications.unread().count(), 'unread_list': unread_list } return JsonResponse(data)
python
def live_unread_notification_list(request): ''' Return a json with a unread notification list ''' try: user_is_authenticated = request.user.is_authenticated() except TypeError: # Django >= 1.11 user_is_authenticated = request.user.is_authenticated if not user_is_authenticated: data = { 'unread_count': 0, 'unread_list': [] } return JsonResponse(data) default_num_to_fetch = get_config()['NUM_TO_FETCH'] try: # If they don't specify, make it 5. num_to_fetch = request.GET.get('max', default_num_to_fetch) num_to_fetch = int(num_to_fetch) if not (1 <= num_to_fetch <= 100): num_to_fetch = default_num_to_fetch except ValueError: # If casting to an int fails. num_to_fetch = default_num_to_fetch unread_list = [] for notification in request.user.notifications.unread()[0:num_to_fetch]: struct = model_to_dict(notification) struct['slug'] = id2slug(notification.id) if notification.actor: struct['actor'] = str(notification.actor) if notification.target: struct['target'] = str(notification.target) if notification.action_object: struct['action_object'] = str(notification.action_object) if notification.data: struct['data'] = notification.data unread_list.append(struct) if request.GET.get('mark_as_read'): notification.mark_as_read() data = { 'unread_count': request.user.notifications.unread().count(), 'unread_list': unread_list } return JsonResponse(data)
[ "def", "live_unread_notification_list", "(", "request", ")", ":", "try", ":", "user_is_authenticated", "=", "request", ".", "user", ".", "is_authenticated", "(", ")", "except", "TypeError", ":", "# Django >= 1.11", "user_is_authenticated", "=", "request", ".", "user...
Return a json with a unread notification list
[ "Return", "a", "json", "with", "a", "unread", "notification", "list" ]
c271193215a053d6477d5ceca6f2524793bf9cb1
https://github.com/django-notifications/django-notifications/blob/c271193215a053d6477d5ceca6f2524793bf9cb1/notifications/views.py#L143-L187
226,079
graphql-python/graphql-core-next
graphql/language/lexer.py
uni_char_code
def uni_char_code(a: str, b: str, c: str, d: str): """Convert unicode characters to integers. Converts four hexadecimal chars to the integer that the string represents. For example, uni_char_code('0','0','0','f') will return 15, and uni_char_code('0','0','f','f') returns 255. Returns a negative number on error, if a char was invalid. This is implemented by noting that char2hex() returns -1 on error, which means the result of ORing the char2hex() will also be negative. """ return char2hex(a) << 12 | char2hex(b) << 8 | char2hex(c) << 4 | char2hex(d)
python
def uni_char_code(a: str, b: str, c: str, d: str): return char2hex(a) << 12 | char2hex(b) << 8 | char2hex(c) << 4 | char2hex(d)
[ "def", "uni_char_code", "(", "a", ":", "str", ",", "b", ":", "str", ",", "c", ":", "str", ",", "d", ":", "str", ")", ":", "return", "char2hex", "(", "a", ")", "<<", "12", "|", "char2hex", "(", "b", ")", "<<", "8", "|", "char2hex", "(", "c", ...
Convert unicode characters to integers. Converts four hexadecimal chars to the integer that the string represents. For example, uni_char_code('0','0','0','f') will return 15, and uni_char_code('0','0','f','f') returns 255. Returns a negative number on error, if a char was invalid. This is implemented by noting that char2hex() returns -1 on error, which means the result of ORing the char2hex() will also be negative.
[ "Convert", "unicode", "characters", "to", "integers", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/lexer.py#L478-L490
226,080
graphql-python/graphql-core-next
graphql/language/lexer.py
char2hex
def char2hex(a: str): """Convert a hex character to its integer value. '0' becomes 0, '9' becomes 9 'A' becomes 10, 'F' becomes 15 'a' becomes 10, 'f' becomes 15 Returns -1 on error. """ if "0" <= a <= "9": return ord(a) - 48 elif "A" <= a <= "F": return ord(a) - 55 elif "a" <= a <= "f": # a-f return ord(a) - 87 return -1
python
def char2hex(a: str): if "0" <= a <= "9": return ord(a) - 48 elif "A" <= a <= "F": return ord(a) - 55 elif "a" <= a <= "f": # a-f return ord(a) - 87 return -1
[ "def", "char2hex", "(", "a", ":", "str", ")", ":", "if", "\"0\"", "<=", "a", "<=", "\"9\"", ":", "return", "ord", "(", "a", ")", "-", "48", "elif", "\"A\"", "<=", "a", "<=", "\"F\"", ":", "return", "ord", "(", "a", ")", "-", "55", "elif", "\"...
Convert a hex character to its integer value. '0' becomes 0, '9' becomes 9 'A' becomes 10, 'F' becomes 15 'a' becomes 10, 'f' becomes 15 Returns -1 on error.
[ "Convert", "a", "hex", "character", "to", "its", "integer", "value", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/lexer.py#L493-L509
226,081
graphql-python/graphql-core-next
graphql/language/lexer.py
Token.desc
def desc(self) -> str: """A helper property to describe a token as a string for debugging""" kind, value = self.kind.value, self.value return f"{kind} {value!r}" if value else kind
python
def desc(self) -> str: kind, value = self.kind.value, self.value return f"{kind} {value!r}" if value else kind
[ "def", "desc", "(", "self", ")", "->", "str", ":", "kind", ",", "value", "=", "self", ".", "kind", ".", "value", ",", "self", ".", "value", "return", "f\"{kind} {value!r}\"", "if", "value", "else", "kind" ]
A helper property to describe a token as a string for debugging
[ "A", "helper", "property", "to", "describe", "a", "token", "as", "a", "string", "for", "debugging" ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/lexer.py#L100-L103
226,082
graphql-python/graphql-core-next
graphql/language/lexer.py
Lexer.read_token
def read_token(self, prev: Token) -> Token: """Get the next token from the source starting at the given position. This skips over whitespace until it finds the next lexable token, then lexes punctuators immediately or calls the appropriate helper function for more complicated tokens. """ source = self.source body = source.body body_length = len(body) pos = self.position_after_whitespace(body, prev.end) line = self.line col = 1 + pos - self.line_start if pos >= body_length: return Token(TokenKind.EOF, body_length, body_length, line, col, prev) char = body[pos] kind = _KIND_FOR_PUNCT.get(char) if kind: return Token(kind, pos, pos + 1, line, col, prev) if char == "#": return self.read_comment(pos, line, col, prev) elif char == ".": if body[pos + 1 : pos + 3] == "..": return Token(TokenKind.SPREAD, pos, pos + 3, line, col, prev) elif "A" <= char <= "Z" or "a" <= char <= "z" or char == "_": return self.read_name(pos, line, col, prev) elif "0" <= char <= "9" or char == "-": return self.read_number(pos, char, line, col, prev) elif char == '"': if body[pos + 1 : pos + 3] == '""': return self.read_block_string(pos, line, col, prev) return self.read_string(pos, line, col, prev) raise GraphQLSyntaxError(source, pos, unexpected_character_message(char))
python
def read_token(self, prev: Token) -> Token: source = self.source body = source.body body_length = len(body) pos = self.position_after_whitespace(body, prev.end) line = self.line col = 1 + pos - self.line_start if pos >= body_length: return Token(TokenKind.EOF, body_length, body_length, line, col, prev) char = body[pos] kind = _KIND_FOR_PUNCT.get(char) if kind: return Token(kind, pos, pos + 1, line, col, prev) if char == "#": return self.read_comment(pos, line, col, prev) elif char == ".": if body[pos + 1 : pos + 3] == "..": return Token(TokenKind.SPREAD, pos, pos + 3, line, col, prev) elif "A" <= char <= "Z" or "a" <= char <= "z" or char == "_": return self.read_name(pos, line, col, prev) elif "0" <= char <= "9" or char == "-": return self.read_number(pos, char, line, col, prev) elif char == '"': if body[pos + 1 : pos + 3] == '""': return self.read_block_string(pos, line, col, prev) return self.read_string(pos, line, col, prev) raise GraphQLSyntaxError(source, pos, unexpected_character_message(char))
[ "def", "read_token", "(", "self", ",", "prev", ":", "Token", ")", "->", "Token", ":", "source", "=", "self", ".", "source", "body", "=", "source", ".", "body", "body_length", "=", "len", "(", "body", ")", "pos", "=", "self", ".", "position_after_whites...
Get the next token from the source starting at the given position. This skips over whitespace until it finds the next lexable token, then lexes punctuators immediately or calls the appropriate helper function for more complicated tokens.
[ "Get", "the", "next", "token", "from", "the", "source", "starting", "at", "the", "given", "position", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/lexer.py#L169-L205
226,083
graphql-python/graphql-core-next
graphql/language/lexer.py
Lexer.position_after_whitespace
def position_after_whitespace(self, body: str, start_position: int) -> int: """Go to next position after a whitespace. Reads from body starting at start_position until it finds a non-whitespace character, then returns the position of that character for lexing. """ body_length = len(body) position = start_position while position < body_length: char = body[position] if char in " \t,\ufeff": position += 1 elif char == "\n": position += 1 self.line += 1 self.line_start = position elif char == "\r": if body[position + 1 : position + 2] == "\n": position += 2 else: position += 1 self.line += 1 self.line_start = position else: break return position
python
def position_after_whitespace(self, body: str, start_position: int) -> int: body_length = len(body) position = start_position while position < body_length: char = body[position] if char in " \t,\ufeff": position += 1 elif char == "\n": position += 1 self.line += 1 self.line_start = position elif char == "\r": if body[position + 1 : position + 2] == "\n": position += 2 else: position += 1 self.line += 1 self.line_start = position else: break return position
[ "def", "position_after_whitespace", "(", "self", ",", "body", ":", "str", ",", "start_position", ":", "int", ")", "->", "int", ":", "body_length", "=", "len", "(", "body", ")", "position", "=", "start_position", "while", "position", "<", "body_length", ":", ...
Go to next position after a whitespace. Reads from body starting at start_position until it finds a non-whitespace character, then returns the position of that character for lexing.
[ "Go", "to", "next", "position", "after", "a", "whitespace", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/lexer.py#L207-L232
226,084
graphql-python/graphql-core-next
graphql/language/lexer.py
Lexer.read_comment
def read_comment(self, start: int, line: int, col: int, prev: Token) -> Token: """Read a comment token from the source file.""" body = self.source.body body_length = len(body) position = start while True: position += 1 if position > body_length: break char = body[position] if char < " " and char != "\t": break return Token( TokenKind.COMMENT, start, position, line, col, prev, body[start + 1 : position], )
python
def read_comment(self, start: int, line: int, col: int, prev: Token) -> Token: body = self.source.body body_length = len(body) position = start while True: position += 1 if position > body_length: break char = body[position] if char < " " and char != "\t": break return Token( TokenKind.COMMENT, start, position, line, col, prev, body[start + 1 : position], )
[ "def", "read_comment", "(", "self", ",", "start", ":", "int", ",", "line", ":", "int", ",", "col", ":", "int", ",", "prev", ":", "Token", ")", "->", "Token", ":", "body", "=", "self", ".", "source", ".", "body", "body_length", "=", "len", "(", "b...
Read a comment token from the source file.
[ "Read", "a", "comment", "token", "from", "the", "source", "file", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/lexer.py#L234-L255
226,085
graphql-python/graphql-core-next
graphql/language/lexer.py
Lexer.read_number
def read_number( self, start: int, char: str, line: int, col: int, prev: Token ) -> Token: """Reads a number token from the source file. Either a float or an int depending on whether a decimal point appears. """ source = self.source body = source.body position = start is_float = False if char == "-": position += 1 char = body[position : position + 1] if char == "0": position += 1 char = body[position : position + 1] if "0" <= char <= "9": raise GraphQLSyntaxError( source, position, f"Invalid number, unexpected digit after 0: {print_char(char)}.", ) else: position = self.read_digits(position, char) char = body[position : position + 1] if char == ".": is_float = True position += 1 char = body[position : position + 1] position = self.read_digits(position, char) char = body[position : position + 1] if char and char in "Ee": is_float = True position += 1 char = body[position : position + 1] if char and char in "+-": position += 1 char = body[position : position + 1] position = self.read_digits(position, char) return Token( TokenKind.FLOAT if is_float else TokenKind.INT, start, position, line, col, prev, body[start:position], )
python
def read_number( self, start: int, char: str, line: int, col: int, prev: Token ) -> Token: source = self.source body = source.body position = start is_float = False if char == "-": position += 1 char = body[position : position + 1] if char == "0": position += 1 char = body[position : position + 1] if "0" <= char <= "9": raise GraphQLSyntaxError( source, position, f"Invalid number, unexpected digit after 0: {print_char(char)}.", ) else: position = self.read_digits(position, char) char = body[position : position + 1] if char == ".": is_float = True position += 1 char = body[position : position + 1] position = self.read_digits(position, char) char = body[position : position + 1] if char and char in "Ee": is_float = True position += 1 char = body[position : position + 1] if char and char in "+-": position += 1 char = body[position : position + 1] position = self.read_digits(position, char) return Token( TokenKind.FLOAT if is_float else TokenKind.INT, start, position, line, col, prev, body[start:position], )
[ "def", "read_number", "(", "self", ",", "start", ":", "int", ",", "char", ":", "str", ",", "line", ":", "int", ",", "col", ":", "int", ",", "prev", ":", "Token", ")", "->", "Token", ":", "source", "=", "self", ".", "source", "body", "=", "source"...
Reads a number token from the source file. Either a float or an int depending on whether a decimal point appears.
[ "Reads", "a", "number", "token", "from", "the", "source", "file", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/lexer.py#L257-L305
226,086
graphql-python/graphql-core-next
graphql/language/lexer.py
Lexer.read_digits
def read_digits(self, start: int, char: str) -> int: """Return the new position in the source after reading digits.""" source = self.source body = source.body position = start while "0" <= char <= "9": position += 1 char = body[position : position + 1] if position == start: raise GraphQLSyntaxError( source, position, f"Invalid number, expected digit but got: {print_char(char)}.", ) return position
python
def read_digits(self, start: int, char: str) -> int: source = self.source body = source.body position = start while "0" <= char <= "9": position += 1 char = body[position : position + 1] if position == start: raise GraphQLSyntaxError( source, position, f"Invalid number, expected digit but got: {print_char(char)}.", ) return position
[ "def", "read_digits", "(", "self", ",", "start", ":", "int", ",", "char", ":", "str", ")", "->", "int", ":", "source", "=", "self", ".", "source", "body", "=", "source", ".", "body", "position", "=", "start", "while", "\"0\"", "<=", "char", "<=", "...
Return the new position in the source after reading digits.
[ "Return", "the", "new", "position", "in", "the", "source", "after", "reading", "digits", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/lexer.py#L307-L321
226,087
graphql-python/graphql-core-next
graphql/language/lexer.py
Lexer.read_string
def read_string(self, start: int, line: int, col: int, prev: Token) -> Token: """Read a string token from the source file.""" source = self.source body = source.body body_length = len(body) position = start + 1 chunk_start = position value: List[str] = [] append = value.append while position < body_length: char = body[position] if char in "\n\r": break if char == '"': append(body[chunk_start:position]) return Token( TokenKind.STRING, start, position + 1, line, col, prev, "".join(value), ) if char < " " and char != "\t": raise GraphQLSyntaxError( source, position, f"Invalid character within String: {print_char(char)}.", ) position += 1 if char == "\\": append(body[chunk_start : position - 1]) char = body[position : position + 1] escaped = _ESCAPED_CHARS.get(char) if escaped: value.append(escaped) elif char == "u" and position + 4 < body_length: code = uni_char_code(*body[position + 1 : position + 5]) if code < 0: escape = repr(body[position : position + 5]) escape = escape[:1] + "\\" + escape[1:] raise GraphQLSyntaxError( source, position, f"Invalid character escape sequence: {escape}.", ) append(chr(code)) position += 4 else: escape = repr(char) escape = escape[:1] + "\\" + escape[1:] raise GraphQLSyntaxError( source, position, f"Invalid character escape sequence: {escape}.", ) position += 1 chunk_start = position raise GraphQLSyntaxError(source, position, "Unterminated string.")
python
def read_string(self, start: int, line: int, col: int, prev: Token) -> Token: source = self.source body = source.body body_length = len(body) position = start + 1 chunk_start = position value: List[str] = [] append = value.append while position < body_length: char = body[position] if char in "\n\r": break if char == '"': append(body[chunk_start:position]) return Token( TokenKind.STRING, start, position + 1, line, col, prev, "".join(value), ) if char < " " and char != "\t": raise GraphQLSyntaxError( source, position, f"Invalid character within String: {print_char(char)}.", ) position += 1 if char == "\\": append(body[chunk_start : position - 1]) char = body[position : position + 1] escaped = _ESCAPED_CHARS.get(char) if escaped: value.append(escaped) elif char == "u" and position + 4 < body_length: code = uni_char_code(*body[position + 1 : position + 5]) if code < 0: escape = repr(body[position : position + 5]) escape = escape[:1] + "\\" + escape[1:] raise GraphQLSyntaxError( source, position, f"Invalid character escape sequence: {escape}.", ) append(chr(code)) position += 4 else: escape = repr(char) escape = escape[:1] + "\\" + escape[1:] raise GraphQLSyntaxError( source, position, f"Invalid character escape sequence: {escape}.", ) position += 1 chunk_start = position raise GraphQLSyntaxError(source, position, "Unterminated string.")
[ "def", "read_string", "(", "self", ",", "start", ":", "int", ",", "line", ":", "int", ",", "col", ":", "int", ",", "prev", ":", "Token", ")", "->", "Token", ":", "source", "=", "self", ".", "source", "body", "=", "source", ".", "body", "body_length...
Read a string token from the source file.
[ "Read", "a", "string", "token", "from", "the", "source", "file", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/lexer.py#L323-L384
226,088
graphql-python/graphql-core-next
graphql/language/lexer.py
Lexer.read_name
def read_name(self, start: int, line: int, col: int, prev: Token) -> Token: """Read an alphanumeric + underscore name from the source.""" body = self.source.body body_length = len(body) position = start + 1 while position < body_length: char = body[position] if not ( char == "_" or "0" <= char <= "9" or "A" <= char <= "Z" or "a" <= char <= "z" ): break position += 1 return Token( TokenKind.NAME, start, position, line, col, prev, body[start:position] )
python
def read_name(self, start: int, line: int, col: int, prev: Token) -> Token: body = self.source.body body_length = len(body) position = start + 1 while position < body_length: char = body[position] if not ( char == "_" or "0" <= char <= "9" or "A" <= char <= "Z" or "a" <= char <= "z" ): break position += 1 return Token( TokenKind.NAME, start, position, line, col, prev, body[start:position] )
[ "def", "read_name", "(", "self", ",", "start", ":", "int", ",", "line", ":", "int", ",", "col", ":", "int", ",", "prev", ":", "Token", ")", "->", "Token", ":", "body", "=", "self", ".", "source", ".", "body", "body_length", "=", "len", "(", "body...
Read an alphanumeric + underscore name from the source.
[ "Read", "an", "alphanumeric", "+", "underscore", "name", "from", "the", "source", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/lexer.py#L434-L451
226,089
graphql-python/graphql-core-next
graphql/execution/execute.py
execute
def execute( schema: GraphQLSchema, document: DocumentNode, root_value: Any = None, context_value: Any = None, variable_values: Dict[str, Any] = None, operation_name: str = None, field_resolver: GraphQLFieldResolver = None, type_resolver: GraphQLTypeResolver = None, middleware: Middleware = None, execution_context_class: Type["ExecutionContext"] = None, ) -> AwaitableOrValue[ExecutionResult]: """Execute a GraphQL operation. Implements the "Evaluating requests" section of the GraphQL specification. Returns an ExecutionResult (if all encountered resolvers are synchronous), or a coroutine object eventually yielding an ExecutionResult. If the arguments to this function do not result in a legal execution context, a GraphQLError will be thrown immediately explaining the invalid input. """ # If arguments are missing or incorrect, throw an error. assert_valid_execution_arguments(schema, document, variable_values) if execution_context_class is None: execution_context_class = ExecutionContext # If a valid execution context cannot be created due to incorrect arguments, # a "Response" with only errors is returned. exe_context = execution_context_class.build( schema, document, root_value, context_value, variable_values, operation_name, field_resolver, type_resolver, middleware, ) # Return early errors if execution context failed. if isinstance(exe_context, list): return ExecutionResult(data=None, errors=exe_context) # Return a possible coroutine object that will eventually yield the data described # by the "Response" section of the GraphQL specification. # # If errors are encountered while executing a GraphQL field, only that field and # its descendants will be omitted, and sibling fields will still be executed. An # execution which encounters errors will still result in a coroutine object that # can be executed without errors. data = exe_context.execute_operation(exe_context.operation, root_value) return exe_context.build_response(data)
python
def execute( schema: GraphQLSchema, document: DocumentNode, root_value: Any = None, context_value: Any = None, variable_values: Dict[str, Any] = None, operation_name: str = None, field_resolver: GraphQLFieldResolver = None, type_resolver: GraphQLTypeResolver = None, middleware: Middleware = None, execution_context_class: Type["ExecutionContext"] = None, ) -> AwaitableOrValue[ExecutionResult]: # If arguments are missing or incorrect, throw an error. assert_valid_execution_arguments(schema, document, variable_values) if execution_context_class is None: execution_context_class = ExecutionContext # If a valid execution context cannot be created due to incorrect arguments, # a "Response" with only errors is returned. exe_context = execution_context_class.build( schema, document, root_value, context_value, variable_values, operation_name, field_resolver, type_resolver, middleware, ) # Return early errors if execution context failed. if isinstance(exe_context, list): return ExecutionResult(data=None, errors=exe_context) # Return a possible coroutine object that will eventually yield the data described # by the "Response" section of the GraphQL specification. # # If errors are encountered while executing a GraphQL field, only that field and # its descendants will be omitted, and sibling fields will still be executed. An # execution which encounters errors will still result in a coroutine object that # can be executed without errors. data = exe_context.execute_operation(exe_context.operation, root_value) return exe_context.build_response(data)
[ "def", "execute", "(", "schema", ":", "GraphQLSchema", ",", "document", ":", "DocumentNode", ",", "root_value", ":", "Any", "=", "None", ",", "context_value", ":", "Any", "=", "None", ",", "variable_values", ":", "Dict", "[", "str", ",", "Any", "]", "=",...
Execute a GraphQL operation. Implements the "Evaluating requests" section of the GraphQL specification. Returns an ExecutionResult (if all encountered resolvers are synchronous), or a coroutine object eventually yielding an ExecutionResult. If the arguments to this function do not result in a legal execution context, a GraphQLError will be thrown immediately explaining the invalid input.
[ "Execute", "a", "GraphQL", "operation", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/execution/execute.py#L108-L163
226,090
graphql-python/graphql-core-next
graphql/execution/execute.py
assert_valid_execution_arguments
def assert_valid_execution_arguments( schema: GraphQLSchema, document: DocumentNode, raw_variable_values: Dict[str, Any] = None, ) -> None: """Check that the arguments are acceptable. Essential assertions before executing to provide developer feedback for improper use of the GraphQL library. """ if not document: raise TypeError("Must provide document") # If the schema used for execution is invalid, throw an error. assert_valid_schema(schema) # Variables, if provided, must be a dictionary. if not (raw_variable_values is None or isinstance(raw_variable_values, dict)): raise TypeError( "Variables must be provided as a dictionary where each property is a" " variable value. Perhaps look to see if an unparsed JSON string was" " provided." )
python
def assert_valid_execution_arguments( schema: GraphQLSchema, document: DocumentNode, raw_variable_values: Dict[str, Any] = None, ) -> None: if not document: raise TypeError("Must provide document") # If the schema used for execution is invalid, throw an error. assert_valid_schema(schema) # Variables, if provided, must be a dictionary. if not (raw_variable_values is None or isinstance(raw_variable_values, dict)): raise TypeError( "Variables must be provided as a dictionary where each property is a" " variable value. Perhaps look to see if an unparsed JSON string was" " provided." )
[ "def", "assert_valid_execution_arguments", "(", "schema", ":", "GraphQLSchema", ",", "document", ":", "DocumentNode", ",", "raw_variable_values", ":", "Dict", "[", "str", ",", "Any", "]", "=", "None", ",", ")", "->", "None", ":", "if", "not", "document", ":"...
Check that the arguments are acceptable. Essential assertions before executing to provide developer feedback for improper use of the GraphQL library.
[ "Check", "that", "the", "arguments", "are", "acceptable", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/execution/execute.py#L1017-L1039
226,091
graphql-python/graphql-core-next
graphql/execution/execute.py
response_path_as_list
def response_path_as_list(path: ResponsePath) -> List[Union[str, int]]: """Get response path as a list. Given a ResponsePath (found in the `path` entry in the information provided as the last argument to a field resolver), return a list of the path keys. """ flattened: List[Union[str, int]] = [] append = flattened.append curr: Optional[ResponsePath] = path while curr: append(curr.key) curr = curr.prev return flattened[::-1]
python
def response_path_as_list(path: ResponsePath) -> List[Union[str, int]]: flattened: List[Union[str, int]] = [] append = flattened.append curr: Optional[ResponsePath] = path while curr: append(curr.key) curr = curr.prev return flattened[::-1]
[ "def", "response_path_as_list", "(", "path", ":", "ResponsePath", ")", "->", "List", "[", "Union", "[", "str", ",", "int", "]", "]", ":", "flattened", ":", "List", "[", "Union", "[", "str", ",", "int", "]", "]", "=", "[", "]", "append", "=", "flatt...
Get response path as a list. Given a ResponsePath (found in the `path` entry in the information provided as the last argument to a field resolver), return a list of the path keys.
[ "Get", "response", "path", "as", "a", "list", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/execution/execute.py#L1042-L1054
226,092
graphql-python/graphql-core-next
graphql/execution/execute.py
add_path
def add_path(prev: Optional[ResponsePath], key: Union[str, int]) -> ResponsePath: """Add a key to a response path. Given a ResponsePath and a key, return a new ResponsePath containing the new key. """ return ResponsePath(prev, key)
python
def add_path(prev: Optional[ResponsePath], key: Union[str, int]) -> ResponsePath: return ResponsePath(prev, key)
[ "def", "add_path", "(", "prev", ":", "Optional", "[", "ResponsePath", "]", ",", "key", ":", "Union", "[", "str", ",", "int", "]", ")", "->", "ResponsePath", ":", "return", "ResponsePath", "(", "prev", ",", "key", ")" ]
Add a key to a response path. Given a ResponsePath and a key, return a new ResponsePath containing the new key.
[ "Add", "a", "key", "to", "a", "response", "path", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/execution/execute.py#L1057-L1062
226,093
graphql-python/graphql-core-next
graphql/execution/execute.py
invalid_return_type_error
def invalid_return_type_error( return_type: GraphQLObjectType, result: Any, field_nodes: List[FieldNode] ) -> GraphQLError: """Create a GraphQLError for an invalid return type.""" return GraphQLError( f"Expected value of type '{return_type.name}' but got: {inspect(result)}.", field_nodes, )
python
def invalid_return_type_error( return_type: GraphQLObjectType, result: Any, field_nodes: List[FieldNode] ) -> GraphQLError: return GraphQLError( f"Expected value of type '{return_type.name}' but got: {inspect(result)}.", field_nodes, )
[ "def", "invalid_return_type_error", "(", "return_type", ":", "GraphQLObjectType", ",", "result", ":", "Any", ",", "field_nodes", ":", "List", "[", "FieldNode", "]", ")", "->", "GraphQLError", ":", "return", "GraphQLError", "(", "f\"Expected value of type '{return_type...
Create a GraphQLError for an invalid return type.
[ "Create", "a", "GraphQLError", "for", "an", "invalid", "return", "type", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/execution/execute.py#L1091-L1098
226,094
graphql-python/graphql-core-next
graphql/execution/execute.py
default_type_resolver
def default_type_resolver( value: Any, info: GraphQLResolveInfo, abstract_type: GraphQLAbstractType ) -> AwaitableOrValue[Optional[Union[GraphQLObjectType, str]]]: """Default type resolver function. If a resolve_type function is not given, then a default resolve behavior is used which attempts two strategies: First, See if the provided value has a `__typename` field defined, if so, use that value as name of the resolved type. Otherwise, test each possible type for the abstract type by calling `is_type_of` for the object being coerced, returning the first type that matches. """ # First, look for `__typename`. type_name = ( value.get("__typename") if isinstance(value, dict) # need to de-mangle the attribute assumed to be "private" in Python else getattr(value, f"_{value.__class__.__name__}__typename", None) ) if isinstance(type_name, str): return type_name # Otherwise, test each possible type. possible_types = info.schema.get_possible_types(abstract_type) awaitable_is_type_of_results: List[Awaitable] = [] append_awaitable_results = awaitable_is_type_of_results.append awaitable_types: List[GraphQLObjectType] = [] append_awaitable_types = awaitable_types.append for type_ in possible_types: if type_.is_type_of: is_type_of_result = type_.is_type_of(value, info) if isawaitable(is_type_of_result): append_awaitable_results(cast(Awaitable, is_type_of_result)) append_awaitable_types(type_) elif is_type_of_result: return type_ if awaitable_is_type_of_results: # noinspection PyShadowingNames async def get_type(): is_type_of_results = await gather(*awaitable_is_type_of_results) for is_type_of_result, type_ in zip(is_type_of_results, awaitable_types): if is_type_of_result: return type_ return get_type() return None
python
def default_type_resolver( value: Any, info: GraphQLResolveInfo, abstract_type: GraphQLAbstractType ) -> AwaitableOrValue[Optional[Union[GraphQLObjectType, str]]]: # First, look for `__typename`. type_name = ( value.get("__typename") if isinstance(value, dict) # need to de-mangle the attribute assumed to be "private" in Python else getattr(value, f"_{value.__class__.__name__}__typename", None) ) if isinstance(type_name, str): return type_name # Otherwise, test each possible type. possible_types = info.schema.get_possible_types(abstract_type) awaitable_is_type_of_results: List[Awaitable] = [] append_awaitable_results = awaitable_is_type_of_results.append awaitable_types: List[GraphQLObjectType] = [] append_awaitable_types = awaitable_types.append for type_ in possible_types: if type_.is_type_of: is_type_of_result = type_.is_type_of(value, info) if isawaitable(is_type_of_result): append_awaitable_results(cast(Awaitable, is_type_of_result)) append_awaitable_types(type_) elif is_type_of_result: return type_ if awaitable_is_type_of_results: # noinspection PyShadowingNames async def get_type(): is_type_of_results = await gather(*awaitable_is_type_of_results) for is_type_of_result, type_ in zip(is_type_of_results, awaitable_types): if is_type_of_result: return type_ return get_type() return None
[ "def", "default_type_resolver", "(", "value", ":", "Any", ",", "info", ":", "GraphQLResolveInfo", ",", "abstract_type", ":", "GraphQLAbstractType", ")", "->", "AwaitableOrValue", "[", "Optional", "[", "Union", "[", "GraphQLObjectType", ",", "str", "]", "]", "]",...
Default type resolver function. If a resolve_type function is not given, then a default resolve behavior is used which attempts two strategies: First, See if the provided value has a `__typename` field defined, if so, use that value as name of the resolved type. Otherwise, test each possible type for the abstract type by calling `is_type_of` for the object being coerced, returning the first type that matches.
[ "Default", "type", "resolver", "function", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/execution/execute.py#L1101-L1152
226,095
graphql-python/graphql-core-next
graphql/execution/execute.py
default_field_resolver
def default_field_resolver(source, info, **args): """Default field resolver. If a resolve function is not given, then a default resolve behavior is used which takes the property of the source object of the same name as the field and returns it as the result, or if it's a function, returns the result of calling that function while passing along args and context. For dictionaries, the field names are used as keys, for all other objects they are used as attribute names. """ # Ensure source is a value for which property access is acceptable. field_name = info.field_name value = ( source.get(field_name) if isinstance(source, dict) else getattr(source, field_name, None) ) if callable(value): return value(info, **args) return value
python
def default_field_resolver(source, info, **args): # Ensure source is a value for which property access is acceptable. field_name = info.field_name value = ( source.get(field_name) if isinstance(source, dict) else getattr(source, field_name, None) ) if callable(value): return value(info, **args) return value
[ "def", "default_field_resolver", "(", "source", ",", "info", ",", "*", "*", "args", ")", ":", "# Ensure source is a value for which property access is acceptable.", "field_name", "=", "info", ".", "field_name", "value", "=", "(", "source", ".", "get", "(", "field_na...
Default field resolver. If a resolve function is not given, then a default resolve behavior is used which takes the property of the source object of the same name as the field and returns it as the result, or if it's a function, returns the result of calling that function while passing along args and context. For dictionaries, the field names are used as keys, for all other objects they are used as attribute names.
[ "Default", "field", "resolver", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/execution/execute.py#L1155-L1175
226,096
graphql-python/graphql-core-next
graphql/execution/execute.py
ExecutionContext.build
def build( cls, schema: GraphQLSchema, document: DocumentNode, root_value: Any = None, context_value: Any = None, raw_variable_values: Dict[str, Any] = None, operation_name: str = None, field_resolver: GraphQLFieldResolver = None, type_resolver: GraphQLTypeResolver = None, middleware: Middleware = None, ) -> Union[List[GraphQLError], "ExecutionContext"]: """Build an execution context Constructs a ExecutionContext object from the arguments passed to execute, which we will pass throughout the other execution methods. Throws a GraphQLError if a valid execution context cannot be created. """ errors: List[GraphQLError] = [] operation: Optional[OperationDefinitionNode] = None has_multiple_assumed_operations = False fragments: Dict[str, FragmentDefinitionNode] = {} middleware_manager: Optional[MiddlewareManager] = None if middleware is not None: if isinstance(middleware, (list, tuple)): middleware_manager = MiddlewareManager(*middleware) elif isinstance(middleware, MiddlewareManager): middleware_manager = middleware else: raise TypeError( "Middleware must be passed as a list or tuple of functions" " or objects, or as a single MiddlewareManager object." f" Got {inspect(middleware)} instead." ) for definition in document.definitions: if isinstance(definition, OperationDefinitionNode): if not operation_name and operation: has_multiple_assumed_operations = True elif not operation_name or ( definition.name and definition.name.value == operation_name ): operation = definition elif isinstance(definition, FragmentDefinitionNode): fragments[definition.name.value] = definition if not operation: if operation_name: errors.append( GraphQLError(f"Unknown operation named '{operation_name}'.") ) else: errors.append(GraphQLError("Must provide an operation.")) elif has_multiple_assumed_operations: errors.append( GraphQLError( "Must provide operation name" " if query contains multiple operations." ) ) variable_values = None if operation: coerced_variable_values = get_variable_values( schema, operation.variable_definitions or [], raw_variable_values or {} ) if coerced_variable_values.errors: errors.extend(coerced_variable_values.errors) else: variable_values = coerced_variable_values.coerced if errors: return errors if operation is None: raise TypeError("Has operation if no errors.") if variable_values is None: raise TypeError("Has variables if no errors.") return cls( schema, fragments, root_value, context_value, operation, variable_values, field_resolver or default_field_resolver, type_resolver or default_type_resolver, middleware_manager, errors, )
python
def build( cls, schema: GraphQLSchema, document: DocumentNode, root_value: Any = None, context_value: Any = None, raw_variable_values: Dict[str, Any] = None, operation_name: str = None, field_resolver: GraphQLFieldResolver = None, type_resolver: GraphQLTypeResolver = None, middleware: Middleware = None, ) -> Union[List[GraphQLError], "ExecutionContext"]: errors: List[GraphQLError] = [] operation: Optional[OperationDefinitionNode] = None has_multiple_assumed_operations = False fragments: Dict[str, FragmentDefinitionNode] = {} middleware_manager: Optional[MiddlewareManager] = None if middleware is not None: if isinstance(middleware, (list, tuple)): middleware_manager = MiddlewareManager(*middleware) elif isinstance(middleware, MiddlewareManager): middleware_manager = middleware else: raise TypeError( "Middleware must be passed as a list or tuple of functions" " or objects, or as a single MiddlewareManager object." f" Got {inspect(middleware)} instead." ) for definition in document.definitions: if isinstance(definition, OperationDefinitionNode): if not operation_name and operation: has_multiple_assumed_operations = True elif not operation_name or ( definition.name and definition.name.value == operation_name ): operation = definition elif isinstance(definition, FragmentDefinitionNode): fragments[definition.name.value] = definition if not operation: if operation_name: errors.append( GraphQLError(f"Unknown operation named '{operation_name}'.") ) else: errors.append(GraphQLError("Must provide an operation.")) elif has_multiple_assumed_operations: errors.append( GraphQLError( "Must provide operation name" " if query contains multiple operations." ) ) variable_values = None if operation: coerced_variable_values = get_variable_values( schema, operation.variable_definitions or [], raw_variable_values or {} ) if coerced_variable_values.errors: errors.extend(coerced_variable_values.errors) else: variable_values = coerced_variable_values.coerced if errors: return errors if operation is None: raise TypeError("Has operation if no errors.") if variable_values is None: raise TypeError("Has variables if no errors.") return cls( schema, fragments, root_value, context_value, operation, variable_values, field_resolver or default_field_resolver, type_resolver or default_type_resolver, middleware_manager, errors, )
[ "def", "build", "(", "cls", ",", "schema", ":", "GraphQLSchema", ",", "document", ":", "DocumentNode", ",", "root_value", ":", "Any", "=", "None", ",", "context_value", ":", "Any", "=", "None", ",", "raw_variable_values", ":", "Dict", "[", "str", ",", "A...
Build an execution context Constructs a ExecutionContext object from the arguments passed to execute, which we will pass throughout the other execution methods. Throws a GraphQLError if a valid execution context cannot be created.
[ "Build", "an", "execution", "context" ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/execution/execute.py#L212-L304
226,097
graphql-python/graphql-core-next
graphql/execution/execute.py
ExecutionContext.build_response
def build_response( self, data: AwaitableOrValue[Optional[Dict[str, Any]]] ) -> AwaitableOrValue[ExecutionResult]: """Build response. Given a completed execution context and data, build the (data, errors) response defined by the "Response" section of the GraphQL spec. """ if isawaitable(data): async def build_response_async(): return self.build_response(await data) return build_response_async() data = cast(Optional[Dict[str, Any]], data) errors = self.errors if not errors: return ExecutionResult(data, None) # Sort the error list in order to make it deterministic, since we might have # been using parallel execution. errors.sort(key=lambda error: (error.locations, error.path, error.message)) return ExecutionResult(data, errors)
python
def build_response( self, data: AwaitableOrValue[Optional[Dict[str, Any]]] ) -> AwaitableOrValue[ExecutionResult]: if isawaitable(data): async def build_response_async(): return self.build_response(await data) return build_response_async() data = cast(Optional[Dict[str, Any]], data) errors = self.errors if not errors: return ExecutionResult(data, None) # Sort the error list in order to make it deterministic, since we might have # been using parallel execution. errors.sort(key=lambda error: (error.locations, error.path, error.message)) return ExecutionResult(data, errors)
[ "def", "build_response", "(", "self", ",", "data", ":", "AwaitableOrValue", "[", "Optional", "[", "Dict", "[", "str", ",", "Any", "]", "]", "]", ")", "->", "AwaitableOrValue", "[", "ExecutionResult", "]", ":", "if", "isawaitable", "(", "data", ")", ":", ...
Build response. Given a completed execution context and data, build the (data, errors) response defined by the "Response" section of the GraphQL spec.
[ "Build", "response", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/execution/execute.py#L306-L327
226,098
graphql-python/graphql-core-next
graphql/execution/execute.py
ExecutionContext.execute_operation
def execute_operation( self, operation: OperationDefinitionNode, root_value: Any ) -> Optional[AwaitableOrValue[Any]]: """Execute an operation. Implements the "Evaluating operations" section of the spec. """ type_ = get_operation_root_type(self.schema, operation) fields = self.collect_fields(type_, operation.selection_set, {}, set()) path = None # Errors from sub-fields of a NonNull type may propagate to the top level, at # which point we still log the error and null the parent field, which in this # case is the entire response. # # Similar to complete_value_catching_error. try: result = ( self.execute_fields_serially if operation.operation == OperationType.MUTATION else self.execute_fields )(type_, root_value, path, fields) except GraphQLError as error: self.errors.append(error) return None except Exception as error: error = GraphQLError(str(error), original_error=error) self.errors.append(error) return None else: if isawaitable(result): # noinspection PyShadowingNames async def await_result(): try: return await result except GraphQLError as error: self.errors.append(error) except Exception as error: error = GraphQLError(str(error), original_error=error) self.errors.append(error) return await_result() return result
python
def execute_operation( self, operation: OperationDefinitionNode, root_value: Any ) -> Optional[AwaitableOrValue[Any]]: type_ = get_operation_root_type(self.schema, operation) fields = self.collect_fields(type_, operation.selection_set, {}, set()) path = None # Errors from sub-fields of a NonNull type may propagate to the top level, at # which point we still log the error and null the parent field, which in this # case is the entire response. # # Similar to complete_value_catching_error. try: result = ( self.execute_fields_serially if operation.operation == OperationType.MUTATION else self.execute_fields )(type_, root_value, path, fields) except GraphQLError as error: self.errors.append(error) return None except Exception as error: error = GraphQLError(str(error), original_error=error) self.errors.append(error) return None else: if isawaitable(result): # noinspection PyShadowingNames async def await_result(): try: return await result except GraphQLError as error: self.errors.append(error) except Exception as error: error = GraphQLError(str(error), original_error=error) self.errors.append(error) return await_result() return result
[ "def", "execute_operation", "(", "self", ",", "operation", ":", "OperationDefinitionNode", ",", "root_value", ":", "Any", ")", "->", "Optional", "[", "AwaitableOrValue", "[", "Any", "]", "]", ":", "type_", "=", "get_operation_root_type", "(", "self", ".", "sch...
Execute an operation. Implements the "Evaluating operations" section of the spec.
[ "Execute", "an", "operation", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/execution/execute.py#L329-L372
226,099
graphql-python/graphql-core-next
graphql/execution/execute.py
ExecutionContext.execute_fields_serially
def execute_fields_serially( self, parent_type: GraphQLObjectType, source_value: Any, path: Optional[ResponsePath], fields: Dict[str, List[FieldNode]], ) -> AwaitableOrValue[Dict[str, Any]]: """Execute the given fields serially. Implements the "Evaluating selection sets" section of the spec for "write" mode. """ results: Dict[str, Any] = {} for response_name, field_nodes in fields.items(): field_path = add_path(path, response_name) result = self.resolve_field( parent_type, source_value, field_nodes, field_path ) if result is INVALID: continue if isawaitable(results): # noinspection PyShadowingNames async def await_and_set_result(results, response_name, result): awaited_results = await results awaited_results[response_name] = ( await result if isawaitable(result) else result ) return awaited_results # noinspection PyTypeChecker results = await_and_set_result( cast(Awaitable, results), response_name, result ) elif isawaitable(result): # noinspection PyShadowingNames async def set_result(results, response_name, result): results[response_name] = await result return results # noinspection PyTypeChecker results = set_result(results, response_name, result) else: results[response_name] = result if isawaitable(results): # noinspection PyShadowingNames async def get_results(): return await cast(Awaitable, results) return get_results() return results
python
def execute_fields_serially( self, parent_type: GraphQLObjectType, source_value: Any, path: Optional[ResponsePath], fields: Dict[str, List[FieldNode]], ) -> AwaitableOrValue[Dict[str, Any]]: results: Dict[str, Any] = {} for response_name, field_nodes in fields.items(): field_path = add_path(path, response_name) result = self.resolve_field( parent_type, source_value, field_nodes, field_path ) if result is INVALID: continue if isawaitable(results): # noinspection PyShadowingNames async def await_and_set_result(results, response_name, result): awaited_results = await results awaited_results[response_name] = ( await result if isawaitable(result) else result ) return awaited_results # noinspection PyTypeChecker results = await_and_set_result( cast(Awaitable, results), response_name, result ) elif isawaitable(result): # noinspection PyShadowingNames async def set_result(results, response_name, result): results[response_name] = await result return results # noinspection PyTypeChecker results = set_result(results, response_name, result) else: results[response_name] = result if isawaitable(results): # noinspection PyShadowingNames async def get_results(): return await cast(Awaitable, results) return get_results() return results
[ "def", "execute_fields_serially", "(", "self", ",", "parent_type", ":", "GraphQLObjectType", ",", "source_value", ":", "Any", ",", "path", ":", "Optional", "[", "ResponsePath", "]", ",", "fields", ":", "Dict", "[", "str", ",", "List", "[", "FieldNode", "]", ...
Execute the given fields serially. Implements the "Evaluating selection sets" section of the spec for "write" mode.
[ "Execute", "the", "given", "fields", "serially", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/execution/execute.py#L374-L422