repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
sighingnow/parsec.py
src/parsec/__init__.py
Value.aggregate
def aggregate(self, other=None): '''collect the furthest failure from self and other.''' if not self.status: return self if not other: return self if not other.status: return other return Value(True, other.index, self.value + other.value, None)
python
def aggregate(self, other=None): '''collect the furthest failure from self and other.''' if not self.status: return self if not other: return self if not other.status: return other return Value(True, other.index, self.value + other.value, None)
[ "def", "aggregate", "(", "self", ",", "other", "=", "None", ")", ":", "if", "not", "self", ".", "status", ":", "return", "self", "if", "not", "other", ":", "return", "self", "if", "not", "other", ".", "status", ":", "return", "other", "return", "Valu...
collect the furthest failure from self and other.
[ "collect", "the", "furthest", "failure", "from", "self", "and", "other", "." ]
ed50e1e259142757470b925f8d20dfe5ad223af0
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L64-L72
train
23,700
sighingnow/parsec.py
src/parsec/__init__.py
Value.combinate
def combinate(values): '''aggregate multiple values into tuple''' prev_v = None for v in values: if prev_v: if not v: return prev_v if not v.status: return v out_values = tuple([v.value for v in values]) return Value(True, values[-1].index, out_values, None)
python
def combinate(values): '''aggregate multiple values into tuple''' prev_v = None for v in values: if prev_v: if not v: return prev_v if not v.status: return v out_values = tuple([v.value for v in values]) return Value(True, values[-1].index, out_values, None)
[ "def", "combinate", "(", "values", ")", ":", "prev_v", "=", "None", "for", "v", "in", "values", ":", "if", "prev_v", ":", "if", "not", "v", ":", "return", "prev_v", "if", "not", "v", ".", "status", ":", "return", "v", "out_values", "=", "tuple", "(...
aggregate multiple values into tuple
[ "aggregate", "multiple", "values", "into", "tuple" ]
ed50e1e259142757470b925f8d20dfe5ad223af0
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L75-L85
train
23,701
sighingnow/parsec.py
src/parsec/__init__.py
Parser.parse_partial
def parse_partial(self, text): '''Parse the longest possible prefix of a given string. Return a tuple of the result value and the rest of the string. If failed, raise a ParseError. ''' if not isinstance(text, str): raise TypeError( 'Can only parsing string but got {!r}'.format(text)) res = self(text, 0) if res.status: return (res.value, text[res.index:]) else: raise ParseError(res.expected, text, res.index)
python
def parse_partial(self, text): '''Parse the longest possible prefix of a given string. Return a tuple of the result value and the rest of the string. If failed, raise a ParseError. ''' if not isinstance(text, str): raise TypeError( 'Can only parsing string but got {!r}'.format(text)) res = self(text, 0) if res.status: return (res.value, text[res.index:]) else: raise ParseError(res.expected, text, res.index)
[ "def", "parse_partial", "(", "self", ",", "text", ")", ":", "if", "not", "isinstance", "(", "text", ",", "str", ")", ":", "raise", "TypeError", "(", "'Can only parsing string but got {!r}'", ".", "format", "(", "text", ")", ")", "res", "=", "self", "(", ...
Parse the longest possible prefix of a given string. Return a tuple of the result value and the rest of the string. If failed, raise a ParseError.
[ "Parse", "the", "longest", "possible", "prefix", "of", "a", "given", "string", ".", "Return", "a", "tuple", "of", "the", "result", "value", "and", "the", "rest", "of", "the", "string", ".", "If", "failed", "raise", "a", "ParseError", "." ]
ed50e1e259142757470b925f8d20dfe5ad223af0
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L117-L128
train
23,702
sighingnow/parsec.py
src/parsec/__init__.py
Parser.bind
def bind(self, fn): '''This is the monadic binding operation. Returns a parser which, if parser is successful, passes the result to fn, and continues with the parser returned from fn. ''' @Parser def bind_parser(text, index): res = self(text, index) return res if not res.status else fn(res.value)(text, res.index) return bind_parser
python
def bind(self, fn): '''This is the monadic binding operation. Returns a parser which, if parser is successful, passes the result to fn, and continues with the parser returned from fn. ''' @Parser def bind_parser(text, index): res = self(text, index) return res if not res.status else fn(res.value)(text, res.index) return bind_parser
[ "def", "bind", "(", "self", ",", "fn", ")", ":", "@", "Parser", "def", "bind_parser", "(", "text", ",", "index", ")", ":", "res", "=", "self", "(", "text", ",", "index", ")", "return", "res", "if", "not", "res", ".", "status", "else", "fn", "(", ...
This is the monadic binding operation. Returns a parser which, if parser is successful, passes the result to fn, and continues with the parser returned from fn.
[ "This", "is", "the", "monadic", "binding", "operation", ".", "Returns", "a", "parser", "which", "if", "parser", "is", "successful", "passes", "the", "result", "to", "fn", "and", "continues", "with", "the", "parser", "returned", "from", "fn", "." ]
ed50e1e259142757470b925f8d20dfe5ad223af0
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L140-L149
train
23,703
sighingnow/parsec.py
src/parsec/__init__.py
Parser.parsecmap
def parsecmap(self, fn): '''Returns a parser that transforms the produced value of parser with `fn`.''' return self.bind(lambda res: Parser(lambda _, index: Value.success(index, fn(res))))
python
def parsecmap(self, fn): '''Returns a parser that transforms the produced value of parser with `fn`.''' return self.bind(lambda res: Parser(lambda _, index: Value.success(index, fn(res))))
[ "def", "parsecmap", "(", "self", ",", "fn", ")", ":", "return", "self", ".", "bind", "(", "lambda", "res", ":", "Parser", "(", "lambda", "_", ",", "index", ":", "Value", ".", "success", "(", "index", ",", "fn", "(", "res", ")", ")", ")", ")" ]
Returns a parser that transforms the produced value of parser with `fn`.
[ "Returns", "a", "parser", "that", "transforms", "the", "produced", "value", "of", "parser", "with", "fn", "." ]
ed50e1e259142757470b925f8d20dfe5ad223af0
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L218-L220
train
23,704
sighingnow/parsec.py
src/parsec/__init__.py
Parser.parsecapp
def parsecapp(self, other): '''Returns a parser that applies the produced value of this parser to the produced value of `other`.''' # pylint: disable=unnecessary-lambda return self.bind(lambda res: other.parsecmap(lambda x: res(x)))
python
def parsecapp(self, other): '''Returns a parser that applies the produced value of this parser to the produced value of `other`.''' # pylint: disable=unnecessary-lambda return self.bind(lambda res: other.parsecmap(lambda x: res(x)))
[ "def", "parsecapp", "(", "self", ",", "other", ")", ":", "# pylint: disable=unnecessary-lambda", "return", "self", ".", "bind", "(", "lambda", "res", ":", "other", ".", "parsecmap", "(", "lambda", "x", ":", "res", "(", "x", ")", ")", ")" ]
Returns a parser that applies the produced value of this parser to the produced value of `other`.
[ "Returns", "a", "parser", "that", "applies", "the", "produced", "value", "of", "this", "parser", "to", "the", "produced", "value", "of", "other", "." ]
ed50e1e259142757470b925f8d20dfe5ad223af0
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L222-L225
train
23,705
sighingnow/parsec.py
src/parsec/__init__.py
Parser.result
def result(self, res): '''Return a value according to the parameter `res` when parse successfully.''' return self >> Parser(lambda _, index: Value.success(index, res))
python
def result(self, res): '''Return a value according to the parameter `res` when parse successfully.''' return self >> Parser(lambda _, index: Value.success(index, res))
[ "def", "result", "(", "self", ",", "res", ")", ":", "return", "self", ">>", "Parser", "(", "lambda", "_", ",", "index", ":", "Value", ".", "success", "(", "index", ",", "res", ")", ")" ]
Return a value according to the parameter `res` when parse successfully.
[ "Return", "a", "value", "according", "to", "the", "parameter", "res", "when", "parse", "successfully", "." ]
ed50e1e259142757470b925f8d20dfe5ad223af0
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L227-L229
train
23,706
sighingnow/parsec.py
src/parsec/__init__.py
Parser.mark
def mark(self): '''Mark the line and column information of the result of this parser.''' def pos(text, index): return ParseError.loc_info(text, index) @Parser def mark_parser(text, index): res = self(text, index) if res.status: return Value.success(res.index, (pos(text, index), res.value, pos(text, res.index))) else: return res # failed. return mark_parser
python
def mark(self): '''Mark the line and column information of the result of this parser.''' def pos(text, index): return ParseError.loc_info(text, index) @Parser def mark_parser(text, index): res = self(text, index) if res.status: return Value.success(res.index, (pos(text, index), res.value, pos(text, res.index))) else: return res # failed. return mark_parser
[ "def", "mark", "(", "self", ")", ":", "def", "pos", "(", "text", ",", "index", ")", ":", "return", "ParseError", ".", "loc_info", "(", "text", ",", "index", ")", "@", "Parser", "def", "mark_parser", "(", "text", ",", "index", ")", ":", "res", "=", ...
Mark the line and column information of the result of this parser.
[ "Mark", "the", "line", "and", "column", "information", "of", "the", "result", "of", "this", "parser", "." ]
ed50e1e259142757470b925f8d20dfe5ad223af0
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L231-L243
train
23,707
sighingnow/parsec.py
src/parsec/__init__.py
Parser.desc
def desc(self, description): '''Describe a parser, when it failed, print out the description text.''' return self | Parser(lambda _, index: Value.failure(index, description))
python
def desc(self, description): '''Describe a parser, when it failed, print out the description text.''' return self | Parser(lambda _, index: Value.failure(index, description))
[ "def", "desc", "(", "self", ",", "description", ")", ":", "return", "self", "|", "Parser", "(", "lambda", "_", ",", "index", ":", "Value", ".", "failure", "(", "index", ",", "description", ")", ")" ]
Describe a parser, when it failed, print out the description text.
[ "Describe", "a", "parser", "when", "it", "failed", "print", "out", "the", "description", "text", "." ]
ed50e1e259142757470b925f8d20dfe5ad223af0
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L245-L247
train
23,708
pecan/pecan
pecan/routing.py
route
def route(*args): """ This function is used to define an explicit route for a path segment. You generally only want to use this in situations where your desired path segment is not a valid Python variable/function name. For example, if you wanted to be able to route to: /path/with-dashes/ ...the following is invalid Python syntax:: class Controller(object): with-dashes = SubController() ...so you would instead define the route explicitly:: class Controller(object): pass pecan.route(Controller, 'with-dashes', SubController()) """ def _validate_route(route): if not isinstance(route, six.string_types): raise TypeError('%s must be a string' % route) if route in ('.', '..') or not re.match( '^[0-9a-zA-Z-_$\(\)\.~!,;:*+@=]+$', route ): raise ValueError( '%s must be a valid path segment. Keep in mind ' 'that path segments should not contain path separators ' '(e.g., /) ' % route ) if len(args) == 2: # The handler in this situation is a @pecan.expose'd callable, # and is generally only used by the @expose() decorator itself. # # This sets a special attribute, `custom_route` on the callable, which # pecan's routing logic knows how to make use of (as a special case) route, handler = args if ismethod(handler): handler = handler.__func__ if not iscontroller(handler): raise TypeError( '%s must be a callable decorated with @pecan.expose' % handler ) obj, attr, value = handler, 'custom_route', route if handler.__name__ in ('_lookup', '_default', '_route'): raise ValueError( '%s is a special method in pecan and cannot be used in ' 'combination with custom path segments.' % handler.__name__ ) elif len(args) == 3: # This is really just a setattr on the parent controller (with some # additional validation for the path segment itself) _, route, handler = args obj, attr, value = args if hasattr(obj, attr): raise RuntimeError( ( "%(module)s.%(class)s already has an " "existing attribute named \"%(route)s\"." % { 'module': obj.__module__, 'class': obj.__name__, 'route': attr } ), ) else: raise TypeError( 'pecan.route should be called in the format ' 'route(ParentController, "path-segment", SubController())' ) _validate_route(route) setattr(obj, attr, value)
python
def route(*args): """ This function is used to define an explicit route for a path segment. You generally only want to use this in situations where your desired path segment is not a valid Python variable/function name. For example, if you wanted to be able to route to: /path/with-dashes/ ...the following is invalid Python syntax:: class Controller(object): with-dashes = SubController() ...so you would instead define the route explicitly:: class Controller(object): pass pecan.route(Controller, 'with-dashes', SubController()) """ def _validate_route(route): if not isinstance(route, six.string_types): raise TypeError('%s must be a string' % route) if route in ('.', '..') or not re.match( '^[0-9a-zA-Z-_$\(\)\.~!,;:*+@=]+$', route ): raise ValueError( '%s must be a valid path segment. Keep in mind ' 'that path segments should not contain path separators ' '(e.g., /) ' % route ) if len(args) == 2: # The handler in this situation is a @pecan.expose'd callable, # and is generally only used by the @expose() decorator itself. # # This sets a special attribute, `custom_route` on the callable, which # pecan's routing logic knows how to make use of (as a special case) route, handler = args if ismethod(handler): handler = handler.__func__ if not iscontroller(handler): raise TypeError( '%s must be a callable decorated with @pecan.expose' % handler ) obj, attr, value = handler, 'custom_route', route if handler.__name__ in ('_lookup', '_default', '_route'): raise ValueError( '%s is a special method in pecan and cannot be used in ' 'combination with custom path segments.' % handler.__name__ ) elif len(args) == 3: # This is really just a setattr on the parent controller (with some # additional validation for the path segment itself) _, route, handler = args obj, attr, value = args if hasattr(obj, attr): raise RuntimeError( ( "%(module)s.%(class)s already has an " "existing attribute named \"%(route)s\"." % { 'module': obj.__module__, 'class': obj.__name__, 'route': attr } ), ) else: raise TypeError( 'pecan.route should be called in the format ' 'route(ParentController, "path-segment", SubController())' ) _validate_route(route) setattr(obj, attr, value)
[ "def", "route", "(", "*", "args", ")", ":", "def", "_validate_route", "(", "route", ")", ":", "if", "not", "isinstance", "(", "route", ",", "six", ".", "string_types", ")", ":", "raise", "TypeError", "(", "'%s must be a string'", "%", "route", ")", "if",...
This function is used to define an explicit route for a path segment. You generally only want to use this in situations where your desired path segment is not a valid Python variable/function name. For example, if you wanted to be able to route to: /path/with-dashes/ ...the following is invalid Python syntax:: class Controller(object): with-dashes = SubController() ...so you would instead define the route explicitly:: class Controller(object): pass pecan.route(Controller, 'with-dashes', SubController())
[ "This", "function", "is", "used", "to", "define", "an", "explicit", "route", "for", "a", "path", "segment", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/routing.py#L19-L101
train
23,709
pecan/pecan
pecan/routing.py
lookup_controller
def lookup_controller(obj, remainder, request=None): ''' Traverses the requested url path and returns the appropriate controller object, including default routes. Handles common errors gracefully. ''' if request is None: warnings.warn( ( "The function signature for %s.lookup_controller is changing " "in the next version of pecan.\nPlease update to: " "`lookup_controller(self, obj, remainder, request)`." % ( __name__, ) ), DeprecationWarning ) notfound_handlers = [] while True: try: obj, remainder = find_object(obj, remainder, notfound_handlers, request) handle_security(obj) return obj, remainder except (exc.HTTPNotFound, exc.HTTPMethodNotAllowed, PecanNotFound) as e: if isinstance(e, PecanNotFound): e = exc.HTTPNotFound() while notfound_handlers: name, obj, remainder = notfound_handlers.pop() if name == '_default': # Notfound handler is, in fact, a controller, so stop # traversal return obj, remainder else: # Notfound handler is an internal redirect, so continue # traversal result = handle_lookup_traversal(obj, remainder) if result: # If no arguments are passed to the _lookup, yet the # argspec requires at least one, raise a 404 if ( remainder == [''] and len(obj._pecan['argspec'].args) > 1 ): raise e obj_, remainder_ = result return lookup_controller(obj_, remainder_, request) else: raise e
python
def lookup_controller(obj, remainder, request=None): ''' Traverses the requested url path and returns the appropriate controller object, including default routes. Handles common errors gracefully. ''' if request is None: warnings.warn( ( "The function signature for %s.lookup_controller is changing " "in the next version of pecan.\nPlease update to: " "`lookup_controller(self, obj, remainder, request)`." % ( __name__, ) ), DeprecationWarning ) notfound_handlers = [] while True: try: obj, remainder = find_object(obj, remainder, notfound_handlers, request) handle_security(obj) return obj, remainder except (exc.HTTPNotFound, exc.HTTPMethodNotAllowed, PecanNotFound) as e: if isinstance(e, PecanNotFound): e = exc.HTTPNotFound() while notfound_handlers: name, obj, remainder = notfound_handlers.pop() if name == '_default': # Notfound handler is, in fact, a controller, so stop # traversal return obj, remainder else: # Notfound handler is an internal redirect, so continue # traversal result = handle_lookup_traversal(obj, remainder) if result: # If no arguments are passed to the _lookup, yet the # argspec requires at least one, raise a 404 if ( remainder == [''] and len(obj._pecan['argspec'].args) > 1 ): raise e obj_, remainder_ = result return lookup_controller(obj_, remainder_, request) else: raise e
[ "def", "lookup_controller", "(", "obj", ",", "remainder", ",", "request", "=", "None", ")", ":", "if", "request", "is", "None", ":", "warnings", ".", "warn", "(", "(", "\"The function signature for %s.lookup_controller is changing \"", "\"in the next version of pecan.\\...
Traverses the requested url path and returns the appropriate controller object, including default routes. Handles common errors gracefully.
[ "Traverses", "the", "requested", "url", "path", "and", "returns", "the", "appropriate", "controller", "object", "including", "default", "routes", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/routing.py#L119-L170
train
23,710
pecan/pecan
pecan/routing.py
find_object
def find_object(obj, remainder, notfound_handlers, request): ''' 'Walks' the url path in search of an action for which a controller is implemented and returns that controller object along with what's left of the remainder. ''' prev_obj = None while True: if obj is None: raise PecanNotFound if iscontroller(obj): if getattr(obj, 'custom_route', None) is None: return obj, remainder _detect_custom_path_segments(obj) if remainder: custom_route = __custom_routes__.get((obj.__class__, remainder[0])) if custom_route: return getattr(obj, custom_route), remainder[1:] # are we traversing to another controller cross_boundary(prev_obj, obj) try: next_obj, rest = remainder[0], remainder[1:] if next_obj == '': index = getattr(obj, 'index', None) if iscontroller(index): return index, rest except IndexError: # the URL has hit an index method without a trailing slash index = getattr(obj, 'index', None) if iscontroller(index): raise NonCanonicalPath(index, []) default = getattr(obj, '_default', None) if iscontroller(default): notfound_handlers.append(('_default', default, remainder)) lookup = getattr(obj, '_lookup', None) if iscontroller(lookup): notfound_handlers.append(('_lookup', lookup, remainder)) route = getattr(obj, '_route', None) if iscontroller(route): if len(getargspec(route).args) == 2: warnings.warn( ( "The function signature for %s.%s._route is changing " "in the next version of pecan.\nPlease update to: " "`def _route(self, args, request)`." % ( obj.__class__.__module__, obj.__class__.__name__ ) ), DeprecationWarning ) next_obj, next_remainder = route(remainder) else: next_obj, next_remainder = route(remainder, request) cross_boundary(route, next_obj) return next_obj, next_remainder if not remainder: raise PecanNotFound prev_remainder = remainder prev_obj = obj remainder = rest try: obj = getattr(obj, next_obj, None) except UnicodeEncodeError: obj = None # Last-ditch effort: if there's not a matching subcontroller, no # `_default`, no `_lookup`, and no `_route`, look to see if there's # an `index` that has a generic method defined for the current request # method. if not obj and not notfound_handlers and hasattr(prev_obj, 'index'): if request.method in _cfg(prev_obj.index).get('generic_handlers', {}): return prev_obj.index, prev_remainder
python
def find_object(obj, remainder, notfound_handlers, request): ''' 'Walks' the url path in search of an action for which a controller is implemented and returns that controller object along with what's left of the remainder. ''' prev_obj = None while True: if obj is None: raise PecanNotFound if iscontroller(obj): if getattr(obj, 'custom_route', None) is None: return obj, remainder _detect_custom_path_segments(obj) if remainder: custom_route = __custom_routes__.get((obj.__class__, remainder[0])) if custom_route: return getattr(obj, custom_route), remainder[1:] # are we traversing to another controller cross_boundary(prev_obj, obj) try: next_obj, rest = remainder[0], remainder[1:] if next_obj == '': index = getattr(obj, 'index', None) if iscontroller(index): return index, rest except IndexError: # the URL has hit an index method without a trailing slash index = getattr(obj, 'index', None) if iscontroller(index): raise NonCanonicalPath(index, []) default = getattr(obj, '_default', None) if iscontroller(default): notfound_handlers.append(('_default', default, remainder)) lookup = getattr(obj, '_lookup', None) if iscontroller(lookup): notfound_handlers.append(('_lookup', lookup, remainder)) route = getattr(obj, '_route', None) if iscontroller(route): if len(getargspec(route).args) == 2: warnings.warn( ( "The function signature for %s.%s._route is changing " "in the next version of pecan.\nPlease update to: " "`def _route(self, args, request)`." % ( obj.__class__.__module__, obj.__class__.__name__ ) ), DeprecationWarning ) next_obj, next_remainder = route(remainder) else: next_obj, next_remainder = route(remainder, request) cross_boundary(route, next_obj) return next_obj, next_remainder if not remainder: raise PecanNotFound prev_remainder = remainder prev_obj = obj remainder = rest try: obj = getattr(obj, next_obj, None) except UnicodeEncodeError: obj = None # Last-ditch effort: if there's not a matching subcontroller, no # `_default`, no `_lookup`, and no `_route`, look to see if there's # an `index` that has a generic method defined for the current request # method. if not obj and not notfound_handlers and hasattr(prev_obj, 'index'): if request.method in _cfg(prev_obj.index).get('generic_handlers', {}): return prev_obj.index, prev_remainder
[ "def", "find_object", "(", "obj", ",", "remainder", ",", "notfound_handlers", ",", "request", ")", ":", "prev_obj", "=", "None", "while", "True", ":", "if", "obj", "is", "None", ":", "raise", "PecanNotFound", "if", "iscontroller", "(", "obj", ")", ":", "...
'Walks' the url path in search of an action for which a controller is implemented and returns that controller object along with what's left of the remainder.
[ "Walks", "the", "url", "path", "in", "search", "of", "an", "action", "for", "which", "a", "controller", "is", "implemented", "and", "returns", "that", "controller", "object", "along", "with", "what", "s", "left", "of", "the", "remainder", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/routing.py#L188-L269
train
23,711
pecan/pecan
pecan/secure.py
unlocked
def unlocked(func_or_obj): """ This method unlocks method or class attribute on a SecureController. Can be used to decorate or wrap an attribute """ if ismethod(func_or_obj) or isfunction(func_or_obj): return _unlocked_method(func_or_obj) else: return _UnlockedAttribute(func_or_obj)
python
def unlocked(func_or_obj): """ This method unlocks method or class attribute on a SecureController. Can be used to decorate or wrap an attribute """ if ismethod(func_or_obj) or isfunction(func_or_obj): return _unlocked_method(func_or_obj) else: return _UnlockedAttribute(func_or_obj)
[ "def", "unlocked", "(", "func_or_obj", ")", ":", "if", "ismethod", "(", "func_or_obj", ")", "or", "isfunction", "(", "func_or_obj", ")", ":", "return", "_unlocked_method", "(", "func_or_obj", ")", "else", ":", "return", "_UnlockedAttribute", "(", "func_or_obj", ...
This method unlocks method or class attribute on a SecureController. Can be used to decorate or wrap an attribute
[ "This", "method", "unlocks", "method", "or", "class", "attribute", "on", "a", "SecureController", ".", "Can", "be", "used", "to", "decorate", "or", "wrap", "an", "attribute" ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/secure.py#L101-L109
train
23,712
pecan/pecan
pecan/secure.py
secure
def secure(func_or_obj, check_permissions_for_obj=None): """ This method secures a method or class depending on invocation. To decorate a method use one argument: @secure(<check_permissions_method>) To secure a class, invoke with two arguments: secure(<obj instance>, <check_permissions_method>) """ if _allowed_check_permissions_types(func_or_obj): return _secure_method(func_or_obj) else: if not _allowed_check_permissions_types(check_permissions_for_obj): msg = "When securing an object, secure() requires the " + \ "second argument to be method" raise TypeError(msg) return _SecuredAttribute(func_or_obj, check_permissions_for_obj)
python
def secure(func_or_obj, check_permissions_for_obj=None): """ This method secures a method or class depending on invocation. To decorate a method use one argument: @secure(<check_permissions_method>) To secure a class, invoke with two arguments: secure(<obj instance>, <check_permissions_method>) """ if _allowed_check_permissions_types(func_or_obj): return _secure_method(func_or_obj) else: if not _allowed_check_permissions_types(check_permissions_for_obj): msg = "When securing an object, secure() requires the " + \ "second argument to be method" raise TypeError(msg) return _SecuredAttribute(func_or_obj, check_permissions_for_obj)
[ "def", "secure", "(", "func_or_obj", ",", "check_permissions_for_obj", "=", "None", ")", ":", "if", "_allowed_check_permissions_types", "(", "func_or_obj", ")", ":", "return", "_secure_method", "(", "func_or_obj", ")", "else", ":", "if", "not", "_allowed_check_permi...
This method secures a method or class depending on invocation. To decorate a method use one argument: @secure(<check_permissions_method>) To secure a class, invoke with two arguments: secure(<obj instance>, <check_permissions_method>)
[ "This", "method", "secures", "a", "method", "or", "class", "depending", "on", "invocation", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/secure.py#L112-L129
train
23,713
pecan/pecan
pecan/secure.py
_make_wrapper
def _make_wrapper(f): """return a wrapped function with a copy of the _pecan context""" @wraps(f) def wrapper(*args, **kwargs): return f(*args, **kwargs) wrapper._pecan = f._pecan.copy() return wrapper
python
def _make_wrapper(f): """return a wrapped function with a copy of the _pecan context""" @wraps(f) def wrapper(*args, **kwargs): return f(*args, **kwargs) wrapper._pecan = f._pecan.copy() return wrapper
[ "def", "_make_wrapper", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "wrapper", ".", "_pecan", "=", "f", ...
return a wrapped function with a copy of the _pecan context
[ "return", "a", "wrapped", "function", "with", "a", "copy", "of", "the", "_pecan", "context" ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/secure.py#L195-L201
train
23,714
pecan/pecan
pecan/secure.py
handle_security
def handle_security(controller, im_self=None): """ Checks the security of a controller. """ if controller._pecan.get('secured', False): check_permissions = controller._pecan['check_permissions'] if isinstance(check_permissions, six.string_types): check_permissions = getattr( im_self or six.get_method_self(controller), check_permissions ) if not check_permissions(): raise exc.HTTPUnauthorized
python
def handle_security(controller, im_self=None): """ Checks the security of a controller. """ if controller._pecan.get('secured', False): check_permissions = controller._pecan['check_permissions'] if isinstance(check_permissions, six.string_types): check_permissions = getattr( im_self or six.get_method_self(controller), check_permissions ) if not check_permissions(): raise exc.HTTPUnauthorized
[ "def", "handle_security", "(", "controller", ",", "im_self", "=", "None", ")", ":", "if", "controller", ".", "_pecan", ".", "get", "(", "'secured'", ",", "False", ")", ":", "check_permissions", "=", "controller", ".", "_pecan", "[", "'check_permissions'", "]...
Checks the security of a controller.
[ "Checks", "the", "security", "of", "a", "controller", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/secure.py#L205-L217
train
23,715
pecan/pecan
pecan/secure.py
cross_boundary
def cross_boundary(prev_obj, obj): """ Check permissions as we move between object instances. """ if prev_obj is None: return if isinstance(obj, _SecuredAttribute): # a secure attribute can live in unsecure class so we have to set # while we walk the route obj.parent = prev_obj if hasattr(prev_obj, '_pecan'): if obj not in prev_obj._pecan.get('unlocked', []): handle_security(prev_obj)
python
def cross_boundary(prev_obj, obj): """ Check permissions as we move between object instances. """ if prev_obj is None: return if isinstance(obj, _SecuredAttribute): # a secure attribute can live in unsecure class so we have to set # while we walk the route obj.parent = prev_obj if hasattr(prev_obj, '_pecan'): if obj not in prev_obj._pecan.get('unlocked', []): handle_security(prev_obj)
[ "def", "cross_boundary", "(", "prev_obj", ",", "obj", ")", ":", "if", "prev_obj", "is", "None", ":", "return", "if", "isinstance", "(", "obj", ",", "_SecuredAttribute", ")", ":", "# a secure attribute can live in unsecure class so we have to set", "# while we walk the r...
Check permissions as we move between object instances.
[ "Check", "permissions", "as", "we", "move", "between", "object", "instances", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/secure.py#L220-L232
train
23,716
pecan/pecan
pecan/scaffolds/__init__.py
makedirs
def makedirs(directory): """ Resursively create a named directory. """ parent = os.path.dirname(os.path.abspath(directory)) if not os.path.exists(parent): makedirs(parent) os.mkdir(directory)
python
def makedirs(directory): """ Resursively create a named directory. """ parent = os.path.dirname(os.path.abspath(directory)) if not os.path.exists(parent): makedirs(parent) os.mkdir(directory)
[ "def", "makedirs", "(", "directory", ")", ":", "parent", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "directory", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "parent", ")", ":", "makedirs",...
Resursively create a named directory.
[ "Resursively", "create", "a", "named", "directory", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/scaffolds/__init__.py#L105-L110
train
23,717
pecan/pecan
pecan/scaffolds/__init__.py
substitute_filename
def substitute_filename(fn, variables): """ Substitute +variables+ in file directory names. """ for var, value in variables.items(): fn = fn.replace('+%s+' % var, str(value)) return fn
python
def substitute_filename(fn, variables): """ Substitute +variables+ in file directory names. """ for var, value in variables.items(): fn = fn.replace('+%s+' % var, str(value)) return fn
[ "def", "substitute_filename", "(", "fn", ",", "variables", ")", ":", "for", "var", ",", "value", "in", "variables", ".", "items", "(", ")", ":", "fn", "=", "fn", ".", "replace", "(", "'+%s+'", "%", "var", ",", "str", "(", "value", ")", ")", "return...
Substitute +variables+ in file directory names.
[ "Substitute", "+", "variables", "+", "in", "file", "directory", "names", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/scaffolds/__init__.py#L113-L117
train
23,718
pecan/pecan
pecan/__init__.py
make_app
def make_app(root, **kw): ''' Utility for creating the Pecan application object. This function should generally be called from the ``setup_app`` function in your project's ``app.py`` file. :param root: A string representing a root controller object (e.g., "myapp.controller.root.RootController") :param static_root: The relative path to a directory containing static files. Serving static files is only enabled when debug mode is set. :param debug: A flag to enable debug mode. This enables the debug middleware and serving static files. :param wrap_app: A function or middleware class to wrap the Pecan app. This must either be a wsgi middleware class or a function that returns a wsgi application. This wrapper is applied first before wrapping the application in other middlewares such as Pecan's debug middleware. This should be used if you want to use middleware to perform authentication or intercept all requests before they are routed to the root controller. :param logging: A dictionary used to configure logging. This uses ``logging.config.dictConfig``. All other keyword arguments are passed in to the Pecan app constructor. :returns: a ``Pecan`` object. ''' # Pass logging configuration (if it exists) on to the Python logging module logging = kw.get('logging', {}) debug = kw.get('debug', False) if logging: if debug: try: # # By default, Python 2.7+ silences DeprecationWarnings. # However, if conf.app.debug is True, we should probably ensure # that users see these types of warnings. # from logging import captureWarnings captureWarnings(True) warnings.simplefilter("default", DeprecationWarning) except ImportError: # No captureWarnings on Python 2.6, DeprecationWarnings are on pass if isinstance(logging, Config): logging = logging.to_dict() if 'version' not in logging: logging['version'] = 1 load_logging_config(logging) # Instantiate the WSGI app by passing **kw onward app = Pecan(root, **kw) # Optionally wrap the app in another WSGI app wrap_app = kw.get('wrap_app', None) if wrap_app: app = wrap_app(app) # Configuration for serving custom error messages errors = kw.get('errors', getattr(conf.app, 'errors', {})) if errors: app = middleware.errordocument.ErrorDocumentMiddleware(app, errors) # Included for internal redirect support app = middleware.recursive.RecursiveMiddleware(app) # When in debug mode, load exception debugging middleware static_root = kw.get('static_root', None) if debug: debug_kwargs = getattr(conf, 'debug', {}) debug_kwargs.setdefault('context_injectors', []).append( lambda environ: { 'request': environ.get('pecan.locals', {}).get('request') } ) app = DebugMiddleware( app, **debug_kwargs ) # Support for serving static files (for development convenience) if static_root: app = middleware.static.StaticFileMiddleware(app, static_root) elif static_root: warnings.warn( "`static_root` is only used when `debug` is True, ignoring", RuntimeWarning ) if hasattr(conf, 'requestviewer'): warnings.warn(''.join([ "`pecan.conf.requestviewer` is deprecated. To apply the ", "`RequestViewerHook` to your application, add it to ", "`pecan.conf.app.hooks` or manually in your project's `app.py` ", "file."]), DeprecationWarning ) return app
python
def make_app(root, **kw): ''' Utility for creating the Pecan application object. This function should generally be called from the ``setup_app`` function in your project's ``app.py`` file. :param root: A string representing a root controller object (e.g., "myapp.controller.root.RootController") :param static_root: The relative path to a directory containing static files. Serving static files is only enabled when debug mode is set. :param debug: A flag to enable debug mode. This enables the debug middleware and serving static files. :param wrap_app: A function or middleware class to wrap the Pecan app. This must either be a wsgi middleware class or a function that returns a wsgi application. This wrapper is applied first before wrapping the application in other middlewares such as Pecan's debug middleware. This should be used if you want to use middleware to perform authentication or intercept all requests before they are routed to the root controller. :param logging: A dictionary used to configure logging. This uses ``logging.config.dictConfig``. All other keyword arguments are passed in to the Pecan app constructor. :returns: a ``Pecan`` object. ''' # Pass logging configuration (if it exists) on to the Python logging module logging = kw.get('logging', {}) debug = kw.get('debug', False) if logging: if debug: try: # # By default, Python 2.7+ silences DeprecationWarnings. # However, if conf.app.debug is True, we should probably ensure # that users see these types of warnings. # from logging import captureWarnings captureWarnings(True) warnings.simplefilter("default", DeprecationWarning) except ImportError: # No captureWarnings on Python 2.6, DeprecationWarnings are on pass if isinstance(logging, Config): logging = logging.to_dict() if 'version' not in logging: logging['version'] = 1 load_logging_config(logging) # Instantiate the WSGI app by passing **kw onward app = Pecan(root, **kw) # Optionally wrap the app in another WSGI app wrap_app = kw.get('wrap_app', None) if wrap_app: app = wrap_app(app) # Configuration for serving custom error messages errors = kw.get('errors', getattr(conf.app, 'errors', {})) if errors: app = middleware.errordocument.ErrorDocumentMiddleware(app, errors) # Included for internal redirect support app = middleware.recursive.RecursiveMiddleware(app) # When in debug mode, load exception debugging middleware static_root = kw.get('static_root', None) if debug: debug_kwargs = getattr(conf, 'debug', {}) debug_kwargs.setdefault('context_injectors', []).append( lambda environ: { 'request': environ.get('pecan.locals', {}).get('request') } ) app = DebugMiddleware( app, **debug_kwargs ) # Support for serving static files (for development convenience) if static_root: app = middleware.static.StaticFileMiddleware(app, static_root) elif static_root: warnings.warn( "`static_root` is only used when `debug` is True, ignoring", RuntimeWarning ) if hasattr(conf, 'requestviewer'): warnings.warn(''.join([ "`pecan.conf.requestviewer` is deprecated. To apply the ", "`RequestViewerHook` to your application, add it to ", "`pecan.conf.app.hooks` or manually in your project's `app.py` ", "file."]), DeprecationWarning ) return app
[ "def", "make_app", "(", "root", ",", "*", "*", "kw", ")", ":", "# Pass logging configuration (if it exists) on to the Python logging module", "logging", "=", "kw", ".", "get", "(", "'logging'", ",", "{", "}", ")", "debug", "=", "kw", ".", "get", "(", "'debug'"...
Utility for creating the Pecan application object. This function should generally be called from the ``setup_app`` function in your project's ``app.py`` file. :param root: A string representing a root controller object (e.g., "myapp.controller.root.RootController") :param static_root: The relative path to a directory containing static files. Serving static files is only enabled when debug mode is set. :param debug: A flag to enable debug mode. This enables the debug middleware and serving static files. :param wrap_app: A function or middleware class to wrap the Pecan app. This must either be a wsgi middleware class or a function that returns a wsgi application. This wrapper is applied first before wrapping the application in other middlewares such as Pecan's debug middleware. This should be used if you want to use middleware to perform authentication or intercept all requests before they are routed to the root controller. :param logging: A dictionary used to configure logging. This uses ``logging.config.dictConfig``. All other keyword arguments are passed in to the Pecan app constructor. :returns: a ``Pecan`` object.
[ "Utility", "for", "creating", "the", "Pecan", "application", "object", ".", "This", "function", "should", "generally", "be", "called", "from", "the", "setup_app", "function", "in", "your", "project", "s", "app", ".", "py", "file", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/__init__.py#L33-L134
train
23,719
pecan/pecan
pecan/configuration.py
conf_from_file
def conf_from_file(filepath): ''' Creates a configuration dictionary from a file. :param filepath: The path to the file. ''' abspath = os.path.abspath(os.path.expanduser(filepath)) conf_dict = {} if not os.path.isfile(abspath): raise RuntimeError('`%s` is not a file.' % abspath) # First, make sure the code will actually compile (and has no SyntaxErrors) with open(abspath, 'rb') as f: compiled = compile(f.read(), abspath, 'exec') # Next, attempt to actually import the file as a module. # This provides more verbose import-related error reporting than exec() absname, _ = os.path.splitext(abspath) basepath, module_name = absname.rsplit(os.sep, 1) if six.PY3: SourceFileLoader(module_name, abspath).load_module(module_name) else: imp.load_module( module_name, *imp.find_module(module_name, [basepath]) ) # If we were able to import as a module, actually exec the compiled code exec(compiled, globals(), conf_dict) conf_dict['__file__'] = abspath return conf_from_dict(conf_dict)
python
def conf_from_file(filepath): ''' Creates a configuration dictionary from a file. :param filepath: The path to the file. ''' abspath = os.path.abspath(os.path.expanduser(filepath)) conf_dict = {} if not os.path.isfile(abspath): raise RuntimeError('`%s` is not a file.' % abspath) # First, make sure the code will actually compile (and has no SyntaxErrors) with open(abspath, 'rb') as f: compiled = compile(f.read(), abspath, 'exec') # Next, attempt to actually import the file as a module. # This provides more verbose import-related error reporting than exec() absname, _ = os.path.splitext(abspath) basepath, module_name = absname.rsplit(os.sep, 1) if six.PY3: SourceFileLoader(module_name, abspath).load_module(module_name) else: imp.load_module( module_name, *imp.find_module(module_name, [basepath]) ) # If we were able to import as a module, actually exec the compiled code exec(compiled, globals(), conf_dict) conf_dict['__file__'] = abspath return conf_from_dict(conf_dict)
[ "def", "conf_from_file", "(", "filepath", ")", ":", "abspath", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "filepath", ")", ")", "conf_dict", "=", "{", "}", "if", "not", "os", ".", "path", ".", "isfile", ...
Creates a configuration dictionary from a file. :param filepath: The path to the file.
[ "Creates", "a", "configuration", "dictionary", "from", "a", "file", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/configuration.py#L154-L186
train
23,720
pecan/pecan
pecan/configuration.py
get_conf_path_from_env
def get_conf_path_from_env(): ''' If the ``PECAN_CONFIG`` environment variable exists and it points to a valid path it will return that, otherwise it will raise a ``RuntimeError``. ''' config_path = os.environ.get('PECAN_CONFIG') if not config_path: error = "PECAN_CONFIG is not set and " \ "no config file was passed as an argument." elif not os.path.isfile(config_path): error = "PECAN_CONFIG was set to an invalid path: %s" % config_path else: return config_path raise RuntimeError(error)
python
def get_conf_path_from_env(): ''' If the ``PECAN_CONFIG`` environment variable exists and it points to a valid path it will return that, otherwise it will raise a ``RuntimeError``. ''' config_path = os.environ.get('PECAN_CONFIG') if not config_path: error = "PECAN_CONFIG is not set and " \ "no config file was passed as an argument." elif not os.path.isfile(config_path): error = "PECAN_CONFIG was set to an invalid path: %s" % config_path else: return config_path raise RuntimeError(error)
[ "def", "get_conf_path_from_env", "(", ")", ":", "config_path", "=", "os", ".", "environ", ".", "get", "(", "'PECAN_CONFIG'", ")", "if", "not", "config_path", ":", "error", "=", "\"PECAN_CONFIG is not set and \"", "\"no config file was passed as an argument.\"", "elif", ...
If the ``PECAN_CONFIG`` environment variable exists and it points to a valid path it will return that, otherwise it will raise a ``RuntimeError``.
[ "If", "the", "PECAN_CONFIG", "environment", "variable", "exists", "and", "it", "points", "to", "a", "valid", "path", "it", "will", "return", "that", "otherwise", "it", "will", "raise", "a", "RuntimeError", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/configuration.py#L189-L204
train
23,721
pecan/pecan
pecan/configuration.py
conf_from_dict
def conf_from_dict(conf_dict): ''' Creates a configuration dictionary from a dictionary. :param conf_dict: The configuration dictionary. ''' conf = Config(filename=conf_dict.get('__file__', '')) for k, v in six.iteritems(conf_dict): if k.startswith('__'): continue elif inspect.ismodule(v): continue conf[k] = v return conf
python
def conf_from_dict(conf_dict): ''' Creates a configuration dictionary from a dictionary. :param conf_dict: The configuration dictionary. ''' conf = Config(filename=conf_dict.get('__file__', '')) for k, v in six.iteritems(conf_dict): if k.startswith('__'): continue elif inspect.ismodule(v): continue conf[k] = v return conf
[ "def", "conf_from_dict", "(", "conf_dict", ")", ":", "conf", "=", "Config", "(", "filename", "=", "conf_dict", ".", "get", "(", "'__file__'", ",", "''", ")", ")", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "conf_dict", ")", ":", "if", ...
Creates a configuration dictionary from a dictionary. :param conf_dict: The configuration dictionary.
[ "Creates", "a", "configuration", "dictionary", "from", "a", "dictionary", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/configuration.py#L207-L222
train
23,722
pecan/pecan
pecan/configuration.py
set_config
def set_config(config, overwrite=False): ''' Updates the global configuration. :param config: Can be a dictionary containing configuration, or a string which represents a (relative) configuration filename. ''' if config is None: config = get_conf_path_from_env() # must be after the fallback other a bad fallback will incorrectly clear if overwrite is True: _runtime_conf.empty() if isinstance(config, six.string_types): config = conf_from_file(config) _runtime_conf.update(config) if config.__file__: _runtime_conf.__file__ = config.__file__ elif isinstance(config, dict): _runtime_conf.update(conf_from_dict(config)) else: raise TypeError('%s is neither a dictionary or a string.' % config)
python
def set_config(config, overwrite=False): ''' Updates the global configuration. :param config: Can be a dictionary containing configuration, or a string which represents a (relative) configuration filename. ''' if config is None: config = get_conf_path_from_env() # must be after the fallback other a bad fallback will incorrectly clear if overwrite is True: _runtime_conf.empty() if isinstance(config, six.string_types): config = conf_from_file(config) _runtime_conf.update(config) if config.__file__: _runtime_conf.__file__ = config.__file__ elif isinstance(config, dict): _runtime_conf.update(conf_from_dict(config)) else: raise TypeError('%s is neither a dictionary or a string.' % config)
[ "def", "set_config", "(", "config", ",", "overwrite", "=", "False", ")", ":", "if", "config", "is", "None", ":", "config", "=", "get_conf_path_from_env", "(", ")", "# must be after the fallback other a bad fallback will incorrectly clear", "if", "overwrite", "is", "Tr...
Updates the global configuration. :param config: Can be a dictionary containing configuration, or a string which represents a (relative) configuration filename.
[ "Updates", "the", "global", "configuration", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/configuration.py#L233-L256
train
23,723
pecan/pecan
pecan/configuration.py
Config.update
def update(self, conf_dict): ''' Updates this configuration with a dictionary. :param conf_dict: A python dictionary to update this configuration with. ''' if isinstance(conf_dict, dict): iterator = six.iteritems(conf_dict) else: iterator = iter(conf_dict) for k, v in iterator: if not IDENTIFIER.match(k): raise ValueError('\'%s\' is not a valid indentifier' % k) cur_val = self.__values__.get(k) if isinstance(cur_val, Config): cur_val.update(conf_dict[k]) else: self[k] = conf_dict[k]
python
def update(self, conf_dict): ''' Updates this configuration with a dictionary. :param conf_dict: A python dictionary to update this configuration with. ''' if isinstance(conf_dict, dict): iterator = six.iteritems(conf_dict) else: iterator = iter(conf_dict) for k, v in iterator: if not IDENTIFIER.match(k): raise ValueError('\'%s\' is not a valid indentifier' % k) cur_val = self.__values__.get(k) if isinstance(cur_val, Config): cur_val.update(conf_dict[k]) else: self[k] = conf_dict[k]
[ "def", "update", "(", "self", ",", "conf_dict", ")", ":", "if", "isinstance", "(", "conf_dict", ",", "dict", ")", ":", "iterator", "=", "six", ".", "iteritems", "(", "conf_dict", ")", "else", ":", "iterator", "=", "iter", "(", "conf_dict", ")", "for", ...
Updates this configuration with a dictionary. :param conf_dict: A python dictionary to update this configuration with.
[ "Updates", "this", "configuration", "with", "a", "dictionary", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/configuration.py#L57-L79
train
23,724
pecan/pecan
pecan/configuration.py
Config.to_dict
def to_dict(self, prefix=None): ''' Converts recursively the Config object into a valid dictionary. :param prefix: A string to optionally prefix all key elements in the returned dictonary. ''' conf_obj = dict(self) return self.__dictify__(conf_obj, prefix)
python
def to_dict(self, prefix=None): ''' Converts recursively the Config object into a valid dictionary. :param prefix: A string to optionally prefix all key elements in the returned dictonary. ''' conf_obj = dict(self) return self.__dictify__(conf_obj, prefix)
[ "def", "to_dict", "(", "self", ",", "prefix", "=", "None", ")", ":", "conf_obj", "=", "dict", "(", "self", ")", "return", "self", ".", "__dictify__", "(", "conf_obj", ",", "prefix", ")" ]
Converts recursively the Config object into a valid dictionary. :param prefix: A string to optionally prefix all key elements in the returned dictonary.
[ "Converts", "recursively", "the", "Config", "object", "into", "a", "valid", "dictionary", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/configuration.py#L100-L109
train
23,725
pecan/pecan
pecan/core.py
override_template
def override_template(template, content_type=None): ''' Call within a controller to override the template that is used in your response. :param template: a valid path to a template file, just as you would specify in an ``@expose``. :param content_type: a valid MIME type to use for the response.func_closure ''' request.pecan['override_template'] = template if content_type: request.pecan['override_content_type'] = content_type
python
def override_template(template, content_type=None): ''' Call within a controller to override the template that is used in your response. :param template: a valid path to a template file, just as you would specify in an ``@expose``. :param content_type: a valid MIME type to use for the response.func_closure ''' request.pecan['override_template'] = template if content_type: request.pecan['override_content_type'] = content_type
[ "def", "override_template", "(", "template", ",", "content_type", "=", "None", ")", ":", "request", ".", "pecan", "[", "'override_template'", "]", "=", "template", "if", "content_type", ":", "request", ".", "pecan", "[", "'override_content_type'", "]", "=", "c...
Call within a controller to override the template that is used in your response. :param template: a valid path to a template file, just as you would specify in an ``@expose``. :param content_type: a valid MIME type to use for the response.func_closure
[ "Call", "within", "a", "controller", "to", "override", "the", "template", "that", "is", "used", "in", "your", "response", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/core.py#L98-L110
train
23,726
pecan/pecan
pecan/core.py
abort
def abort(status_code, detail='', headers=None, comment=None, **kw): ''' Raise an HTTP status code, as specified. Useful for returning status codes like 401 Unauthorized or 403 Forbidden. :param status_code: The HTTP status code as an integer. :param detail: The message to send along, as a string. :param headers: A dictionary of headers to send along with the response. :param comment: A comment to include in the response. ''' # If there is a traceback, we need to catch it for a re-raise try: _, _, traceback = sys.exc_info() webob_exception = exc.status_map[status_code]( detail=detail, headers=headers, comment=comment, **kw ) if six.PY3: raise webob_exception.with_traceback(traceback) else: # Using exec to avoid python 3 parsers from crashing exec('raise webob_exception, None, traceback') finally: # Per the suggestion of the Python docs, delete the traceback object del traceback
python
def abort(status_code, detail='', headers=None, comment=None, **kw): ''' Raise an HTTP status code, as specified. Useful for returning status codes like 401 Unauthorized or 403 Forbidden. :param status_code: The HTTP status code as an integer. :param detail: The message to send along, as a string. :param headers: A dictionary of headers to send along with the response. :param comment: A comment to include in the response. ''' # If there is a traceback, we need to catch it for a re-raise try: _, _, traceback = sys.exc_info() webob_exception = exc.status_map[status_code]( detail=detail, headers=headers, comment=comment, **kw ) if six.PY3: raise webob_exception.with_traceback(traceback) else: # Using exec to avoid python 3 parsers from crashing exec('raise webob_exception, None, traceback') finally: # Per the suggestion of the Python docs, delete the traceback object del traceback
[ "def", "abort", "(", "status_code", ",", "detail", "=", "''", ",", "headers", "=", "None", ",", "comment", "=", "None", ",", "*", "*", "kw", ")", ":", "# If there is a traceback, we need to catch it for a re-raise", "try", ":", "_", ",", "_", ",", "traceback...
Raise an HTTP status code, as specified. Useful for returning status codes like 401 Unauthorized or 403 Forbidden. :param status_code: The HTTP status code as an integer. :param detail: The message to send along, as a string. :param headers: A dictionary of headers to send along with the response. :param comment: A comment to include in the response.
[ "Raise", "an", "HTTP", "status", "code", "as", "specified", ".", "Useful", "for", "returning", "status", "codes", "like", "401", "Unauthorized", "or", "403", "Forbidden", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/core.py#L113-L141
train
23,727
pecan/pecan
pecan/core.py
redirect
def redirect(location=None, internal=False, code=None, headers={}, add_slash=False, request=None): ''' Perform a redirect, either internal or external. An internal redirect performs the redirect server-side, while the external redirect utilizes an HTTP 302 status code. :param location: The HTTP location to redirect to. :param internal: A boolean indicating whether the redirect should be internal. :param code: The HTTP status code to use for the redirect. Defaults to 302. :param headers: Any HTTP headers to send with the response, as a dictionary. :param request: The :class:`pecan.Request` instance to use. ''' request = request or state.request if add_slash: if location is None: split_url = list(urlparse.urlsplit(request.url)) new_proto = request.environ.get( 'HTTP_X_FORWARDED_PROTO', split_url[0] ) split_url[0] = new_proto else: split_url = urlparse.urlsplit(location) split_url[2] = split_url[2].rstrip('/') + '/' location = urlparse.urlunsplit(split_url) if not headers: headers = {} if internal: if code is not None: raise ValueError('Cannot specify a code for internal redirects') request.environ['pecan.recursive.context'] = request.context raise ForwardRequestException(location) if code is None: code = 302 raise exc.status_map[code](location=location, headers=headers)
python
def redirect(location=None, internal=False, code=None, headers={}, add_slash=False, request=None): ''' Perform a redirect, either internal or external. An internal redirect performs the redirect server-side, while the external redirect utilizes an HTTP 302 status code. :param location: The HTTP location to redirect to. :param internal: A boolean indicating whether the redirect should be internal. :param code: The HTTP status code to use for the redirect. Defaults to 302. :param headers: Any HTTP headers to send with the response, as a dictionary. :param request: The :class:`pecan.Request` instance to use. ''' request = request or state.request if add_slash: if location is None: split_url = list(urlparse.urlsplit(request.url)) new_proto = request.environ.get( 'HTTP_X_FORWARDED_PROTO', split_url[0] ) split_url[0] = new_proto else: split_url = urlparse.urlsplit(location) split_url[2] = split_url[2].rstrip('/') + '/' location = urlparse.urlunsplit(split_url) if not headers: headers = {} if internal: if code is not None: raise ValueError('Cannot specify a code for internal redirects') request.environ['pecan.recursive.context'] = request.context raise ForwardRequestException(location) if code is None: code = 302 raise exc.status_map[code](location=location, headers=headers)
[ "def", "redirect", "(", "location", "=", "None", ",", "internal", "=", "False", ",", "code", "=", "None", ",", "headers", "=", "{", "}", ",", "add_slash", "=", "False", ",", "request", "=", "None", ")", ":", "request", "=", "request", "or", "state", ...
Perform a redirect, either internal or external. An internal redirect performs the redirect server-side, while the external redirect utilizes an HTTP 302 status code. :param location: The HTTP location to redirect to. :param internal: A boolean indicating whether the redirect should be internal. :param code: The HTTP status code to use for the redirect. Defaults to 302. :param headers: Any HTTP headers to send with the response, as a dictionary. :param request: The :class:`pecan.Request` instance to use.
[ "Perform", "a", "redirect", "either", "internal", "or", "external", ".", "An", "internal", "redirect", "performs", "the", "redirect", "server", "-", "side", "while", "the", "external", "redirect", "utilizes", "an", "HTTP", "302", "status", "code", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/core.py#L144-L183
train
23,728
pecan/pecan
pecan/core.py
load_app
def load_app(config, **kwargs): ''' Used to load a ``Pecan`` application and its environment based on passed configuration. :param config: Can be a dictionary containing configuration, a string which represents a (relative) configuration filename returns a pecan.Pecan object ''' from .configuration import _runtime_conf, set_config set_config(config, overwrite=True) for package_name in getattr(_runtime_conf.app, 'modules', []): module = __import__(package_name, fromlist=['app']) if hasattr(module, 'app') and hasattr(module.app, 'setup_app'): app = module.app.setup_app(_runtime_conf, **kwargs) app.config = _runtime_conf return app raise RuntimeError( 'No app.setup_app found in any of the configured app.modules' )
python
def load_app(config, **kwargs): ''' Used to load a ``Pecan`` application and its environment based on passed configuration. :param config: Can be a dictionary containing configuration, a string which represents a (relative) configuration filename returns a pecan.Pecan object ''' from .configuration import _runtime_conf, set_config set_config(config, overwrite=True) for package_name in getattr(_runtime_conf.app, 'modules', []): module = __import__(package_name, fromlist=['app']) if hasattr(module, 'app') and hasattr(module.app, 'setup_app'): app = module.app.setup_app(_runtime_conf, **kwargs) app.config = _runtime_conf return app raise RuntimeError( 'No app.setup_app found in any of the configured app.modules' )
[ "def", "load_app", "(", "config", ",", "*", "*", "kwargs", ")", ":", "from", ".", "configuration", "import", "_runtime_conf", ",", "set_config", "set_config", "(", "config", ",", "overwrite", "=", "True", ")", "for", "package_name", "in", "getattr", "(", "...
Used to load a ``Pecan`` application and its environment based on passed configuration. :param config: Can be a dictionary containing configuration, a string which represents a (relative) configuration filename returns a pecan.Pecan object
[ "Used", "to", "load", "a", "Pecan", "application", "and", "its", "environment", "based", "on", "passed", "configuration", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/core.py#L202-L223
train
23,729
pecan/pecan
pecan/core.py
PecanBase.route
def route(self, req, node, path): ''' Looks up a controller from a node based upon the specified path. :param node: The node, such as a root controller object. :param path: The path to look up on this node. ''' path = path.split('/')[1:] try: node, remainder = lookup_controller(node, path, req) return node, remainder except NonCanonicalPath as e: if self.force_canonical and \ not _cfg(e.controller).get('accept_noncanonical', False): if req.method == 'POST': raise RuntimeError( "You have POSTed to a URL '%s' which " "requires a slash. Most browsers will not maintain " "POST data when redirected. Please update your code " "to POST to '%s/' or set force_canonical to False" % (req.pecan['routing_path'], req.pecan['routing_path']) ) redirect(code=302, add_slash=True, request=req) return e.controller, e.remainder
python
def route(self, req, node, path): ''' Looks up a controller from a node based upon the specified path. :param node: The node, such as a root controller object. :param path: The path to look up on this node. ''' path = path.split('/')[1:] try: node, remainder = lookup_controller(node, path, req) return node, remainder except NonCanonicalPath as e: if self.force_canonical and \ not _cfg(e.controller).get('accept_noncanonical', False): if req.method == 'POST': raise RuntimeError( "You have POSTed to a URL '%s' which " "requires a slash. Most browsers will not maintain " "POST data when redirected. Please update your code " "to POST to '%s/' or set force_canonical to False" % (req.pecan['routing_path'], req.pecan['routing_path']) ) redirect(code=302, add_slash=True, request=req) return e.controller, e.remainder
[ "def", "route", "(", "self", ",", "req", ",", "node", ",", "path", ")", ":", "path", "=", "path", ".", "split", "(", "'/'", ")", "[", "1", ":", "]", "try", ":", "node", ",", "remainder", "=", "lookup_controller", "(", "node", ",", "path", ",", ...
Looks up a controller from a node based upon the specified path. :param node: The node, such as a root controller object. :param path: The path to look up on this node.
[ "Looks", "up", "a", "controller", "from", "a", "node", "based", "upon", "the", "specified", "path", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/core.py#L284-L308
train
23,730
pecan/pecan
pecan/core.py
PecanBase.determine_hooks
def determine_hooks(self, controller=None): ''' Determines the hooks to be run, in which order. :param controller: If specified, includes hooks for a specific controller. ''' controller_hooks = [] if controller: controller_hooks = _cfg(controller).get('hooks', []) if controller_hooks: return list( sorted( chain(controller_hooks, self.hooks), key=operator.attrgetter('priority') ) ) return self.hooks
python
def determine_hooks(self, controller=None): ''' Determines the hooks to be run, in which order. :param controller: If specified, includes hooks for a specific controller. ''' controller_hooks = [] if controller: controller_hooks = _cfg(controller).get('hooks', []) if controller_hooks: return list( sorted( chain(controller_hooks, self.hooks), key=operator.attrgetter('priority') ) ) return self.hooks
[ "def", "determine_hooks", "(", "self", ",", "controller", "=", "None", ")", ":", "controller_hooks", "=", "[", "]", "if", "controller", ":", "controller_hooks", "=", "_cfg", "(", "controller", ")", ".", "get", "(", "'hooks'", ",", "[", "]", ")", "if", ...
Determines the hooks to be run, in which order. :param controller: If specified, includes hooks for a specific controller.
[ "Determines", "the", "hooks", "to", "be", "run", "in", "which", "order", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/core.py#L310-L328
train
23,731
pecan/pecan
pecan/core.py
PecanBase.handle_hooks
def handle_hooks(self, hooks, hook_type, *args): ''' Processes hooks of the specified type. :param hook_type: The type of hook, including ``before``, ``after``, ``on_error``, and ``on_route``. :param \*args: Arguments to pass to the hooks. ''' if hook_type not in ['before', 'on_route']: hooks = reversed(hooks) for hook in hooks: result = getattr(hook, hook_type)(*args) # on_error hooks can choose to return a Response, which will # be used instead of the standard error pages. if hook_type == 'on_error' and isinstance(result, WebObResponse): return result
python
def handle_hooks(self, hooks, hook_type, *args): ''' Processes hooks of the specified type. :param hook_type: The type of hook, including ``before``, ``after``, ``on_error``, and ``on_route``. :param \*args: Arguments to pass to the hooks. ''' if hook_type not in ['before', 'on_route']: hooks = reversed(hooks) for hook in hooks: result = getattr(hook, hook_type)(*args) # on_error hooks can choose to return a Response, which will # be used instead of the standard error pages. if hook_type == 'on_error' and isinstance(result, WebObResponse): return result
[ "def", "handle_hooks", "(", "self", ",", "hooks", ",", "hook_type", ",", "*", "args", ")", ":", "if", "hook_type", "not", "in", "[", "'before'", ",", "'on_route'", "]", ":", "hooks", "=", "reversed", "(", "hooks", ")", "for", "hook", "in", "hooks", "...
Processes hooks of the specified type. :param hook_type: The type of hook, including ``before``, ``after``, ``on_error``, and ``on_route``. :param \*args: Arguments to pass to the hooks.
[ "Processes", "hooks", "of", "the", "specified", "type", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/core.py#L330-L346
train
23,732
pecan/pecan
pecan/core.py
PecanBase.get_args
def get_args(self, state, all_params, remainder, argspec, im_self): ''' Determines the arguments for a controller based upon parameters passed the argument specification for the controller. ''' args = [] varargs = [] kwargs = dict() valid_args = argspec.args[:] if ismethod(state.controller) or im_self: valid_args.pop(0) # pop off `self` pecan_state = state.request.pecan remainder = [x for x in remainder if x] if im_self is not None: args.append(im_self) # grab the routing args from nested REST controllers if 'routing_args' in pecan_state: remainder = pecan_state['routing_args'] + list(remainder) del pecan_state['routing_args'] # handle positional arguments if valid_args and remainder: args.extend(remainder[:len(valid_args)]) remainder = remainder[len(valid_args):] valid_args = valid_args[len(args):] # handle wildcard arguments if [i for i in remainder if i]: if not argspec[1]: abort(404) varargs.extend(remainder) # get the default positional arguments if argspec[3]: defaults = dict(izip(argspec[0][-len(argspec[3]):], argspec[3])) else: defaults = dict() # handle positional GET/POST params for name in valid_args: if name in all_params: args.append(all_params.pop(name)) elif name in defaults: args.append(defaults[name]) else: break # handle wildcard GET/POST params if argspec[2]: for name, value in six.iteritems(all_params): if name not in argspec[0]: kwargs[name] = value return args, varargs, kwargs
python
def get_args(self, state, all_params, remainder, argspec, im_self): ''' Determines the arguments for a controller based upon parameters passed the argument specification for the controller. ''' args = [] varargs = [] kwargs = dict() valid_args = argspec.args[:] if ismethod(state.controller) or im_self: valid_args.pop(0) # pop off `self` pecan_state = state.request.pecan remainder = [x for x in remainder if x] if im_self is not None: args.append(im_self) # grab the routing args from nested REST controllers if 'routing_args' in pecan_state: remainder = pecan_state['routing_args'] + list(remainder) del pecan_state['routing_args'] # handle positional arguments if valid_args and remainder: args.extend(remainder[:len(valid_args)]) remainder = remainder[len(valid_args):] valid_args = valid_args[len(args):] # handle wildcard arguments if [i for i in remainder if i]: if not argspec[1]: abort(404) varargs.extend(remainder) # get the default positional arguments if argspec[3]: defaults = dict(izip(argspec[0][-len(argspec[3]):], argspec[3])) else: defaults = dict() # handle positional GET/POST params for name in valid_args: if name in all_params: args.append(all_params.pop(name)) elif name in defaults: args.append(defaults[name]) else: break # handle wildcard GET/POST params if argspec[2]: for name, value in six.iteritems(all_params): if name not in argspec[0]: kwargs[name] = value return args, varargs, kwargs
[ "def", "get_args", "(", "self", ",", "state", ",", "all_params", ",", "remainder", ",", "argspec", ",", "im_self", ")", ":", "args", "=", "[", "]", "varargs", "=", "[", "]", "kwargs", "=", "dict", "(", ")", "valid_args", "=", "argspec", ".", "args", ...
Determines the arguments for a controller based upon parameters passed the argument specification for the controller.
[ "Determines", "the", "arguments", "for", "a", "controller", "based", "upon", "parameters", "passed", "the", "argument", "specification", "for", "the", "controller", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/core.py#L348-L404
train
23,733
pecan/pecan
pecan/commands/shell.py
ShellCommand.run
def run(self, args): """ Load the pecan app, prepare the locals, sets the banner, and invokes the python shell. """ super(ShellCommand, self).run(args) # load the application app = self.load_app() # prepare the locals locs = dict(__name__='pecan-admin') locs['wsgiapp'] = app locs['app'] = TestApp(app) model = self.load_model(app.config) if model: locs['model'] = model # insert the pecan locals from pecan import abort, conf, redirect, request, response locs['abort'] = abort locs['conf'] = conf locs['redirect'] = redirect locs['request'] = request locs['response'] = response # prepare the banner banner = ' The following objects are available:\n' banner += ' %-10s - This project\'s WSGI App instance\n' % 'wsgiapp' banner += ' %-10s - The current configuration\n' % 'conf' banner += ' %-10s - webtest.TestApp wrapped around wsgiapp\n' % 'app' if model: model_name = getattr( model, '__module__', getattr(model, '__name__', 'model') ) banner += ' %-10s - Models from %s\n' % ('model', model_name) self.invoke_shell(locs, banner)
python
def run(self, args): """ Load the pecan app, prepare the locals, sets the banner, and invokes the python shell. """ super(ShellCommand, self).run(args) # load the application app = self.load_app() # prepare the locals locs = dict(__name__='pecan-admin') locs['wsgiapp'] = app locs['app'] = TestApp(app) model = self.load_model(app.config) if model: locs['model'] = model # insert the pecan locals from pecan import abort, conf, redirect, request, response locs['abort'] = abort locs['conf'] = conf locs['redirect'] = redirect locs['request'] = request locs['response'] = response # prepare the banner banner = ' The following objects are available:\n' banner += ' %-10s - This project\'s WSGI App instance\n' % 'wsgiapp' banner += ' %-10s - The current configuration\n' % 'conf' banner += ' %-10s - webtest.TestApp wrapped around wsgiapp\n' % 'app' if model: model_name = getattr( model, '__module__', getattr(model, '__name__', 'model') ) banner += ' %-10s - Models from %s\n' % ('model', model_name) self.invoke_shell(locs, banner)
[ "def", "run", "(", "self", ",", "args", ")", ":", "super", "(", "ShellCommand", ",", "self", ")", ".", "run", "(", "args", ")", "# load the application", "app", "=", "self", ".", "load_app", "(", ")", "# prepare the locals", "locs", "=", "dict", "(", "...
Load the pecan app, prepare the locals, sets the banner, and invokes the python shell.
[ "Load", "the", "pecan", "app", "prepare", "the", "locals", "sets", "the", "banner", "and", "invokes", "the", "python", "shell", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/commands/shell.py#L108-L148
train
23,734
pecan/pecan
pecan/commands/shell.py
ShellCommand.load_model
def load_model(self, config): """ Load the model extension module """ for package_name in getattr(config.app, 'modules', []): module = __import__(package_name, fromlist=['model']) if hasattr(module, 'model'): return module.model return None
python
def load_model(self, config): """ Load the model extension module """ for package_name in getattr(config.app, 'modules', []): module = __import__(package_name, fromlist=['model']) if hasattr(module, 'model'): return module.model return None
[ "def", "load_model", "(", "self", ",", "config", ")", ":", "for", "package_name", "in", "getattr", "(", "config", ".", "app", ",", "'modules'", ",", "[", "]", ")", ":", "module", "=", "__import__", "(", "package_name", ",", "fromlist", "=", "[", "'mode...
Load the model extension module
[ "Load", "the", "model", "extension", "module" ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/commands/shell.py#L169-L177
train
23,735
pecan/pecan
pecan/rest.py
RestController._handle_bad_rest_arguments
def _handle_bad_rest_arguments(self, controller, remainder, request): """ Ensure that the argspec for a discovered controller actually matched the positional arguments in the request path. If not, raise a webob.exc.HTTPBadRequest. """ argspec = self._get_args_for_controller(controller) fixed_args = len(argspec) - len( request.pecan.get('routing_args', []) ) if len(remainder) < fixed_args: # For controllers that are missing intermediate IDs # (e.g., /authors/books vs /authors/1/books), return a 404 for an # invalid path. abort(404)
python
def _handle_bad_rest_arguments(self, controller, remainder, request): """ Ensure that the argspec for a discovered controller actually matched the positional arguments in the request path. If not, raise a webob.exc.HTTPBadRequest. """ argspec = self._get_args_for_controller(controller) fixed_args = len(argspec) - len( request.pecan.get('routing_args', []) ) if len(remainder) < fixed_args: # For controllers that are missing intermediate IDs # (e.g., /authors/books vs /authors/1/books), return a 404 for an # invalid path. abort(404)
[ "def", "_handle_bad_rest_arguments", "(", "self", ",", "controller", ",", "remainder", ",", "request", ")", ":", "argspec", "=", "self", ".", "_get_args_for_controller", "(", "controller", ")", "fixed_args", "=", "len", "(", "argspec", ")", "-", "len", "(", ...
Ensure that the argspec for a discovered controller actually matched the positional arguments in the request path. If not, raise a webob.exc.HTTPBadRequest.
[ "Ensure", "that", "the", "argspec", "for", "a", "discovered", "controller", "actually", "matched", "the", "positional", "arguments", "in", "the", "request", "path", ".", "If", "not", "raise", "a", "webob", ".", "exc", ".", "HTTPBadRequest", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/rest.py#L75-L89
train
23,736
pecan/pecan
pecan/rest.py
RestController._route
def _route(self, args, request=None): ''' Routes a request to the appropriate controller and returns its result. Performs a bit of validation - refuses to route delete and put actions via a GET request). ''' if request is None: from pecan import request # convention uses "_method" to handle browser-unsupported methods method = request.params.get('_method', request.method).lower() # make sure DELETE/PUT requests don't use GET if request.method == 'GET' and method in ('delete', 'put'): abort(405) # check for nested controllers result = self._find_sub_controllers(args, request) if result: return result # handle the request handler = getattr( self, '_handle_%s' % method, self._handle_unknown_method ) try: if len(getargspec(handler).args) == 3: result = handler(method, args) else: result = handler(method, args, request) # # If the signature of the handler does not match the number # of remaining positional arguments, attempt to handle # a _lookup method (if it exists) # argspec = self._get_args_for_controller(result[0]) num_args = len(argspec) if num_args < len(args): _lookup_result = self._handle_lookup(args, request) if _lookup_result: return _lookup_result except (exc.HTTPClientError, exc.HTTPNotFound, exc.HTTPMethodNotAllowed) as e: # # If the matching handler results in a 400, 404, or 405, attempt to # handle a _lookup method (if it exists) # _lookup_result = self._handle_lookup(args, request) if _lookup_result: return _lookup_result # Build a correct Allow: header if isinstance(e, exc.HTTPMethodNotAllowed): def method_iter(): for func in ('get', 'get_one', 'get_all', 'new', 'edit', 'get_delete'): if self._find_controller(func): yield 'GET' break for method in ('HEAD', 'POST', 'PUT', 'DELETE', 'TRACE', 'PATCH'): func = method.lower() if self._find_controller(func): yield method e.allow = sorted(method_iter()) raise # return the result return result
python
def _route(self, args, request=None): ''' Routes a request to the appropriate controller and returns its result. Performs a bit of validation - refuses to route delete and put actions via a GET request). ''' if request is None: from pecan import request # convention uses "_method" to handle browser-unsupported methods method = request.params.get('_method', request.method).lower() # make sure DELETE/PUT requests don't use GET if request.method == 'GET' and method in ('delete', 'put'): abort(405) # check for nested controllers result = self._find_sub_controllers(args, request) if result: return result # handle the request handler = getattr( self, '_handle_%s' % method, self._handle_unknown_method ) try: if len(getargspec(handler).args) == 3: result = handler(method, args) else: result = handler(method, args, request) # # If the signature of the handler does not match the number # of remaining positional arguments, attempt to handle # a _lookup method (if it exists) # argspec = self._get_args_for_controller(result[0]) num_args = len(argspec) if num_args < len(args): _lookup_result = self._handle_lookup(args, request) if _lookup_result: return _lookup_result except (exc.HTTPClientError, exc.HTTPNotFound, exc.HTTPMethodNotAllowed) as e: # # If the matching handler results in a 400, 404, or 405, attempt to # handle a _lookup method (if it exists) # _lookup_result = self._handle_lookup(args, request) if _lookup_result: return _lookup_result # Build a correct Allow: header if isinstance(e, exc.HTTPMethodNotAllowed): def method_iter(): for func in ('get', 'get_one', 'get_all', 'new', 'edit', 'get_delete'): if self._find_controller(func): yield 'GET' break for method in ('HEAD', 'POST', 'PUT', 'DELETE', 'TRACE', 'PATCH'): func = method.lower() if self._find_controller(func): yield method e.allow = sorted(method_iter()) raise # return the result return result
[ "def", "_route", "(", "self", ",", "args", ",", "request", "=", "None", ")", ":", "if", "request", "is", "None", ":", "from", "pecan", "import", "request", "# convention uses \"_method\" to handle browser-unsupported methods", "method", "=", "request", ".", "param...
Routes a request to the appropriate controller and returns its result. Performs a bit of validation - refuses to route delete and put actions via a GET request).
[ "Routes", "a", "request", "to", "the", "appropriate", "controller", "and", "returns", "its", "result", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/rest.py#L103-L178
train
23,737
pecan/pecan
pecan/rest.py
RestController._find_controller
def _find_controller(self, *args): ''' Returns the appropriate controller for routing a custom action. ''' for name in args: obj = self._lookup_child(name) if obj and iscontroller(obj): return obj return None
python
def _find_controller(self, *args): ''' Returns the appropriate controller for routing a custom action. ''' for name in args: obj = self._lookup_child(name) if obj and iscontroller(obj): return obj return None
[ "def", "_find_controller", "(", "self", ",", "*", "args", ")", ":", "for", "name", "in", "args", ":", "obj", "=", "self", ".", "_lookup_child", "(", "name", ")", "if", "obj", "and", "iscontroller", "(", "obj", ")", ":", "return", "obj", "return", "No...
Returns the appropriate controller for routing a custom action.
[ "Returns", "the", "appropriate", "controller", "for", "routing", "a", "custom", "action", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/rest.py#L195-L203
train
23,738
pecan/pecan
pecan/rest.py
RestController._find_sub_controllers
def _find_sub_controllers(self, remainder, request): ''' Identifies the correct controller to route to by analyzing the request URI. ''' # need either a get_one or get to parse args method = None for name in ('get_one', 'get'): if hasattr(self, name): method = name break if not method: return # get the args to figure out how much to chop off args = self._get_args_for_controller(getattr(self, method)) fixed_args = len(args) - len( request.pecan.get('routing_args', []) ) var_args = getargspec(getattr(self, method)).varargs # attempt to locate a sub-controller if var_args: for i, item in enumerate(remainder): controller = self._lookup_child(item) if controller and not ismethod(controller): self._set_routing_args(request, remainder[:i]) return lookup_controller(controller, remainder[i + 1:], request) elif fixed_args < len(remainder) and hasattr( self, remainder[fixed_args] ): controller = self._lookup_child(remainder[fixed_args]) if not ismethod(controller): self._set_routing_args(request, remainder[:fixed_args]) return lookup_controller( controller, remainder[fixed_args + 1:], request )
python
def _find_sub_controllers(self, remainder, request): ''' Identifies the correct controller to route to by analyzing the request URI. ''' # need either a get_one or get to parse args method = None for name in ('get_one', 'get'): if hasattr(self, name): method = name break if not method: return # get the args to figure out how much to chop off args = self._get_args_for_controller(getattr(self, method)) fixed_args = len(args) - len( request.pecan.get('routing_args', []) ) var_args = getargspec(getattr(self, method)).varargs # attempt to locate a sub-controller if var_args: for i, item in enumerate(remainder): controller = self._lookup_child(item) if controller and not ismethod(controller): self._set_routing_args(request, remainder[:i]) return lookup_controller(controller, remainder[i + 1:], request) elif fixed_args < len(remainder) and hasattr( self, remainder[fixed_args] ): controller = self._lookup_child(remainder[fixed_args]) if not ismethod(controller): self._set_routing_args(request, remainder[:fixed_args]) return lookup_controller( controller, remainder[fixed_args + 1:], request )
[ "def", "_find_sub_controllers", "(", "self", ",", "remainder", ",", "request", ")", ":", "# need either a get_one or get to parse args", "method", "=", "None", "for", "name", "in", "(", "'get_one'", ",", "'get'", ")", ":", "if", "hasattr", "(", "self", ",", "n...
Identifies the correct controller to route to by analyzing the request URI.
[ "Identifies", "the", "correct", "controller", "to", "route", "to", "by", "analyzing", "the", "request", "URI", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/rest.py#L205-L244
train
23,739
pecan/pecan
pecan/rest.py
RestController._handle_get
def _handle_get(self, method, remainder, request=None): ''' Routes ``GET`` actions to the appropriate controller. ''' if request is None: self._raise_method_deprecation_warning(self._handle_get) # route to a get_all or get if no additional parts are available if not remainder or remainder == ['']: remainder = list(six.moves.filter(bool, remainder)) controller = self._find_controller('get_all', 'get') if controller: self._handle_bad_rest_arguments(controller, remainder, request) return controller, [] abort(405) method_name = remainder[-1] # check for new/edit/delete GET requests if method_name in ('new', 'edit', 'delete'): if method_name == 'delete': method_name = 'get_delete' controller = self._find_controller(method_name) if controller: return controller, remainder[:-1] match = self._handle_custom_action(method, remainder, request) if match: return match controller = self._lookup_child(remainder[0]) if controller and not ismethod(controller): return lookup_controller(controller, remainder[1:], request) # finally, check for the regular get_one/get requests controller = self._find_controller('get_one', 'get') if controller: self._handle_bad_rest_arguments(controller, remainder, request) return controller, remainder abort(405)
python
def _handle_get(self, method, remainder, request=None): ''' Routes ``GET`` actions to the appropriate controller. ''' if request is None: self._raise_method_deprecation_warning(self._handle_get) # route to a get_all or get if no additional parts are available if not remainder or remainder == ['']: remainder = list(six.moves.filter(bool, remainder)) controller = self._find_controller('get_all', 'get') if controller: self._handle_bad_rest_arguments(controller, remainder, request) return controller, [] abort(405) method_name = remainder[-1] # check for new/edit/delete GET requests if method_name in ('new', 'edit', 'delete'): if method_name == 'delete': method_name = 'get_delete' controller = self._find_controller(method_name) if controller: return controller, remainder[:-1] match = self._handle_custom_action(method, remainder, request) if match: return match controller = self._lookup_child(remainder[0]) if controller and not ismethod(controller): return lookup_controller(controller, remainder[1:], request) # finally, check for the regular get_one/get requests controller = self._find_controller('get_one', 'get') if controller: self._handle_bad_rest_arguments(controller, remainder, request) return controller, remainder abort(405)
[ "def", "_handle_get", "(", "self", ",", "method", ",", "remainder", ",", "request", "=", "None", ")", ":", "if", "request", "is", "None", ":", "self", ".", "_raise_method_deprecation_warning", "(", "self", ".", "_handle_get", ")", "# route to a get_all or get if...
Routes ``GET`` actions to the appropriate controller.
[ "Routes", "GET", "actions", "to", "the", "appropriate", "controller", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/rest.py#L270-L309
train
23,740
pecan/pecan
pecan/rest.py
RestController._handle_delete
def _handle_delete(self, method, remainder, request=None): ''' Routes ``DELETE`` actions to the appropriate controller. ''' if request is None: self._raise_method_deprecation_warning(self._handle_delete) if remainder: match = self._handle_custom_action(method, remainder, request) if match: return match controller = self._lookup_child(remainder[0]) if controller and not ismethod(controller): return lookup_controller(controller, remainder[1:], request) # check for post_delete/delete requests first controller = self._find_controller('post_delete', 'delete') if controller: return controller, remainder # if no controller exists, try routing to a sub-controller; note that # since this is a DELETE verb, any local exposes are 405'd if remainder: if self._find_controller(remainder[0]): abort(405) sub_controller = self._lookup_child(remainder[0]) if sub_controller: return lookup_controller(sub_controller, remainder[1:], request) abort(405)
python
def _handle_delete(self, method, remainder, request=None): ''' Routes ``DELETE`` actions to the appropriate controller. ''' if request is None: self._raise_method_deprecation_warning(self._handle_delete) if remainder: match = self._handle_custom_action(method, remainder, request) if match: return match controller = self._lookup_child(remainder[0]) if controller and not ismethod(controller): return lookup_controller(controller, remainder[1:], request) # check for post_delete/delete requests first controller = self._find_controller('post_delete', 'delete') if controller: return controller, remainder # if no controller exists, try routing to a sub-controller; note that # since this is a DELETE verb, any local exposes are 405'd if remainder: if self._find_controller(remainder[0]): abort(405) sub_controller = self._lookup_child(remainder[0]) if sub_controller: return lookup_controller(sub_controller, remainder[1:], request) abort(405)
[ "def", "_handle_delete", "(", "self", ",", "method", ",", "remainder", ",", "request", "=", "None", ")", ":", "if", "request", "is", "None", ":", "self", ".", "_raise_method_deprecation_warning", "(", "self", ".", "_handle_delete", ")", "if", "remainder", ":...
Routes ``DELETE`` actions to the appropriate controller.
[ "Routes", "DELETE", "actions", "to", "the", "appropriate", "controller", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/rest.py#L311-L342
train
23,741
pecan/pecan
pecan/rest.py
RestController._handle_post
def _handle_post(self, method, remainder, request=None): ''' Routes ``POST`` requests. ''' if request is None: self._raise_method_deprecation_warning(self._handle_post) # check for custom POST/PUT requests if remainder: match = self._handle_custom_action(method, remainder, request) if match: return match controller = self._lookup_child(remainder[0]) if controller and not ismethod(controller): return lookup_controller(controller, remainder[1:], request) # check for regular POST/PUT requests controller = self._find_controller(method) if controller: return controller, remainder abort(405)
python
def _handle_post(self, method, remainder, request=None): ''' Routes ``POST`` requests. ''' if request is None: self._raise_method_deprecation_warning(self._handle_post) # check for custom POST/PUT requests if remainder: match = self._handle_custom_action(method, remainder, request) if match: return match controller = self._lookup_child(remainder[0]) if controller and not ismethod(controller): return lookup_controller(controller, remainder[1:], request) # check for regular POST/PUT requests controller = self._find_controller(method) if controller: return controller, remainder abort(405)
[ "def", "_handle_post", "(", "self", ",", "method", ",", "remainder", ",", "request", "=", "None", ")", ":", "if", "request", "is", "None", ":", "self", ".", "_raise_method_deprecation_warning", "(", "self", ".", "_handle_post", ")", "# check for custom POST/PUT ...
Routes ``POST`` requests.
[ "Routes", "POST", "requests", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/rest.py#L344-L366
train
23,742
pecan/pecan
pecan/templating.py
format_line_context
def format_line_context(filename, lineno, context=10): ''' Formats the the line context for error rendering. :param filename: the location of the file, within which the error occurred :param lineno: the offending line number :param context: number of lines of code to display before and after the offending line. ''' with open(filename) as f: lines = f.readlines() lineno = lineno - 1 # files are indexed by 1 not 0 if lineno > 0: start_lineno = max(lineno - context, 0) end_lineno = lineno + context lines = [escape(l, True) for l in lines[start_lineno:end_lineno]] i = lineno - start_lineno lines[i] = '<strong>%s</strong>' % lines[i] else: lines = [escape(l, True) for l in lines[:context]] msg = '<pre style="background-color:#ccc;padding:2em;">%s</pre>' return msg % ''.join(lines)
python
def format_line_context(filename, lineno, context=10): ''' Formats the the line context for error rendering. :param filename: the location of the file, within which the error occurred :param lineno: the offending line number :param context: number of lines of code to display before and after the offending line. ''' with open(filename) as f: lines = f.readlines() lineno = lineno - 1 # files are indexed by 1 not 0 if lineno > 0: start_lineno = max(lineno - context, 0) end_lineno = lineno + context lines = [escape(l, True) for l in lines[start_lineno:end_lineno]] i = lineno - start_lineno lines[i] = '<strong>%s</strong>' % lines[i] else: lines = [escape(l, True) for l in lines[:context]] msg = '<pre style="background-color:#ccc;padding:2em;">%s</pre>' return msg % ''.join(lines)
[ "def", "format_line_context", "(", "filename", ",", "lineno", ",", "context", "=", "10", ")", ":", "with", "open", "(", "filename", ")", "as", "f", ":", "lines", "=", "f", ".", "readlines", "(", ")", "lineno", "=", "lineno", "-", "1", "# files are inde...
Formats the the line context for error rendering. :param filename: the location of the file, within which the error occurred :param lineno: the offending line number :param context: number of lines of code to display before and after the offending line.
[ "Formats", "the", "the", "line", "context", "for", "error", "rendering", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/templating.py#L183-L207
train
23,743
pecan/pecan
pecan/templating.py
ExtraNamespace.make_ns
def make_ns(self, ns): ''' Returns the `lazily` created template namespace. ''' if self.namespace: val = {} val.update(self.namespace) val.update(ns) return val else: return ns
python
def make_ns(self, ns): ''' Returns the `lazily` created template namespace. ''' if self.namespace: val = {} val.update(self.namespace) val.update(ns) return val else: return ns
[ "def", "make_ns", "(", "self", ",", "ns", ")", ":", "if", "self", ".", "namespace", ":", "val", "=", "{", "}", "val", ".", "update", "(", "self", ".", "namespace", ")", "val", ".", "update", "(", "ns", ")", "return", "val", "else", ":", "return",...
Returns the `lazily` created template namespace.
[ "Returns", "the", "lazily", "created", "template", "namespace", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/templating.py#L229-L239
train
23,744
pecan/pecan
pecan/templating.py
RendererFactory.get
def get(self, name, template_path): ''' Returns the renderer object. :param name: name of the requested renderer :param template_path: path to the template ''' if name not in self._renderers: cls = self._renderer_classes.get(name) if cls is None: return None else: self._renderers[name] = cls(template_path, self.extra_vars) return self._renderers[name]
python
def get(self, name, template_path): ''' Returns the renderer object. :param name: name of the requested renderer :param template_path: path to the template ''' if name not in self._renderers: cls = self._renderer_classes.get(name) if cls is None: return None else: self._renderers[name] = cls(template_path, self.extra_vars) return self._renderers[name]
[ "def", "get", "(", "self", ",", "name", ",", "template_path", ")", ":", "if", "name", "not", "in", "self", ".", "_renderers", ":", "cls", "=", "self", ".", "_renderer_classes", ".", "get", "(", "name", ")", "if", "cls", "is", "None", ":", "return", ...
Returns the renderer object. :param name: name of the requested renderer :param template_path: path to the template
[ "Returns", "the", "renderer", "object", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/templating.py#L274-L287
train
23,745
pecan/pecan
pecan/jsonify.py
GenericJSON.default
def default(self, obj): ''' Converts an object and returns a ``JSON``-friendly structure. :param obj: object or structure to be converted into a ``JSON``-ifiable structure Considers the following special cases in order: * object has a callable __json__() attribute defined returns the result of the call to __json__() * date and datetime objects returns the object cast to str * Decimal objects returns the object cast to float * SQLAlchemy objects returns a copy of the object.__dict__ with internal SQLAlchemy parameters removed * SQLAlchemy ResultProxy objects Casts the iterable ResultProxy into a list of tuples containing the entire resultset data, returns the list in a dictionary along with the resultset "row" count. .. note:: {'count': 5, 'rows': [('Ed Jones',), ('Pete Jones',), ('Wendy Williams',), ('Mary Contrary',), ('Fred Smith',)]} * SQLAlchemy RowProxy objects Casts the RowProxy cursor object into a dictionary, probably losing its ordered dictionary behavior in the process but making it JSON-friendly. * webob_dicts objects returns webob_dicts.mixed() dictionary, which is guaranteed to be JSON-friendly. ''' if hasattr(obj, '__json__') and six.callable(obj.__json__): return obj.__json__() elif isinstance(obj, (date, datetime)): return str(obj) elif isinstance(obj, Decimal): # XXX What to do about JSONEncoder crappy handling of Decimals? # SimpleJSON has better Decimal encoding than the std lib # but only in recent versions return float(obj) elif is_saobject(obj): props = {} for key in obj.__dict__: if not key.startswith('_sa_'): props[key] = getattr(obj, key) return props elif isinstance(obj, ResultProxy): props = dict(rows=list(obj), count=obj.rowcount) if props['count'] < 0: props['count'] = len(props['rows']) return props elif isinstance(obj, RowProxy): return dict(obj) elif isinstance(obj, webob_dicts): return obj.mixed() else: return JSONEncoder.default(self, obj)
python
def default(self, obj): ''' Converts an object and returns a ``JSON``-friendly structure. :param obj: object or structure to be converted into a ``JSON``-ifiable structure Considers the following special cases in order: * object has a callable __json__() attribute defined returns the result of the call to __json__() * date and datetime objects returns the object cast to str * Decimal objects returns the object cast to float * SQLAlchemy objects returns a copy of the object.__dict__ with internal SQLAlchemy parameters removed * SQLAlchemy ResultProxy objects Casts the iterable ResultProxy into a list of tuples containing the entire resultset data, returns the list in a dictionary along with the resultset "row" count. .. note:: {'count': 5, 'rows': [('Ed Jones',), ('Pete Jones',), ('Wendy Williams',), ('Mary Contrary',), ('Fred Smith',)]} * SQLAlchemy RowProxy objects Casts the RowProxy cursor object into a dictionary, probably losing its ordered dictionary behavior in the process but making it JSON-friendly. * webob_dicts objects returns webob_dicts.mixed() dictionary, which is guaranteed to be JSON-friendly. ''' if hasattr(obj, '__json__') and six.callable(obj.__json__): return obj.__json__() elif isinstance(obj, (date, datetime)): return str(obj) elif isinstance(obj, Decimal): # XXX What to do about JSONEncoder crappy handling of Decimals? # SimpleJSON has better Decimal encoding than the std lib # but only in recent versions return float(obj) elif is_saobject(obj): props = {} for key in obj.__dict__: if not key.startswith('_sa_'): props[key] = getattr(obj, key) return props elif isinstance(obj, ResultProxy): props = dict(rows=list(obj), count=obj.rowcount) if props['count'] < 0: props['count'] = len(props['rows']) return props elif isinstance(obj, RowProxy): return dict(obj) elif isinstance(obj, webob_dicts): return obj.mixed() else: return JSONEncoder.default(self, obj)
[ "def", "default", "(", "self", ",", "obj", ")", ":", "if", "hasattr", "(", "obj", ",", "'__json__'", ")", "and", "six", ".", "callable", "(", "obj", ".", "__json__", ")", ":", "return", "obj", ".", "__json__", "(", ")", "elif", "isinstance", "(", "...
Converts an object and returns a ``JSON``-friendly structure. :param obj: object or structure to be converted into a ``JSON``-ifiable structure Considers the following special cases in order: * object has a callable __json__() attribute defined returns the result of the call to __json__() * date and datetime objects returns the object cast to str * Decimal objects returns the object cast to float * SQLAlchemy objects returns a copy of the object.__dict__ with internal SQLAlchemy parameters removed * SQLAlchemy ResultProxy objects Casts the iterable ResultProxy into a list of tuples containing the entire resultset data, returns the list in a dictionary along with the resultset "row" count. .. note:: {'count': 5, 'rows': [('Ed Jones',), ('Pete Jones',), ('Wendy Williams',), ('Mary Contrary',), ('Fred Smith',)]} * SQLAlchemy RowProxy objects Casts the RowProxy cursor object into a dictionary, probably losing its ordered dictionary behavior in the process but making it JSON-friendly. * webob_dicts objects returns webob_dicts.mixed() dictionary, which is guaranteed to be JSON-friendly.
[ "Converts", "an", "object", "and", "returns", "a", "JSON", "-", "friendly", "structure", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/jsonify.py#L49-L108
train
23,746
pecan/pecan
pecan/util.py
getargspec
def getargspec(method): """ Drill through layers of decorators attempting to locate the actual argspec for a method. """ argspec = _getargspec(method) args = argspec[0] if args and args[0] == 'self': return argspec if hasattr(method, '__func__'): method = method.__func__ func_closure = six.get_function_closure(method) # NOTE(sileht): if the closure is None we cannot look deeper, # so return actual argspec, this occurs when the method # is static for example. if not func_closure: return argspec closure = None # In the case of deeply nested decorators (with arguments), it's possible # that there are several callables in scope; Take a best guess and go # with the one that looks most like a pecan controller function # (has a __code__ object, and 'self' is the first argument) func_closure = filter( lambda c: ( six.callable(c.cell_contents) and hasattr(c.cell_contents, '__code__') ), func_closure ) func_closure = sorted( func_closure, key=lambda c: 'self' in c.cell_contents.__code__.co_varnames, reverse=True ) closure = func_closure[0] method = closure.cell_contents return getargspec(method)
python
def getargspec(method): """ Drill through layers of decorators attempting to locate the actual argspec for a method. """ argspec = _getargspec(method) args = argspec[0] if args and args[0] == 'self': return argspec if hasattr(method, '__func__'): method = method.__func__ func_closure = six.get_function_closure(method) # NOTE(sileht): if the closure is None we cannot look deeper, # so return actual argspec, this occurs when the method # is static for example. if not func_closure: return argspec closure = None # In the case of deeply nested decorators (with arguments), it's possible # that there are several callables in scope; Take a best guess and go # with the one that looks most like a pecan controller function # (has a __code__ object, and 'self' is the first argument) func_closure = filter( lambda c: ( six.callable(c.cell_contents) and hasattr(c.cell_contents, '__code__') ), func_closure ) func_closure = sorted( func_closure, key=lambda c: 'self' in c.cell_contents.__code__.co_varnames, reverse=True ) closure = func_closure[0] method = closure.cell_contents return getargspec(method)
[ "def", "getargspec", "(", "method", ")", ":", "argspec", "=", "_getargspec", "(", "method", ")", "args", "=", "argspec", "[", "0", "]", "if", "args", "and", "args", "[", "0", "]", "==", "'self'", ":", "return", "argspec", "if", "hasattr", "(", "metho...
Drill through layers of decorators attempting to locate the actual argspec for a method.
[ "Drill", "through", "layers", "of", "decorators", "attempting", "to", "locate", "the", "actual", "argspec", "for", "a", "method", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/util.py#L12-L54
train
23,747
pecan/pecan
pecan/commands/serve.py
gunicorn_run
def gunicorn_run(): """ The ``gunicorn_pecan`` command for launching ``pecan`` applications """ try: from gunicorn.app.wsgiapp import WSGIApplication except ImportError as exc: args = exc.args arg0 = args[0] if args else '' arg0 += ' (are you sure `gunicorn` is installed?)' exc.args = (arg0,) + args[1:] raise class PecanApplication(WSGIApplication): def init(self, parser, opts, args): if len(args) != 1: parser.error("No configuration file was specified.") self.cfgfname = os.path.normpath( os.path.join(os.getcwd(), args[0]) ) self.cfgfname = os.path.abspath(self.cfgfname) if not os.path.exists(self.cfgfname): parser.error("Config file not found: %s" % self.cfgfname) from pecan.configuration import _runtime_conf, set_config set_config(self.cfgfname, overwrite=True) # If available, use the host and port from the pecan config file cfg = {} if _runtime_conf.get('server'): server = _runtime_conf['server'] if hasattr(server, 'host') and hasattr(server, 'port'): cfg['bind'] = '%s:%s' % ( server.host, server.port ) return cfg def load(self): from pecan.deploy import deploy return deploy(self.cfgfname) PecanApplication("%(prog)s [OPTIONS] config.py").run()
python
def gunicorn_run(): """ The ``gunicorn_pecan`` command for launching ``pecan`` applications """ try: from gunicorn.app.wsgiapp import WSGIApplication except ImportError as exc: args = exc.args arg0 = args[0] if args else '' arg0 += ' (are you sure `gunicorn` is installed?)' exc.args = (arg0,) + args[1:] raise class PecanApplication(WSGIApplication): def init(self, parser, opts, args): if len(args) != 1: parser.error("No configuration file was specified.") self.cfgfname = os.path.normpath( os.path.join(os.getcwd(), args[0]) ) self.cfgfname = os.path.abspath(self.cfgfname) if not os.path.exists(self.cfgfname): parser.error("Config file not found: %s" % self.cfgfname) from pecan.configuration import _runtime_conf, set_config set_config(self.cfgfname, overwrite=True) # If available, use the host and port from the pecan config file cfg = {} if _runtime_conf.get('server'): server = _runtime_conf['server'] if hasattr(server, 'host') and hasattr(server, 'port'): cfg['bind'] = '%s:%s' % ( server.host, server.port ) return cfg def load(self): from pecan.deploy import deploy return deploy(self.cfgfname) PecanApplication("%(prog)s [OPTIONS] config.py").run()
[ "def", "gunicorn_run", "(", ")", ":", "try", ":", "from", "gunicorn", ".", "app", ".", "wsgiapp", "import", "WSGIApplication", "except", "ImportError", "as", "exc", ":", "args", "=", "exc", ".", "args", "arg0", "=", "args", "[", "0", "]", "if", "args",...
The ``gunicorn_pecan`` command for launching ``pecan`` applications
[ "The", "gunicorn_pecan", "command", "for", "launching", "pecan", "applications" ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/commands/serve.py#L155-L198
train
23,748
pecan/pecan
pecan/commands/serve.py
ServeCommand.serve
def serve(self, app, conf): """ A very simple approach for a WSGI server. """ if self.args.reload: try: self.watch_and_spawn(conf) except ImportError: print('The `--reload` option requires `watchdog` to be ' 'installed.') print(' $ pip install watchdog') else: self._serve(app, conf)
python
def serve(self, app, conf): """ A very simple approach for a WSGI server. """ if self.args.reload: try: self.watch_and_spawn(conf) except ImportError: print('The `--reload` option requires `watchdog` to be ' 'installed.') print(' $ pip install watchdog') else: self._serve(app, conf)
[ "def", "serve", "(", "self", ",", "app", ",", "conf", ")", ":", "if", "self", ".", "args", ".", "reload", ":", "try", ":", "self", ".", "watch_and_spawn", "(", "conf", ")", "except", "ImportError", ":", "print", "(", "'The `--reload` option requires `watch...
A very simple approach for a WSGI server.
[ "A", "very", "simple", "approach", "for", "a", "WSGI", "server", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/commands/serve.py#L139-L152
train
23,749
pecan/pecan
pecan/commands/serve.py
PecanWSGIRequestHandler.log_message
def log_message(self, format, *args): """ overrides the ``log_message`` method from the wsgiref server so that normal logging works with whatever configuration the application has been set to. Levels are inferred from the HTTP status code, 4XX codes are treated as warnings, 5XX as errors and everything else as INFO level. """ code = args[1][0] levels = { '4': 'warning', '5': 'error' } log_handler = getattr(logger, levels.get(code, 'info')) log_handler(format % args)
python
def log_message(self, format, *args): """ overrides the ``log_message`` method from the wsgiref server so that normal logging works with whatever configuration the application has been set to. Levels are inferred from the HTTP status code, 4XX codes are treated as warnings, 5XX as errors and everything else as INFO level. """ code = args[1][0] levels = { '4': 'warning', '5': 'error' } log_handler = getattr(logger, levels.get(code, 'info')) log_handler(format % args)
[ "def", "log_message", "(", "self", ",", "format", ",", "*", "args", ")", ":", "code", "=", "args", "[", "1", "]", "[", "0", "]", "levels", "=", "{", "'4'", ":", "'warning'", ",", "'5'", ":", "'error'", "}", "log_handler", "=", "getattr", "(", "lo...
overrides the ``log_message`` method from the wsgiref server so that normal logging works with whatever configuration the application has been set to. Levels are inferred from the HTTP status code, 4XX codes are treated as warnings, 5XX as errors and everything else as INFO level.
[ "overrides", "the", "log_message", "method", "from", "the", "wsgiref", "server", "so", "that", "normal", "logging", "works", "with", "whatever", "configuration", "the", "application", "has", "been", "set", "to", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/commands/serve.py#L213-L229
train
23,750
pecan/pecan
pecan/decorators.py
expose
def expose(template=None, generic=False, route=None, **kw): ''' Decorator used to flag controller methods as being "exposed" for access via HTTP, and to configure that access. :param template: The path to a template, relative to the base template directory. Can also be passed a string representing a special or custom renderer, such as ``'json'`` for :ref:`expose_json`. :param content_type: The content-type to use for this template. :param generic: A boolean which flags this as a "generic" controller, which uses generic functions based upon ``functools.singledispatch`` generic functions. Allows you to split a single controller into multiple paths based upon HTTP method. :param route: The name of the path segment to match (excluding separator characters, like `/`). Defaults to the name of the function itself, but this can be used to resolve paths which are not valid Python function names, e.g., if you wanted to route a function to `some-special-path'. ''' content_type = kw.get('content_type', 'text/html') if template == 'json': content_type = 'application/json' def decorate(f): # flag the method as exposed f.exposed = True cfg = _cfg(f) cfg['explicit_content_type'] = 'content_type' in kw if route: # This import is here to avoid a circular import issue from pecan import routing if cfg.get('generic_handler'): raise ValueError( 'Path segments cannot be overridden for generic ' 'controllers.' ) routing.route(route, f) # set a "pecan" attribute, where we will store details cfg['content_type'] = content_type cfg.setdefault('template', []).append(template) cfg.setdefault('content_types', {})[content_type] = template # handle generic controllers if generic: if f.__name__ in ('_default', '_lookup', '_route'): raise ValueError( 'The special method %s cannot be used as a generic ' 'controller' % f.__name__ ) cfg['generic'] = True cfg['generic_handlers'] = dict(DEFAULT=f) cfg['allowed_methods'] = [] f.when = when_for(f) # store the arguments for this controller method cfg['argspec'] = getargspec(f) return f return decorate
python
def expose(template=None, generic=False, route=None, **kw): ''' Decorator used to flag controller methods as being "exposed" for access via HTTP, and to configure that access. :param template: The path to a template, relative to the base template directory. Can also be passed a string representing a special or custom renderer, such as ``'json'`` for :ref:`expose_json`. :param content_type: The content-type to use for this template. :param generic: A boolean which flags this as a "generic" controller, which uses generic functions based upon ``functools.singledispatch`` generic functions. Allows you to split a single controller into multiple paths based upon HTTP method. :param route: The name of the path segment to match (excluding separator characters, like `/`). Defaults to the name of the function itself, but this can be used to resolve paths which are not valid Python function names, e.g., if you wanted to route a function to `some-special-path'. ''' content_type = kw.get('content_type', 'text/html') if template == 'json': content_type = 'application/json' def decorate(f): # flag the method as exposed f.exposed = True cfg = _cfg(f) cfg['explicit_content_type'] = 'content_type' in kw if route: # This import is here to avoid a circular import issue from pecan import routing if cfg.get('generic_handler'): raise ValueError( 'Path segments cannot be overridden for generic ' 'controllers.' ) routing.route(route, f) # set a "pecan" attribute, where we will store details cfg['content_type'] = content_type cfg.setdefault('template', []).append(template) cfg.setdefault('content_types', {})[content_type] = template # handle generic controllers if generic: if f.__name__ in ('_default', '_lookup', '_route'): raise ValueError( 'The special method %s cannot be used as a generic ' 'controller' % f.__name__ ) cfg['generic'] = True cfg['generic_handlers'] = dict(DEFAULT=f) cfg['allowed_methods'] = [] f.when = when_for(f) # store the arguments for this controller method cfg['argspec'] = getargspec(f) return f return decorate
[ "def", "expose", "(", "template", "=", "None", ",", "generic", "=", "False", ",", "route", "=", "None", ",", "*", "*", "kw", ")", ":", "content_type", "=", "kw", ".", "get", "(", "'content_type'", ",", "'text/html'", ")", "if", "template", "==", "'js...
Decorator used to flag controller methods as being "exposed" for access via HTTP, and to configure that access. :param template: The path to a template, relative to the base template directory. Can also be passed a string representing a special or custom renderer, such as ``'json'`` for :ref:`expose_json`. :param content_type: The content-type to use for this template. :param generic: A boolean which flags this as a "generic" controller, which uses generic functions based upon ``functools.singledispatch`` generic functions. Allows you to split a single controller into multiple paths based upon HTTP method. :param route: The name of the path segment to match (excluding separator characters, like `/`). Defaults to the name of the function itself, but this can be used to resolve paths which are not valid Python function names, e.g., if you wanted to route a function to `some-special-path'.
[ "Decorator", "used", "to", "flag", "controller", "methods", "as", "being", "exposed", "for", "access", "via", "HTTP", "and", "to", "configure", "that", "access", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/decorators.py#L25-L95
train
23,751
craft-ai/craft-ai-client-python
craftai/time.py
Time.to_dict
def to_dict(self): """Returns the Time instance as a usable dictionary for craftai""" return { "timestamp": int(self.timestamp), "timezone": self.timezone, "time_of_day": self.time_of_day, "day_of_week": self.day_of_week, "day_of_month": self.day_of_month, "month_of_year": self.month_of_year, "utc_iso": self.utc_iso }
python
def to_dict(self): """Returns the Time instance as a usable dictionary for craftai""" return { "timestamp": int(self.timestamp), "timezone": self.timezone, "time_of_day": self.time_of_day, "day_of_week": self.day_of_week, "day_of_month": self.day_of_month, "month_of_year": self.month_of_year, "utc_iso": self.utc_iso }
[ "def", "to_dict", "(", "self", ")", ":", "return", "{", "\"timestamp\"", ":", "int", "(", "self", ".", "timestamp", ")", ",", "\"timezone\"", ":", "self", ".", "timezone", ",", "\"time_of_day\"", ":", "self", ".", "time_of_day", ",", "\"day_of_week\"", ":"...
Returns the Time instance as a usable dictionary for craftai
[ "Returns", "the", "Time", "instance", "as", "a", "usable", "dictionary", "for", "craftai" ]
8bc1a9038511540930371aacfdde0f4040e08f24
https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/time.py#L138-L148
train
23,752
craft-ai/craft-ai-client-python
craftai/time.py
Time.timestamp_from_datetime
def timestamp_from_datetime(date_time): """Returns POSIX timestamp as float""" if date_time.tzinfo is None: return time.mktime((date_time.year, date_time.month, date_time.day, date_time.hour, date_time.minute, date_time.second, -1, -1, -1)) + date_time.microsecond / 1e6 return (date_time - _EPOCH).total_seconds()
python
def timestamp_from_datetime(date_time): """Returns POSIX timestamp as float""" if date_time.tzinfo is None: return time.mktime((date_time.year, date_time.month, date_time.day, date_time.hour, date_time.minute, date_time.second, -1, -1, -1)) + date_time.microsecond / 1e6 return (date_time - _EPOCH).total_seconds()
[ "def", "timestamp_from_datetime", "(", "date_time", ")", ":", "if", "date_time", ".", "tzinfo", "is", "None", ":", "return", "time", ".", "mktime", "(", "(", "date_time", ".", "year", ",", "date_time", ".", "month", ",", "date_time", ".", "day", ",", "da...
Returns POSIX timestamp as float
[ "Returns", "POSIX", "timestamp", "as", "float" ]
8bc1a9038511540930371aacfdde0f4040e08f24
https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/time.py#L151-L157
train
23,753
craft-ai/craft-ai-client-python
craftai/client.py
CraftAIClient.create_agent
def create_agent(self, configuration, agent_id=""): """Create an agent. :param dict configuration: Form given by the craftai documentation. :param str agent_id: Optional. The id of the agent to create. It must be an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. :default agent_id: "", the agent_id is generated. :return: agent created. :rtype: dict. :raise CraftAiBadRequestError: if the input is not of the right form. """ # Extra header in addition to the main session's ct_header = {"Content-Type": "application/json; charset=utf-8"} # Building payload and checking that it is valid for a JSON # serialization payload = {"configuration": configuration} if agent_id != "": # Raises an error when agent_id is invalid self._check_agent_id(agent_id) payload["id"] = agent_id try: json_pl = json.dumps(payload) except TypeError as err: raise CraftAiBadRequestError("Invalid configuration or agent id given. {}" .format(err.__str__())) req_url = "{}/agents".format(self._base_url) resp = self._requests_session.post(req_url, headers=ct_header, data=json_pl) agent = self._decode_response(resp) return agent
python
def create_agent(self, configuration, agent_id=""): """Create an agent. :param dict configuration: Form given by the craftai documentation. :param str agent_id: Optional. The id of the agent to create. It must be an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. :default agent_id: "", the agent_id is generated. :return: agent created. :rtype: dict. :raise CraftAiBadRequestError: if the input is not of the right form. """ # Extra header in addition to the main session's ct_header = {"Content-Type": "application/json; charset=utf-8"} # Building payload and checking that it is valid for a JSON # serialization payload = {"configuration": configuration} if agent_id != "": # Raises an error when agent_id is invalid self._check_agent_id(agent_id) payload["id"] = agent_id try: json_pl = json.dumps(payload) except TypeError as err: raise CraftAiBadRequestError("Invalid configuration or agent id given. {}" .format(err.__str__())) req_url = "{}/agents".format(self._base_url) resp = self._requests_session.post(req_url, headers=ct_header, data=json_pl) agent = self._decode_response(resp) return agent
[ "def", "create_agent", "(", "self", ",", "configuration", ",", "agent_id", "=", "\"\"", ")", ":", "# Extra header in addition to the main session's", "ct_header", "=", "{", "\"Content-Type\"", ":", "\"application/json; charset=utf-8\"", "}", "# Building payload and checking t...
Create an agent. :param dict configuration: Form given by the craftai documentation. :param str agent_id: Optional. The id of the agent to create. It must be an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. :default agent_id: "", the agent_id is generated. :return: agent created. :rtype: dict. :raise CraftAiBadRequestError: if the input is not of the right form.
[ "Create", "an", "agent", "." ]
8bc1a9038511540930371aacfdde0f4040e08f24
https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L112-L151
train
23,754
craft-ai/craft-ai-client-python
craftai/client.py
CraftAIClient.delete_agent
def delete_agent(self, agent_id): """Delete an agent. :param str agent_id: The id of the agent to delete. It must be an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. :return: agent deleted. :rtype: dict. """ # Raises an error when agent_id is invalid self._check_agent_id(agent_id) req_url = "{}/agents/{}".format(self._base_url, agent_id) resp = self._requests_session.delete(req_url) decoded_resp = self._decode_response(resp) return decoded_resp
python
def delete_agent(self, agent_id): """Delete an agent. :param str agent_id: The id of the agent to delete. It must be an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. :return: agent deleted. :rtype: dict. """ # Raises an error when agent_id is invalid self._check_agent_id(agent_id) req_url = "{}/agents/{}".format(self._base_url, agent_id) resp = self._requests_session.delete(req_url) decoded_resp = self._decode_response(resp) return decoded_resp
[ "def", "delete_agent", "(", "self", ",", "agent_id", ")", ":", "# Raises an error when agent_id is invalid", "self", ".", "_check_agent_id", "(", "agent_id", ")", "req_url", "=", "\"{}/agents/{}\"", ".", "format", "(", "self", ".", "_base_url", ",", "agent_id", ")...
Delete an agent. :param str agent_id: The id of the agent to delete. It must be an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. :return: agent deleted. :rtype: dict.
[ "Delete", "an", "agent", "." ]
8bc1a9038511540930371aacfdde0f4040e08f24
https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L205-L223
train
23,755
craft-ai/craft-ai-client-python
craftai/client.py
CraftAIClient.delete_agents_bulk
def delete_agents_bulk(self, payload): """Delete a group of agents :param list payload: Contains the informations to delete the agents. It's in the form [{"id": agent_id}]. With id an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. :return: the list of agents deleted which are represented with dictionnaries. :rtype: list of dict. :raises CraftAiBadRequestError: If all of the ids are invalid. """ # Check all ids, raise an error if all ids are invalid valid_indices, invalid_indices, invalid_agents = self._check_agent_id_bulk(payload) # Create the json file with the agents with valid id and send it valid_agents = self._create_and_send_json_bulk([payload[i] for i in valid_indices], "{}/bulk/agents".format(self._base_url), "DELETE") if invalid_indices == []: return valid_agents # Put the valid and invalid agents in their original index return self._recreate_list_with_indices(valid_indices, valid_agents, invalid_indices, invalid_agents)
python
def delete_agents_bulk(self, payload): """Delete a group of agents :param list payload: Contains the informations to delete the agents. It's in the form [{"id": agent_id}]. With id an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. :return: the list of agents deleted which are represented with dictionnaries. :rtype: list of dict. :raises CraftAiBadRequestError: If all of the ids are invalid. """ # Check all ids, raise an error if all ids are invalid valid_indices, invalid_indices, invalid_agents = self._check_agent_id_bulk(payload) # Create the json file with the agents with valid id and send it valid_agents = self._create_and_send_json_bulk([payload[i] for i in valid_indices], "{}/bulk/agents".format(self._base_url), "DELETE") if invalid_indices == []: return valid_agents # Put the valid and invalid agents in their original index return self._recreate_list_with_indices(valid_indices, valid_agents, invalid_indices, invalid_agents)
[ "def", "delete_agents_bulk", "(", "self", ",", "payload", ")", ":", "# Check all ids, raise an error if all ids are invalid", "valid_indices", ",", "invalid_indices", ",", "invalid_agents", "=", "self", ".", "_check_agent_id_bulk", "(", "payload", ")", "# Create the json fi...
Delete a group of agents :param list payload: Contains the informations to delete the agents. It's in the form [{"id": agent_id}]. With id an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. :return: the list of agents deleted which are represented with dictionnaries. :rtype: list of dict. :raises CraftAiBadRequestError: If all of the ids are invalid.
[ "Delete", "a", "group", "of", "agents" ]
8bc1a9038511540930371aacfdde0f4040e08f24
https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L225-L254
train
23,756
craft-ai/craft-ai-client-python
craftai/client.py
CraftAIClient.add_operations
def add_operations(self, agent_id, operations): """Add operations to an agent. :param str agent_id: The id of the agent to delete. It must be an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. It must referenced an existing agent. :param list operations: Contains dictionnaries that has the form given in the craftai documentation and the configuration of the agent. :return: message about the added operations. :rtype: str :raise CraftAiBadRequestError: if the input is not of the right form. """ # Raises an error when agent_id is invalid self._check_agent_id(agent_id) # Extra header in addition to the main session's ct_header = {"Content-Type": "application/json; charset=utf-8"} offset = 0 is_looping = True while is_looping: next_offset = offset + self.config["operationsChunksSize"] try: json_pl = json.dumps(operations[offset:next_offset]) except TypeError as err: raise CraftAiBadRequestError("Invalid configuration or agent id given. {}" .format(err.__str__())) req_url = "{}/agents/{}/context".format(self._base_url, agent_id) resp = self._requests_session.post(req_url, headers=ct_header, data=json_pl) self._decode_response(resp) if next_offset >= len(operations): is_looping = False offset = next_offset return { "message": "Successfully added %i operation(s) to the agent \"%s/%s/%s\" context." % (len(operations), self.config["owner"], self.config["project"], agent_id) }
python
def add_operations(self, agent_id, operations): """Add operations to an agent. :param str agent_id: The id of the agent to delete. It must be an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. It must referenced an existing agent. :param list operations: Contains dictionnaries that has the form given in the craftai documentation and the configuration of the agent. :return: message about the added operations. :rtype: str :raise CraftAiBadRequestError: if the input is not of the right form. """ # Raises an error when agent_id is invalid self._check_agent_id(agent_id) # Extra header in addition to the main session's ct_header = {"Content-Type": "application/json; charset=utf-8"} offset = 0 is_looping = True while is_looping: next_offset = offset + self.config["operationsChunksSize"] try: json_pl = json.dumps(operations[offset:next_offset]) except TypeError as err: raise CraftAiBadRequestError("Invalid configuration or agent id given. {}" .format(err.__str__())) req_url = "{}/agents/{}/context".format(self._base_url, agent_id) resp = self._requests_session.post(req_url, headers=ct_header, data=json_pl) self._decode_response(resp) if next_offset >= len(operations): is_looping = False offset = next_offset return { "message": "Successfully added %i operation(s) to the agent \"%s/%s/%s\" context." % (len(operations), self.config["owner"], self.config["project"], agent_id) }
[ "def", "add_operations", "(", "self", ",", "agent_id", ",", "operations", ")", ":", "# Raises an error when agent_id is invalid", "self", ".", "_check_agent_id", "(", "agent_id", ")", "# Extra header in addition to the main session's", "ct_header", "=", "{", "\"Content-Type...
Add operations to an agent. :param str agent_id: The id of the agent to delete. It must be an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. It must referenced an existing agent. :param list operations: Contains dictionnaries that has the form given in the craftai documentation and the configuration of the agent. :return: message about the added operations. :rtype: str :raise CraftAiBadRequestError: if the input is not of the right form.
[ "Add", "operations", "to", "an", "agent", "." ]
8bc1a9038511540930371aacfdde0f4040e08f24
https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L285-L331
train
23,757
craft-ai/craft-ai-client-python
craftai/client.py
CraftAIClient._add_operations_bulk
def _add_operations_bulk(self, chunked_data): """Tool for the function add_operations_bulk. It send the requests to add the operations to the agents. :param list chunked_data: list of list of the agents and their operations to add. Each chunk can be requested at the same time. :return: list of agents containing a message about the added operations. :rtype: list if dict. :raises CraftAiBadRequestError: if the input is not of the right form. """ url = "{}/bulk/context".format(self._base_url) ct_header = {"Content-Type": "application/json; charset=utf-8"} responses = [] for chunk in chunked_data: if len(chunk) > 1: try: json_pl = json.dumps(chunk) except TypeError as err: raise CraftAiBadRequestError("Error while dumping the payload into json" "format when converting it for the bulk request. {}" .format(err.__str__())) resp = self._requests_session.post(url, headers=ct_header, data=json_pl) resp = self._decode_response(resp) responses += resp elif chunk: message = self.add_operations(chunk[0]["id"], chunk[0]["operations"]) responses.append({"id": chunk[0]["id"], "status": 201, "message": message}) if responses == []: raise CraftAiBadRequestError("Invalid or empty set of operations given") return responses
python
def _add_operations_bulk(self, chunked_data): """Tool for the function add_operations_bulk. It send the requests to add the operations to the agents. :param list chunked_data: list of list of the agents and their operations to add. Each chunk can be requested at the same time. :return: list of agents containing a message about the added operations. :rtype: list if dict. :raises CraftAiBadRequestError: if the input is not of the right form. """ url = "{}/bulk/context".format(self._base_url) ct_header = {"Content-Type": "application/json; charset=utf-8"} responses = [] for chunk in chunked_data: if len(chunk) > 1: try: json_pl = json.dumps(chunk) except TypeError as err: raise CraftAiBadRequestError("Error while dumping the payload into json" "format when converting it for the bulk request. {}" .format(err.__str__())) resp = self._requests_session.post(url, headers=ct_header, data=json_pl) resp = self._decode_response(resp) responses += resp elif chunk: message = self.add_operations(chunk[0]["id"], chunk[0]["operations"]) responses.append({"id": chunk[0]["id"], "status": 201, "message": message}) if responses == []: raise CraftAiBadRequestError("Invalid or empty set of operations given") return responses
[ "def", "_add_operations_bulk", "(", "self", ",", "chunked_data", ")", ":", "url", "=", "\"{}/bulk/context\"", ".", "format", "(", "self", ".", "_base_url", ")", "ct_header", "=", "{", "\"Content-Type\"", ":", "\"application/json; charset=utf-8\"", "}", "responses", ...
Tool for the function add_operations_bulk. It send the requests to add the operations to the agents. :param list chunked_data: list of list of the agents and their operations to add. Each chunk can be requested at the same time. :return: list of agents containing a message about the added operations. :rtype: list if dict. :raises CraftAiBadRequestError: if the input is not of the right form.
[ "Tool", "for", "the", "function", "add_operations_bulk", ".", "It", "send", "the", "requests", "to", "add", "the", "operations", "to", "the", "agents", "." ]
8bc1a9038511540930371aacfdde0f4040e08f24
https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L333-L368
train
23,758
craft-ai/craft-ai-client-python
craftai/client.py
CraftAIClient.add_operations_bulk
def add_operations_bulk(self, payload): """Add operations to a group of agents. :param list payload: contains the informations necessary for the action. It's in the form [{"id": agent_id, "operations": operations}] With id that is an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. It must referenced an existing agent. With operations a list containing dictionnaries that has the form given in the craftai documentation and the configuration of the agent. :return: list of agents containing a message about the added operations. :rtype: list if dict. :raises CraftAiBadRequestError: if all of the ids are invalid or referenced non existing agents or one of the operations is invalid. """ # Check all ids, raise an error if all ids are invalid valid_indices, _, _ = self._check_agent_id_bulk(payload) valid_payload = [payload[i] for i in valid_indices] chunked_data = [] current_chunk = [] current_chunk_size = 0 for agent in valid_payload: if (agent["operations"] and isinstance(agent["operations"], list)): if current_chunk_size + len(agent["operations"]) > self.config["operationsChunksSize"]: chunked_data.append(current_chunk) current_chunk_size = 0 current_chunk = [] if len(agent["operations"]) > self.config["operationsChunksSize"]: chunked_data.append([agent]) current_chunk_size = 0 else: current_chunk_size += len(agent["operations"]) current_chunk.append(agent) if current_chunk: chunked_data.append(current_chunk) return self._add_operations_bulk(chunked_data)
python
def add_operations_bulk(self, payload): """Add operations to a group of agents. :param list payload: contains the informations necessary for the action. It's in the form [{"id": agent_id, "operations": operations}] With id that is an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. It must referenced an existing agent. With operations a list containing dictionnaries that has the form given in the craftai documentation and the configuration of the agent. :return: list of agents containing a message about the added operations. :rtype: list if dict. :raises CraftAiBadRequestError: if all of the ids are invalid or referenced non existing agents or one of the operations is invalid. """ # Check all ids, raise an error if all ids are invalid valid_indices, _, _ = self._check_agent_id_bulk(payload) valid_payload = [payload[i] for i in valid_indices] chunked_data = [] current_chunk = [] current_chunk_size = 0 for agent in valid_payload: if (agent["operations"] and isinstance(agent["operations"], list)): if current_chunk_size + len(agent["operations"]) > self.config["operationsChunksSize"]: chunked_data.append(current_chunk) current_chunk_size = 0 current_chunk = [] if len(agent["operations"]) > self.config["operationsChunksSize"]: chunked_data.append([agent]) current_chunk_size = 0 else: current_chunk_size += len(agent["operations"]) current_chunk.append(agent) if current_chunk: chunked_data.append(current_chunk) return self._add_operations_bulk(chunked_data)
[ "def", "add_operations_bulk", "(", "self", ",", "payload", ")", ":", "# Check all ids, raise an error if all ids are invalid", "valid_indices", ",", "_", ",", "_", "=", "self", ".", "_check_agent_id_bulk", "(", "payload", ")", "valid_payload", "=", "[", "payload", "...
Add operations to a group of agents. :param list payload: contains the informations necessary for the action. It's in the form [{"id": agent_id, "operations": operations}] With id that is an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. It must referenced an existing agent. With operations a list containing dictionnaries that has the form given in the craftai documentation and the configuration of the agent. :return: list of agents containing a message about the added operations. :rtype: list if dict. :raises CraftAiBadRequestError: if all of the ids are invalid or referenced non existing agents or one of the operations is invalid.
[ "Add", "operations", "to", "a", "group", "of", "agents", "." ]
8bc1a9038511540930371aacfdde0f4040e08f24
https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L370-L412
train
23,759
craft-ai/craft-ai-client-python
craftai/client.py
CraftAIClient._get_decision_tree
def _get_decision_tree(self, agent_id, timestamp, version): """Tool for the function get_decision_tree. :param str agent_id: the id of the agent to get the tree. It must be an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. :param int timestamp: Optional. The decision tree is comptuted at this timestamp. :default timestamp: None, means that we get the tree computed with all its context history. :param version: version of the tree to get. :type version: str or int :default version: default version of the tree. :return: decision tree. :rtype: dict. """ headers = self._headers.copy() headers["x-craft-ai-tree-version"] = version # If we give no timestamp the default behaviour is to give the tree from the latest timestamp if timestamp is None: req_url = "{}/agents/{}/decision/tree?".format(self._base_url, agent_id) else: req_url = "{}/agents/{}/decision/tree?t={}".format(self._base_url, agent_id, timestamp) resp = self._requests_session.get(req_url) decision_tree = self._decode_response(resp) return decision_tree
python
def _get_decision_tree(self, agent_id, timestamp, version): """Tool for the function get_decision_tree. :param str agent_id: the id of the agent to get the tree. It must be an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. :param int timestamp: Optional. The decision tree is comptuted at this timestamp. :default timestamp: None, means that we get the tree computed with all its context history. :param version: version of the tree to get. :type version: str or int :default version: default version of the tree. :return: decision tree. :rtype: dict. """ headers = self._headers.copy() headers["x-craft-ai-tree-version"] = version # If we give no timestamp the default behaviour is to give the tree from the latest timestamp if timestamp is None: req_url = "{}/agents/{}/decision/tree?".format(self._base_url, agent_id) else: req_url = "{}/agents/{}/decision/tree?t={}".format(self._base_url, agent_id, timestamp) resp = self._requests_session.get(req_url) decision_tree = self._decode_response(resp) return decision_tree
[ "def", "_get_decision_tree", "(", "self", ",", "agent_id", ",", "timestamp", ",", "version", ")", ":", "headers", "=", "self", ".", "_headers", ".", "copy", "(", ")", "headers", "[", "\"x-craft-ai-tree-version\"", "]", "=", "version", "# If we give no timestamp ...
Tool for the function get_decision_tree. :param str agent_id: the id of the agent to get the tree. It must be an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. :param int timestamp: Optional. The decision tree is comptuted at this timestamp. :default timestamp: None, means that we get the tree computed with all its context history. :param version: version of the tree to get. :type version: str or int :default version: default version of the tree. :return: decision tree. :rtype: dict.
[ "Tool", "for", "the", "function", "get_decision_tree", "." ]
8bc1a9038511540930371aacfdde0f4040e08f24
https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L485-L514
train
23,760
craft-ai/craft-ai-client-python
craftai/client.py
CraftAIClient.get_decision_tree
def get_decision_tree(self, agent_id, timestamp=None, version=DEFAULT_DECISION_TREE_VERSION): """Get decision tree. :param str agent_id: the id of the agent to get the tree. It must be an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. :param int timestamp: Optional. The decision tree is comptuted at this timestamp. :default timestamp: None, means that we get the tree computed with all its context history. :param version: version of the tree to get. :type version: str or int. :default version: default version of the tree. :return: decision tree. :rtype: dict. :raises CraftAiLongRequestTimeOutError: if the API doesn't get the tree in the time given by the configuration. """ # Raises an error when agent_id is invalid self._check_agent_id(agent_id) if self._config["decisionTreeRetrievalTimeout"] is False: # Don't retry return self._get_decision_tree(agent_id, timestamp, version) start = current_time_ms() while True: now = current_time_ms() if now - start > self._config["decisionTreeRetrievalTimeout"]: # Client side timeout raise CraftAiLongRequestTimeOutError() try: return self._get_decision_tree(agent_id, timestamp, version) except CraftAiLongRequestTimeOutError: # Do nothing and continue. continue
python
def get_decision_tree(self, agent_id, timestamp=None, version=DEFAULT_DECISION_TREE_VERSION): """Get decision tree. :param str agent_id: the id of the agent to get the tree. It must be an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. :param int timestamp: Optional. The decision tree is comptuted at this timestamp. :default timestamp: None, means that we get the tree computed with all its context history. :param version: version of the tree to get. :type version: str or int. :default version: default version of the tree. :return: decision tree. :rtype: dict. :raises CraftAiLongRequestTimeOutError: if the API doesn't get the tree in the time given by the configuration. """ # Raises an error when agent_id is invalid self._check_agent_id(agent_id) if self._config["decisionTreeRetrievalTimeout"] is False: # Don't retry return self._get_decision_tree(agent_id, timestamp, version) start = current_time_ms() while True: now = current_time_ms() if now - start > self._config["decisionTreeRetrievalTimeout"]: # Client side timeout raise CraftAiLongRequestTimeOutError() try: return self._get_decision_tree(agent_id, timestamp, version) except CraftAiLongRequestTimeOutError: # Do nothing and continue. continue
[ "def", "get_decision_tree", "(", "self", ",", "agent_id", ",", "timestamp", "=", "None", ",", "version", "=", "DEFAULT_DECISION_TREE_VERSION", ")", ":", "# Raises an error when agent_id is invalid", "self", ".", "_check_agent_id", "(", "agent_id", ")", "if", "self", ...
Get decision tree. :param str agent_id: the id of the agent to get the tree. It must be an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. :param int timestamp: Optional. The decision tree is comptuted at this timestamp. :default timestamp: None, means that we get the tree computed with all its context history. :param version: version of the tree to get. :type version: str or int. :default version: default version of the tree. :return: decision tree. :rtype: dict. :raises CraftAiLongRequestTimeOutError: if the API doesn't get the tree in the time given by the configuration.
[ "Get", "decision", "tree", "." ]
8bc1a9038511540930371aacfdde0f4040e08f24
https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L516-L552
train
23,761
craft-ai/craft-ai-client-python
craftai/client.py
CraftAIClient._get_decision_trees_bulk
def _get_decision_trees_bulk(self, payload, valid_indices, invalid_indices, invalid_dts): """Tool for the function get_decision_trees_bulk. :param list payload: contains the informations necessary for getting the trees. Its form is the same than for the function. get_decision_trees_bulk. :param list valid_indices: list of the indices of the valid agent id. :param list invalid_indices: list of the indices of the valid agent id. :param list invalid_dts: list of the invalid agent id. :return: decision trees. :rtype: list of dict. """ valid_dts = self._create_and_send_json_bulk([payload[i] for i in valid_indices], "{}/bulk/decision_tree".format(self._base_url), "POST") if invalid_indices == []: return valid_dts # Put the valid and invalid decision trees in their original index return self._recreate_list_with_indices(valid_indices, valid_dts, invalid_indices, invalid_dts)
python
def _get_decision_trees_bulk(self, payload, valid_indices, invalid_indices, invalid_dts): """Tool for the function get_decision_trees_bulk. :param list payload: contains the informations necessary for getting the trees. Its form is the same than for the function. get_decision_trees_bulk. :param list valid_indices: list of the indices of the valid agent id. :param list invalid_indices: list of the indices of the valid agent id. :param list invalid_dts: list of the invalid agent id. :return: decision trees. :rtype: list of dict. """ valid_dts = self._create_and_send_json_bulk([payload[i] for i in valid_indices], "{}/bulk/decision_tree".format(self._base_url), "POST") if invalid_indices == []: return valid_dts # Put the valid and invalid decision trees in their original index return self._recreate_list_with_indices(valid_indices, valid_dts, invalid_indices, invalid_dts)
[ "def", "_get_decision_trees_bulk", "(", "self", ",", "payload", ",", "valid_indices", ",", "invalid_indices", ",", "invalid_dts", ")", ":", "valid_dts", "=", "self", ".", "_create_and_send_json_bulk", "(", "[", "payload", "[", "i", "]", "for", "i", "in", "vali...
Tool for the function get_decision_trees_bulk. :param list payload: contains the informations necessary for getting the trees. Its form is the same than for the function. get_decision_trees_bulk. :param list valid_indices: list of the indices of the valid agent id. :param list invalid_indices: list of the indices of the valid agent id. :param list invalid_dts: list of the invalid agent id. :return: decision trees. :rtype: list of dict.
[ "Tool", "for", "the", "function", "get_decision_trees_bulk", "." ]
8bc1a9038511540930371aacfdde0f4040e08f24
https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L554-L575
train
23,762
craft-ai/craft-ai-client-python
craftai/client.py
CraftAIClient.get_decision_trees_bulk
def get_decision_trees_bulk(self, payload, version=DEFAULT_DECISION_TREE_VERSION): """Get a group of decision trees. :param list payload: contains the informations necessary for getting the trees. It's in the form [{"id": agent_id, "timestamp": timestamp}] With id a str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. It must referenced an existing agent. With timestamp an positive and not null integer. :param version: version of the tree to get. :type version: str or int. :default version: default version of the tree. :return: Decision trees. :rtype: list of dict. :raises CraftAiBadRequestError: if all of the ids are invalid or referenced non existing agents or all of the timestamp are invalid. :raises CraftAiLongRequestTimeOutError: if the API doesn't get the tree in the time given by the configuration. """ # payload = [{"id": agent_id, "timestamp": timestamp}] headers = self._headers.copy() headers["x-craft-ai-tree-version"] = version # Check all ids, raise an error if all ids are invalid valid_indices, invalid_indices, invalid_dts = self._check_agent_id_bulk(payload) if self._config["decisionTreeRetrievalTimeout"] is False: # Don't retry return self._get_decision_trees_bulk(payload, valid_indices, invalid_indices, invalid_dts) start = current_time_ms() while True: now = current_time_ms() if now - start > self._config["decisionTreeRetrievalTimeout"]: # Client side timeout raise CraftAiLongRequestTimeOutError() try: return self._get_decision_trees_bulk(payload, valid_indices, invalid_indices, invalid_dts) except CraftAiLongRequestTimeOutError: # Do nothing and continue. continue
python
def get_decision_trees_bulk(self, payload, version=DEFAULT_DECISION_TREE_VERSION): """Get a group of decision trees. :param list payload: contains the informations necessary for getting the trees. It's in the form [{"id": agent_id, "timestamp": timestamp}] With id a str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. It must referenced an existing agent. With timestamp an positive and not null integer. :param version: version of the tree to get. :type version: str or int. :default version: default version of the tree. :return: Decision trees. :rtype: list of dict. :raises CraftAiBadRequestError: if all of the ids are invalid or referenced non existing agents or all of the timestamp are invalid. :raises CraftAiLongRequestTimeOutError: if the API doesn't get the tree in the time given by the configuration. """ # payload = [{"id": agent_id, "timestamp": timestamp}] headers = self._headers.copy() headers["x-craft-ai-tree-version"] = version # Check all ids, raise an error if all ids are invalid valid_indices, invalid_indices, invalid_dts = self._check_agent_id_bulk(payload) if self._config["decisionTreeRetrievalTimeout"] is False: # Don't retry return self._get_decision_trees_bulk(payload, valid_indices, invalid_indices, invalid_dts) start = current_time_ms() while True: now = current_time_ms() if now - start > self._config["decisionTreeRetrievalTimeout"]: # Client side timeout raise CraftAiLongRequestTimeOutError() try: return self._get_decision_trees_bulk(payload, valid_indices, invalid_indices, invalid_dts) except CraftAiLongRequestTimeOutError: # Do nothing and continue. continue
[ "def", "get_decision_trees_bulk", "(", "self", ",", "payload", ",", "version", "=", "DEFAULT_DECISION_TREE_VERSION", ")", ":", "# payload = [{\"id\": agent_id, \"timestamp\": timestamp}]", "headers", "=", "self", ".", "_headers", ".", "copy", "(", ")", "headers", "[", ...
Get a group of decision trees. :param list payload: contains the informations necessary for getting the trees. It's in the form [{"id": agent_id, "timestamp": timestamp}] With id a str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. It must referenced an existing agent. With timestamp an positive and not null integer. :param version: version of the tree to get. :type version: str or int. :default version: default version of the tree. :return: Decision trees. :rtype: list of dict. :raises CraftAiBadRequestError: if all of the ids are invalid or referenced non existing agents or all of the timestamp are invalid. :raises CraftAiLongRequestTimeOutError: if the API doesn't get the tree in the time given by the configuration.
[ "Get", "a", "group", "of", "decision", "trees", "." ]
8bc1a9038511540930371aacfdde0f4040e08f24
https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L577-L623
train
23,763
craft-ai/craft-ai-client-python
craftai/client.py
CraftAIClient._decode_response
def _decode_response(response): """Decode the response of a request. :param response: response of a request. :return: decoded response. :raise Error: Raise the error given by the request. """ status_code = response.status_code message = "Status code " + str(status_code) try: message = CraftAIClient._parse_body(response)["message"] except (CraftAiInternalError, KeyError, TypeError): pass if status_code in [200, 201, 204, 207]: return CraftAIClient._parse_body(response) else: raise CraftAIClient._get_error_from_status(status_code, message) return None
python
def _decode_response(response): """Decode the response of a request. :param response: response of a request. :return: decoded response. :raise Error: Raise the error given by the request. """ status_code = response.status_code message = "Status code " + str(status_code) try: message = CraftAIClient._parse_body(response)["message"] except (CraftAiInternalError, KeyError, TypeError): pass if status_code in [200, 201, 204, 207]: return CraftAIClient._parse_body(response) else: raise CraftAIClient._get_error_from_status(status_code, message) return None
[ "def", "_decode_response", "(", "response", ")", ":", "status_code", "=", "response", ".", "status_code", "message", "=", "\"Status code \"", "+", "str", "(", "status_code", ")", "try", ":", "message", "=", "CraftAIClient", ".", "_parse_body", "(", "response", ...
Decode the response of a request. :param response: response of a request. :return: decoded response. :raise Error: Raise the error given by the request.
[ "Decode", "the", "response", "of", "a", "request", "." ]
8bc1a9038511540930371aacfdde0f4040e08f24
https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L639-L660
train
23,764
craft-ai/craft-ai-client-python
craftai/client.py
CraftAIClient._decode_response_bulk
def _decode_response_bulk(response_bulk): """Decode the response of each agent given by a bulk function. :param list response_bulk: list of dictionnary which represents the response for an agent. :return: decoded response. :rtype: list of dict. """ resp = [] for response in response_bulk: if ("status" in response) and (response.get("status") == 201): agent = {"id": response["id"], "message": response["message"]} resp.append(agent) elif "status" in response: status_code = response["status"] message = response["message"] agent = {"error": CraftAIClient._get_error_from_status(status_code, message)} try: agent["id"] = response["id"] except KeyError: pass resp.append(agent) else: resp.append(response) return resp
python
def _decode_response_bulk(response_bulk): """Decode the response of each agent given by a bulk function. :param list response_bulk: list of dictionnary which represents the response for an agent. :return: decoded response. :rtype: list of dict. """ resp = [] for response in response_bulk: if ("status" in response) and (response.get("status") == 201): agent = {"id": response["id"], "message": response["message"]} resp.append(agent) elif "status" in response: status_code = response["status"] message = response["message"] agent = {"error": CraftAIClient._get_error_from_status(status_code, message)} try: agent["id"] = response["id"] except KeyError: pass resp.append(agent) else: resp.append(response) return resp
[ "def", "_decode_response_bulk", "(", "response_bulk", ")", ":", "resp", "=", "[", "]", "for", "response", "in", "response_bulk", ":", "if", "(", "\"status\"", "in", "response", ")", "and", "(", "response", ".", "get", "(", "\"status\"", ")", "==", "201", ...
Decode the response of each agent given by a bulk function. :param list response_bulk: list of dictionnary which represents the response for an agent. :return: decoded response. :rtype: list of dict.
[ "Decode", "the", "response", "of", "each", "agent", "given", "by", "a", "bulk", "function", "." ]
8bc1a9038511540930371aacfdde0f4040e08f24
https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L663-L691
train
23,765
craft-ai/craft-ai-client-python
craftai/client.py
CraftAIClient._get_error_from_status
def _get_error_from_status(status_code, message): """Give the error corresponding to the status code. :param int status_code: status code of the response to a request. :param str message: error message given by the response. :return: error corresponding to the status code. :rtype: Error. """ if status_code == 202: err = CraftAiLongRequestTimeOutError(message) elif status_code == 401 or status_code == 403: err = CraftAiCredentialsError(message) elif status_code == 400: err = CraftAiBadRequestError(message) elif status_code == 404: err = CraftAiNotFoundError(message) elif status_code == 413: err = CraftAiBadRequestError("Given payload is too large") elif status_code == 500: err = CraftAiInternalError(message) elif status_code == 503: err = CraftAiNetworkError("""Service momentarily unavailable, please try""" """again in a few minutes. If the problem """ """persists please contact us at support@craft.ai""") elif status_code == 504: err = CraftAiBadRequestError("Request has timed out") else: err = CraftAiUnknownError(message) return err
python
def _get_error_from_status(status_code, message): """Give the error corresponding to the status code. :param int status_code: status code of the response to a request. :param str message: error message given by the response. :return: error corresponding to the status code. :rtype: Error. """ if status_code == 202: err = CraftAiLongRequestTimeOutError(message) elif status_code == 401 or status_code == 403: err = CraftAiCredentialsError(message) elif status_code == 400: err = CraftAiBadRequestError(message) elif status_code == 404: err = CraftAiNotFoundError(message) elif status_code == 413: err = CraftAiBadRequestError("Given payload is too large") elif status_code == 500: err = CraftAiInternalError(message) elif status_code == 503: err = CraftAiNetworkError("""Service momentarily unavailable, please try""" """again in a few minutes. If the problem """ """persists please contact us at support@craft.ai""") elif status_code == 504: err = CraftAiBadRequestError("Request has timed out") else: err = CraftAiUnknownError(message) return err
[ "def", "_get_error_from_status", "(", "status_code", ",", "message", ")", ":", "if", "status_code", "==", "202", ":", "err", "=", "CraftAiLongRequestTimeOutError", "(", "message", ")", "elif", "status_code", "==", "401", "or", "status_code", "==", "403", ":", ...
Give the error corresponding to the status code. :param int status_code: status code of the response to a request. :param str message: error message given by the response. :return: error corresponding to the status code. :rtype: Error.
[ "Give", "the", "error", "corresponding", "to", "the", "status", "code", "." ]
8bc1a9038511540930371aacfdde0f4040e08f24
https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L694-L725
train
23,766
craft-ai/craft-ai-client-python
craftai/client.py
CraftAIClient._check_agent_id
def _check_agent_id(agent_id): """Checks that the given agent_id is a valid non-empty string. :param str agent_id: agent id to check. :raise CraftAiBadRequestError: If the given agent_id is not of type string or if it is an empty string. """ if (not isinstance(agent_id, six.string_types) or AGENT_ID_PATTERN.match(agent_id) is None): raise CraftAiBadRequestError(ERROR_ID_MESSAGE)
python
def _check_agent_id(agent_id): """Checks that the given agent_id is a valid non-empty string. :param str agent_id: agent id to check. :raise CraftAiBadRequestError: If the given agent_id is not of type string or if it is an empty string. """ if (not isinstance(agent_id, six.string_types) or AGENT_ID_PATTERN.match(agent_id) is None): raise CraftAiBadRequestError(ERROR_ID_MESSAGE)
[ "def", "_check_agent_id", "(", "agent_id", ")", ":", "if", "(", "not", "isinstance", "(", "agent_id", ",", "six", ".", "string_types", ")", "or", "AGENT_ID_PATTERN", ".", "match", "(", "agent_id", ")", "is", "None", ")", ":", "raise", "CraftAiBadRequestError...
Checks that the given agent_id is a valid non-empty string. :param str agent_id: agent id to check. :raise CraftAiBadRequestError: If the given agent_id is not of type string or if it is an empty string.
[ "Checks", "that", "the", "given", "agent_id", "is", "a", "valid", "non", "-", "empty", "string", "." ]
8bc1a9038511540930371aacfdde0f4040e08f24
https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L728-L738
train
23,767
craft-ai/craft-ai-client-python
craftai/client.py
CraftAIClient._check_agent_id_bulk
def _check_agent_id_bulk(self, payload): """Checks that all the given agent ids are valid non-empty strings and if the agents are serializable. :param list payload: list of dictionnary which represents an agent. :return: list of the agents with valid ids, list of the agents with invalid ids, list of the dictionnaries with valid ids. :rtype: list, list, list of dict. :raise CraftAiBadRequestError: If all the agents are invalid. """ invalid_agent_indices = [] valid_agent_indices = [] invalid_payload = [] for index, agent in enumerate(payload): # Check if the agent ID is valid try: if "id" in agent: self._check_agent_id(agent["id"]) except CraftAiBadRequestError: invalid_agent_indices.append(index) invalid_payload.append({"id": agent["id"], "error": CraftAiBadRequestError(ERROR_ID_MESSAGE)}) else: # Check if the agent is serializable try: json.dumps([agent]) except TypeError as err: invalid_agent_indices.append(index) invalid_payload.append({"id": agent["id"], "error": err}) else: valid_agent_indices.append(index) if len(invalid_agent_indices) == len(payload): raise CraftAiBadRequestError(ERROR_ID_MESSAGE) return valid_agent_indices, invalid_agent_indices, invalid_payload
python
def _check_agent_id_bulk(self, payload): """Checks that all the given agent ids are valid non-empty strings and if the agents are serializable. :param list payload: list of dictionnary which represents an agent. :return: list of the agents with valid ids, list of the agents with invalid ids, list of the dictionnaries with valid ids. :rtype: list, list, list of dict. :raise CraftAiBadRequestError: If all the agents are invalid. """ invalid_agent_indices = [] valid_agent_indices = [] invalid_payload = [] for index, agent in enumerate(payload): # Check if the agent ID is valid try: if "id" in agent: self._check_agent_id(agent["id"]) except CraftAiBadRequestError: invalid_agent_indices.append(index) invalid_payload.append({"id": agent["id"], "error": CraftAiBadRequestError(ERROR_ID_MESSAGE)}) else: # Check if the agent is serializable try: json.dumps([agent]) except TypeError as err: invalid_agent_indices.append(index) invalid_payload.append({"id": agent["id"], "error": err}) else: valid_agent_indices.append(index) if len(invalid_agent_indices) == len(payload): raise CraftAiBadRequestError(ERROR_ID_MESSAGE) return valid_agent_indices, invalid_agent_indices, invalid_payload
[ "def", "_check_agent_id_bulk", "(", "self", ",", "payload", ")", ":", "invalid_agent_indices", "=", "[", "]", "valid_agent_indices", "=", "[", "]", "invalid_payload", "=", "[", "]", "for", "index", ",", "agent", "in", "enumerate", "(", "payload", ")", ":", ...
Checks that all the given agent ids are valid non-empty strings and if the agents are serializable. :param list payload: list of dictionnary which represents an agent. :return: list of the agents with valid ids, list of the agents with invalid ids, list of the dictionnaries with valid ids. :rtype: list, list, list of dict. :raise CraftAiBadRequestError: If all the agents are invalid.
[ "Checks", "that", "all", "the", "given", "agent", "ids", "are", "valid", "non", "-", "empty", "strings", "and", "if", "the", "agents", "are", "serializable", "." ]
8bc1a9038511540930371aacfdde0f4040e08f24
https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L740-L778
train
23,768
craft-ai/craft-ai-client-python
craftai/client.py
CraftAIClient._recreate_list_with_indices
def _recreate_list_with_indices(indices1, values1, indices2, values2): """Create a list in the right order. :param list indices1: contains the list of indices corresponding to the values in values1. :param list values1: contains the first list of values. :param list indices2: contains the list of indices corresponding to the values in values2. :param list values2: contains the second list of values. :return: list of the values in the correct order. :rtype: list. """ # Test if indices are continuous list_indices = sorted(indices1 + indices2) for i, index in enumerate(list_indices): if i != index: raise CraftAiInternalError("The agents's indices are not continuous") full_list = [None] * (len(indices1) + len(indices2)) for i, index in enumerate(indices1): full_list[index] = values1[i] for i, index in enumerate(indices2): full_list[index] = values2[i] return full_list
python
def _recreate_list_with_indices(indices1, values1, indices2, values2): """Create a list in the right order. :param list indices1: contains the list of indices corresponding to the values in values1. :param list values1: contains the first list of values. :param list indices2: contains the list of indices corresponding to the values in values2. :param list values2: contains the second list of values. :return: list of the values in the correct order. :rtype: list. """ # Test if indices are continuous list_indices = sorted(indices1 + indices2) for i, index in enumerate(list_indices): if i != index: raise CraftAiInternalError("The agents's indices are not continuous") full_list = [None] * (len(indices1) + len(indices2)) for i, index in enumerate(indices1): full_list[index] = values1[i] for i, index in enumerate(indices2): full_list[index] = values2[i] return full_list
[ "def", "_recreate_list_with_indices", "(", "indices1", ",", "values1", ",", "indices2", ",", "values2", ")", ":", "# Test if indices are continuous", "list_indices", "=", "sorted", "(", "indices1", "+", "indices2", ")", "for", "i", ",", "index", "in", "enumerate",...
Create a list in the right order. :param list indices1: contains the list of indices corresponding to the values in values1. :param list values1: contains the first list of values. :param list indices2: contains the list of indices corresponding to the values in values2. :param list values2: contains the second list of values. :return: list of the values in the correct order. :rtype: list.
[ "Create", "a", "list", "in", "the", "right", "order", "." ]
8bc1a9038511540930371aacfdde0f4040e08f24
https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L781-L805
train
23,769
craft-ai/craft-ai-client-python
craftai/client.py
CraftAIClient._create_and_send_json_bulk
def _create_and_send_json_bulk(self, payload, req_url, request_type="POST"): """Create a json, do a request to the URL and process the response. :param list payload: contains the informations necessary for the action. It's a list of dictionnary. :param str req_url: URL to request with the payload. :param str request_type: type of request, either "POST" or "DELETE". :default request_type: "POST". :return: response of the request. :rtype: list of dict. :raises CraftAiBadRequestError: if the payload doesn't have the correct form to be transformed into a json or request_type is neither "POST" or "DELETE". """ # Extra header in addition to the main session's ct_header = {"Content-Type": "application/json; charset=utf-8"} try: json_pl = json.dumps(payload) except TypeError as err: raise CraftAiBadRequestError("Error while dumping the payload into json" "format when converting it for the bulk request. {}" .format(err.__str__())) if request_type == "POST": resp = self._requests_session.post(req_url, headers=ct_header, data=json_pl) elif request_type == "DELETE": resp = self._requests_session.delete(req_url, headers=ct_header, data=json_pl) else: raise CraftAiBadRequestError("Request for the bulk API should be either a POST or DELETE" "request") agents = self._decode_response(resp) agents = self._decode_response_bulk(agents) return agents
python
def _create_and_send_json_bulk(self, payload, req_url, request_type="POST"): """Create a json, do a request to the URL and process the response. :param list payload: contains the informations necessary for the action. It's a list of dictionnary. :param str req_url: URL to request with the payload. :param str request_type: type of request, either "POST" or "DELETE". :default request_type: "POST". :return: response of the request. :rtype: list of dict. :raises CraftAiBadRequestError: if the payload doesn't have the correct form to be transformed into a json or request_type is neither "POST" or "DELETE". """ # Extra header in addition to the main session's ct_header = {"Content-Type": "application/json; charset=utf-8"} try: json_pl = json.dumps(payload) except TypeError as err: raise CraftAiBadRequestError("Error while dumping the payload into json" "format when converting it for the bulk request. {}" .format(err.__str__())) if request_type == "POST": resp = self._requests_session.post(req_url, headers=ct_header, data=json_pl) elif request_type == "DELETE": resp = self._requests_session.delete(req_url, headers=ct_header, data=json_pl) else: raise CraftAiBadRequestError("Request for the bulk API should be either a POST or DELETE" "request") agents = self._decode_response(resp) agents = self._decode_response_bulk(agents) return agents
[ "def", "_create_and_send_json_bulk", "(", "self", ",", "payload", ",", "req_url", ",", "request_type", "=", "\"POST\"", ")", ":", "# Extra header in addition to the main session's", "ct_header", "=", "{", "\"Content-Type\"", ":", "\"application/json; charset=utf-8\"", "}", ...
Create a json, do a request to the URL and process the response. :param list payload: contains the informations necessary for the action. It's a list of dictionnary. :param str req_url: URL to request with the payload. :param str request_type: type of request, either "POST" or "DELETE". :default request_type: "POST". :return: response of the request. :rtype: list of dict. :raises CraftAiBadRequestError: if the payload doesn't have the correct form to be transformed into a json or request_type is neither "POST" or "DELETE".
[ "Create", "a", "json", "do", "a", "request", "to", "the", "URL", "and", "process", "the", "response", "." ]
8bc1a9038511540930371aacfdde0f4040e08f24
https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L807-L844
train
23,770
Shizmob/pydle
pydle/features/ctcp.py
construct_ctcp
def construct_ctcp(*parts): """ Construct CTCP message. """ message = ' '.join(parts) message = message.replace('\0', CTCP_ESCAPE_CHAR + '0') message = message.replace('\n', CTCP_ESCAPE_CHAR + 'n') message = message.replace('\r', CTCP_ESCAPE_CHAR + 'r') message = message.replace(CTCP_ESCAPE_CHAR, CTCP_ESCAPE_CHAR + CTCP_ESCAPE_CHAR) return CTCP_DELIMITER + message + CTCP_DELIMITER
python
def construct_ctcp(*parts): """ Construct CTCP message. """ message = ' '.join(parts) message = message.replace('\0', CTCP_ESCAPE_CHAR + '0') message = message.replace('\n', CTCP_ESCAPE_CHAR + 'n') message = message.replace('\r', CTCP_ESCAPE_CHAR + 'r') message = message.replace(CTCP_ESCAPE_CHAR, CTCP_ESCAPE_CHAR + CTCP_ESCAPE_CHAR) return CTCP_DELIMITER + message + CTCP_DELIMITER
[ "def", "construct_ctcp", "(", "*", "parts", ")", ":", "message", "=", "' '", ".", "join", "(", "parts", ")", "message", "=", "message", ".", "replace", "(", "'\\0'", ",", "CTCP_ESCAPE_CHAR", "+", "'0'", ")", "message", "=", "message", ".", "replace", "...
Construct CTCP message.
[ "Construct", "CTCP", "message", "." ]
7ec7d65d097318ed0bcdc5d8401470287d8c7cf7
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ctcp.py#L105-L112
train
23,771
Shizmob/pydle
pydle/features/ctcp.py
parse_ctcp
def parse_ctcp(query): """ Strip and de-quote CTCP messages. """ query = query.strip(CTCP_DELIMITER) query = query.replace(CTCP_ESCAPE_CHAR + '0', '\0') query = query.replace(CTCP_ESCAPE_CHAR + 'n', '\n') query = query.replace(CTCP_ESCAPE_CHAR + 'r', '\r') query = query.replace(CTCP_ESCAPE_CHAR + CTCP_ESCAPE_CHAR, CTCP_ESCAPE_CHAR) if ' ' in query: return query.split(' ', 1) return query, None
python
def parse_ctcp(query): """ Strip and de-quote CTCP messages. """ query = query.strip(CTCP_DELIMITER) query = query.replace(CTCP_ESCAPE_CHAR + '0', '\0') query = query.replace(CTCP_ESCAPE_CHAR + 'n', '\n') query = query.replace(CTCP_ESCAPE_CHAR + 'r', '\r') query = query.replace(CTCP_ESCAPE_CHAR + CTCP_ESCAPE_CHAR, CTCP_ESCAPE_CHAR) if ' ' in query: return query.split(' ', 1) return query, None
[ "def", "parse_ctcp", "(", "query", ")", ":", "query", "=", "query", ".", "strip", "(", "CTCP_DELIMITER", ")", "query", "=", "query", ".", "replace", "(", "CTCP_ESCAPE_CHAR", "+", "'0'", ",", "'\\0'", ")", "query", "=", "query", ".", "replace", "(", "CT...
Strip and de-quote CTCP messages.
[ "Strip", "and", "de", "-", "quote", "CTCP", "messages", "." ]
7ec7d65d097318ed0bcdc5d8401470287d8c7cf7
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ctcp.py#L114-L123
train
23,772
Shizmob/pydle
pydle/features/ctcp.py
CTCPSupport.on_ctcp_version
async def on_ctcp_version(self, by, target, contents): """ Built-in CTCP version as some networks seem to require it. """ import pydle version = '{name} v{ver}'.format(name=pydle.__name__, ver=pydle.__version__) self.ctcp_reply(by, 'VERSION', version)
python
async def on_ctcp_version(self, by, target, contents): """ Built-in CTCP version as some networks seem to require it. """ import pydle version = '{name} v{ver}'.format(name=pydle.__name__, ver=pydle.__version__) self.ctcp_reply(by, 'VERSION', version)
[ "async", "def", "on_ctcp_version", "(", "self", ",", "by", ",", "target", ",", "contents", ")", ":", "import", "pydle", "version", "=", "'{name} v{ver}'", ".", "format", "(", "name", "=", "pydle", ".", "__name__", ",", "ver", "=", "pydle", ".", "__versio...
Built-in CTCP version as some networks seem to require it.
[ "Built", "-", "in", "CTCP", "version", "as", "some", "networks", "seem", "to", "require", "it", "." ]
7ec7d65d097318ed0bcdc5d8401470287d8c7cf7
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ctcp.py#L34-L39
train
23,773
Shizmob/pydle
pydle/features/ctcp.py
CTCPSupport.ctcp
async def ctcp(self, target, query, contents=None): """ Send a CTCP request to a target. """ if self.is_channel(target) and not self.in_channel(target): raise client.NotInChannel(target) await self.message(target, construct_ctcp(query, contents))
python
async def ctcp(self, target, query, contents=None): """ Send a CTCP request to a target. """ if self.is_channel(target) and not self.in_channel(target): raise client.NotInChannel(target) await self.message(target, construct_ctcp(query, contents))
[ "async", "def", "ctcp", "(", "self", ",", "target", ",", "query", ",", "contents", "=", "None", ")", ":", "if", "self", ".", "is_channel", "(", "target", ")", "and", "not", "self", ".", "in_channel", "(", "target", ")", ":", "raise", "client", ".", ...
Send a CTCP request to a target.
[ "Send", "a", "CTCP", "request", "to", "a", "target", "." ]
7ec7d65d097318ed0bcdc5d8401470287d8c7cf7
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ctcp.py#L44-L49
train
23,774
Shizmob/pydle
pydle/features/ctcp.py
CTCPSupport.ctcp_reply
async def ctcp_reply(self, target, query, response): """ Send a CTCP reply to a target. """ if self.is_channel(target) and not self.in_channel(target): raise client.NotInChannel(target) await self.notice(target, construct_ctcp(query, response))
python
async def ctcp_reply(self, target, query, response): """ Send a CTCP reply to a target. """ if self.is_channel(target) and not self.in_channel(target): raise client.NotInChannel(target) await self.notice(target, construct_ctcp(query, response))
[ "async", "def", "ctcp_reply", "(", "self", ",", "target", ",", "query", ",", "response", ")", ":", "if", "self", ".", "is_channel", "(", "target", ")", "and", "not", "self", ".", "in_channel", "(", "target", ")", ":", "raise", "client", ".", "NotInChan...
Send a CTCP reply to a target.
[ "Send", "a", "CTCP", "reply", "to", "a", "target", "." ]
7ec7d65d097318ed0bcdc5d8401470287d8c7cf7
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ctcp.py#L51-L56
train
23,775
Shizmob/pydle
pydle/features/ctcp.py
CTCPSupport.on_raw_privmsg
async def on_raw_privmsg(self, message): """ Modify PRIVMSG to redirect CTCP messages. """ nick, metadata = self._parse_user(message.source) target, msg = message.params if is_ctcp(msg): self._sync_user(nick, metadata) type, contents = parse_ctcp(msg) # Find dedicated handler if it exists. attr = 'on_ctcp_' + pydle.protocol.identifierify(type) if hasattr(self, attr): await getattr(self, attr)(nick, target, contents) # Invoke global handler. await self.on_ctcp(nick, target, type, contents) else: await super().on_raw_privmsg(message)
python
async def on_raw_privmsg(self, message): """ Modify PRIVMSG to redirect CTCP messages. """ nick, metadata = self._parse_user(message.source) target, msg = message.params if is_ctcp(msg): self._sync_user(nick, metadata) type, contents = parse_ctcp(msg) # Find dedicated handler if it exists. attr = 'on_ctcp_' + pydle.protocol.identifierify(type) if hasattr(self, attr): await getattr(self, attr)(nick, target, contents) # Invoke global handler. await self.on_ctcp(nick, target, type, contents) else: await super().on_raw_privmsg(message)
[ "async", "def", "on_raw_privmsg", "(", "self", ",", "message", ")", ":", "nick", ",", "metadata", "=", "self", ".", "_parse_user", "(", "message", ".", "source", ")", "target", ",", "msg", "=", "message", ".", "params", "if", "is_ctcp", "(", "msg", ")"...
Modify PRIVMSG to redirect CTCP messages.
[ "Modify", "PRIVMSG", "to", "redirect", "CTCP", "messages", "." ]
7ec7d65d097318ed0bcdc5d8401470287d8c7cf7
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ctcp.py#L61-L77
train
23,776
Shizmob/pydle
pydle/features/ctcp.py
CTCPSupport.on_raw_notice
async def on_raw_notice(self, message): """ Modify NOTICE to redirect CTCP messages. """ nick, metadata = self._parse_user(message.source) target, msg = message.params if is_ctcp(msg): self._sync_user(nick, metadata) type, response = parse_ctcp(msg) # Find dedicated handler if it exists. attr = 'on_ctcp_' + pydle.protocol.identifierify(type) + '_reply' if hasattr(self, attr): await getattr(self, attr)(user, target, response) # Invoke global handler. await self.on_ctcp_reply(user, target, type, response) else: await super().on_raw_notice(message)
python
async def on_raw_notice(self, message): """ Modify NOTICE to redirect CTCP messages. """ nick, metadata = self._parse_user(message.source) target, msg = message.params if is_ctcp(msg): self._sync_user(nick, metadata) type, response = parse_ctcp(msg) # Find dedicated handler if it exists. attr = 'on_ctcp_' + pydle.protocol.identifierify(type) + '_reply' if hasattr(self, attr): await getattr(self, attr)(user, target, response) # Invoke global handler. await self.on_ctcp_reply(user, target, type, response) else: await super().on_raw_notice(message)
[ "async", "def", "on_raw_notice", "(", "self", ",", "message", ")", ":", "nick", ",", "metadata", "=", "self", ".", "_parse_user", "(", "message", ".", "source", ")", "target", ",", "msg", "=", "message", ".", "params", "if", "is_ctcp", "(", "msg", ")",...
Modify NOTICE to redirect CTCP messages.
[ "Modify", "NOTICE", "to", "redirect", "CTCP", "messages", "." ]
7ec7d65d097318ed0bcdc5d8401470287d8c7cf7
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ctcp.py#L80-L96
train
23,777
Shizmob/pydle
pydle/features/ircv3/cap.py
CapabilityNegotiationSupport._register
async def _register(self): """ Hijack registration to send a CAP LS first. """ if self.registered: self.logger.debug("skipping cap registration, already registered!") return # Ask server to list capabilities. await self.rawmsg('CAP', 'LS', '302') # Register as usual. await super()._register()
python
async def _register(self): """ Hijack registration to send a CAP LS first. """ if self.registered: self.logger.debug("skipping cap registration, already registered!") return # Ask server to list capabilities. await self.rawmsg('CAP', 'LS', '302') # Register as usual. await super()._register()
[ "async", "def", "_register", "(", "self", ")", ":", "if", "self", ".", "registered", ":", "self", ".", "logger", ".", "debug", "(", "\"skipping cap registration, already registered!\"", ")", "return", "# Ask server to list capabilities.", "await", "self", ".", "rawm...
Hijack registration to send a CAP LS first.
[ "Hijack", "registration", "to", "send", "a", "CAP", "LS", "first", "." ]
7ec7d65d097318ed0bcdc5d8401470287d8c7cf7
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/cap.py#L31-L41
train
23,778
Shizmob/pydle
pydle/features/ircv3/cap.py
CapabilityNegotiationSupport._capability_negotiated
async def _capability_negotiated(self, capab): """ Mark capability as negotiated, and end negotiation if we're done. """ self._capabilities_negotiating.discard(capab) if not self._capabilities_requested and not self._capabilities_negotiating: await self.rawmsg('CAP', 'END')
python
async def _capability_negotiated(self, capab): """ Mark capability as negotiated, and end negotiation if we're done. """ self._capabilities_negotiating.discard(capab) if not self._capabilities_requested and not self._capabilities_negotiating: await self.rawmsg('CAP', 'END')
[ "async", "def", "_capability_negotiated", "(", "self", ",", "capab", ")", ":", "self", ".", "_capabilities_negotiating", ".", "discard", "(", "capab", ")", "if", "not", "self", ".", "_capabilities_requested", "and", "not", "self", ".", "_capabilities_negotiating",...
Mark capability as negotiated, and end negotiation if we're done.
[ "Mark", "capability", "as", "negotiated", "and", "end", "negotiation", "if", "we", "re", "done", "." ]
7ec7d65d097318ed0bcdc5d8401470287d8c7cf7
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/cap.py#L55-L60
train
23,779
Shizmob/pydle
pydle/features/ircv3/cap.py
CapabilityNegotiationSupport.on_raw_cap
async def on_raw_cap(self, message): """ Handle CAP message. """ target, subcommand = message.params[:2] params = message.params[2:] # Call handler. attr = 'on_raw_cap_' + pydle.protocol.identifierify(subcommand) if hasattr(self, attr): await getattr(self, attr)(params) else: self.logger.warning('Unknown CAP subcommand sent from server: %s', subcommand)
python
async def on_raw_cap(self, message): """ Handle CAP message. """ target, subcommand = message.params[:2] params = message.params[2:] # Call handler. attr = 'on_raw_cap_' + pydle.protocol.identifierify(subcommand) if hasattr(self, attr): await getattr(self, attr)(params) else: self.logger.warning('Unknown CAP subcommand sent from server: %s', subcommand)
[ "async", "def", "on_raw_cap", "(", "self", ",", "message", ")", ":", "target", ",", "subcommand", "=", "message", ".", "params", "[", ":", "2", "]", "params", "=", "message", ".", "params", "[", "2", ":", "]", "# Call handler.", "attr", "=", "'on_raw_c...
Handle CAP message.
[ "Handle", "CAP", "message", "." ]
7ec7d65d097318ed0bcdc5d8401470287d8c7cf7
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/cap.py#L65-L75
train
23,780
Shizmob/pydle
pydle/features/ircv3/cap.py
CapabilityNegotiationSupport.on_raw_cap_ls
async def on_raw_cap_ls(self, params): """ Update capability mapping. Request capabilities. """ to_request = set() for capab in params[0].split(): capab, value = self._capability_normalize(capab) # Only process new capabilities. if capab in self._capabilities: continue # Check if we support the capability. attr = 'on_capability_' + pydle.protocol.identifierify(capab) + '_available' supported = (await getattr(self, attr)(value)) if hasattr(self, attr) else False if supported: if isinstance(supported, str): to_request.add(capab + CAPABILITY_VALUE_DIVIDER + supported) else: to_request.add(capab) else: self._capabilities[capab] = False if to_request: # Request some capabilities. self._capabilities_requested.update(x.split(CAPABILITY_VALUE_DIVIDER, 1)[0] for x in to_request) await self.rawmsg('CAP', 'REQ', ' '.join(to_request)) else: # No capabilities requested, end negotiation. await self.rawmsg('CAP', 'END')
python
async def on_raw_cap_ls(self, params): """ Update capability mapping. Request capabilities. """ to_request = set() for capab in params[0].split(): capab, value = self._capability_normalize(capab) # Only process new capabilities. if capab in self._capabilities: continue # Check if we support the capability. attr = 'on_capability_' + pydle.protocol.identifierify(capab) + '_available' supported = (await getattr(self, attr)(value)) if hasattr(self, attr) else False if supported: if isinstance(supported, str): to_request.add(capab + CAPABILITY_VALUE_DIVIDER + supported) else: to_request.add(capab) else: self._capabilities[capab] = False if to_request: # Request some capabilities. self._capabilities_requested.update(x.split(CAPABILITY_VALUE_DIVIDER, 1)[0] for x in to_request) await self.rawmsg('CAP', 'REQ', ' '.join(to_request)) else: # No capabilities requested, end negotiation. await self.rawmsg('CAP', 'END')
[ "async", "def", "on_raw_cap_ls", "(", "self", ",", "params", ")", ":", "to_request", "=", "set", "(", ")", "for", "capab", "in", "params", "[", "0", "]", ".", "split", "(", ")", ":", "capab", ",", "value", "=", "self", ".", "_capability_normalize", "...
Update capability mapping. Request capabilities.
[ "Update", "capability", "mapping", ".", "Request", "capabilities", "." ]
7ec7d65d097318ed0bcdc5d8401470287d8c7cf7
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/cap.py#L77-L106
train
23,781
Shizmob/pydle
pydle/features/ircv3/cap.py
CapabilityNegotiationSupport.on_raw_cap_list
async def on_raw_cap_list(self, params): """ Update active capabilities. """ self._capabilities = { capab: False for capab in self._capabilities } for capab in params[0].split(): capab, value = self._capability_normalize(capab) self._capabilities[capab] = value if value else True
python
async def on_raw_cap_list(self, params): """ Update active capabilities. """ self._capabilities = { capab: False for capab in self._capabilities } for capab in params[0].split(): capab, value = self._capability_normalize(capab) self._capabilities[capab] = value if value else True
[ "async", "def", "on_raw_cap_list", "(", "self", ",", "params", ")", ":", "self", ".", "_capabilities", "=", "{", "capab", ":", "False", "for", "capab", "in", "self", ".", "_capabilities", "}", "for", "capab", "in", "params", "[", "0", "]", ".", "split"...
Update active capabilities.
[ "Update", "active", "capabilities", "." ]
7ec7d65d097318ed0bcdc5d8401470287d8c7cf7
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/cap.py#L108-L114
train
23,782
Shizmob/pydle
pydle/features/ircv3/cap.py
CapabilityNegotiationSupport.on_raw_410
async def on_raw_410(self, message): """ Unknown CAP subcommand or CAP error. Force-end negotiations. """ self.logger.error('Server sent "Unknown CAP subcommand: %s". Aborting capability negotiation.', message.params[0]) self._capabilities_requested = set() self._capabilities_negotiating = set() await self.rawmsg('CAP', 'END')
python
async def on_raw_410(self, message): """ Unknown CAP subcommand or CAP error. Force-end negotiations. """ self.logger.error('Server sent "Unknown CAP subcommand: %s". Aborting capability negotiation.', message.params[0]) self._capabilities_requested = set() self._capabilities_negotiating = set() await self.rawmsg('CAP', 'END')
[ "async", "def", "on_raw_410", "(", "self", ",", "message", ")", ":", "self", ".", "logger", ".", "error", "(", "'Server sent \"Unknown CAP subcommand: %s\". Aborting capability negotiation.'", ",", "message", ".", "params", "[", "0", "]", ")", "self", ".", "_capab...
Unknown CAP subcommand or CAP error. Force-end negotiations.
[ "Unknown", "CAP", "subcommand", "or", "CAP", "error", ".", "Force", "-", "end", "negotiations", "." ]
7ec7d65d097318ed0bcdc5d8401470287d8c7cf7
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/cap.py#L179-L185
train
23,783
Shizmob/pydle
pydle/features/ircv3/sasl.py
SASLSupport._sasl_start
async def _sasl_start(self, mechanism): """ Initiate SASL authentication. """ # The rest will be handled in on_raw_authenticate()/_sasl_respond(). await self.rawmsg('AUTHENTICATE', mechanism) # create a partial, required for our callback to get the kwarg _sasl_partial = partial(self._sasl_abort, timeout=True) self._sasl_timer = self.eventloop.call_later(self.SASL_TIMEOUT, _sasl_partial)
python
async def _sasl_start(self, mechanism): """ Initiate SASL authentication. """ # The rest will be handled in on_raw_authenticate()/_sasl_respond(). await self.rawmsg('AUTHENTICATE', mechanism) # create a partial, required for our callback to get the kwarg _sasl_partial = partial(self._sasl_abort, timeout=True) self._sasl_timer = self.eventloop.call_later(self.SASL_TIMEOUT, _sasl_partial)
[ "async", "def", "_sasl_start", "(", "self", ",", "mechanism", ")", ":", "# The rest will be handled in on_raw_authenticate()/_sasl_respond().", "await", "self", ".", "rawmsg", "(", "'AUTHENTICATE'", ",", "mechanism", ")", "# create a partial, required for our callback to get th...
Initiate SASL authentication.
[ "Initiate", "SASL", "authentication", "." ]
7ec7d65d097318ed0bcdc5d8401470287d8c7cf7
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/sasl.py#L45-L51
train
23,784
Shizmob/pydle
pydle/features/ircv3/sasl.py
SASLSupport._sasl_abort
async def _sasl_abort(self, timeout=False): """ Abort SASL authentication. """ if timeout: self.logger.error('SASL authentication timed out: aborting.') else: self.logger.error('SASL authentication aborted.') if self._sasl_timer: self._sasl_timer.cancel() self._sasl_timer = None # We're done here. await self.rawmsg('AUTHENTICATE', ABORT_MESSAGE) await self._capability_negotiated('sasl')
python
async def _sasl_abort(self, timeout=False): """ Abort SASL authentication. """ if timeout: self.logger.error('SASL authentication timed out: aborting.') else: self.logger.error('SASL authentication aborted.') if self._sasl_timer: self._sasl_timer.cancel() self._sasl_timer = None # We're done here. await self.rawmsg('AUTHENTICATE', ABORT_MESSAGE) await self._capability_negotiated('sasl')
[ "async", "def", "_sasl_abort", "(", "self", ",", "timeout", "=", "False", ")", ":", "if", "timeout", ":", "self", ".", "logger", ".", "error", "(", "'SASL authentication timed out: aborting.'", ")", "else", ":", "self", ".", "logger", ".", "error", "(", "'...
Abort SASL authentication.
[ "Abort", "SASL", "authentication", "." ]
7ec7d65d097318ed0bcdc5d8401470287d8c7cf7
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/sasl.py#L53-L67
train
23,785
Shizmob/pydle
pydle/features/ircv3/sasl.py
SASLSupport._sasl_end
async def _sasl_end(self): """ Finalize SASL authentication. """ if self._sasl_timer: self._sasl_timer.cancel() self._sasl_timer = None await self._capability_negotiated('sasl')
python
async def _sasl_end(self): """ Finalize SASL authentication. """ if self._sasl_timer: self._sasl_timer.cancel() self._sasl_timer = None await self._capability_negotiated('sasl')
[ "async", "def", "_sasl_end", "(", "self", ")", ":", "if", "self", ".", "_sasl_timer", ":", "self", ".", "_sasl_timer", ".", "cancel", "(", ")", "self", ".", "_sasl_timer", "=", "None", "await", "self", ".", "_capability_negotiated", "(", "'sasl'", ")" ]
Finalize SASL authentication.
[ "Finalize", "SASL", "authentication", "." ]
7ec7d65d097318ed0bcdc5d8401470287d8c7cf7
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/sasl.py#L69-L74
train
23,786
Shizmob/pydle
pydle/features/ircv3/sasl.py
SASLSupport._sasl_respond
async def _sasl_respond(self): """ Respond to SASL challenge with response. """ # Formulate a response. if self._sasl_client: try: response = self._sasl_client.process(self._sasl_challenge) except puresasl.SASLError: response = None if response is None: self.logger.warning('SASL challenge processing failed: aborting SASL authentication.') await self._sasl_abort() else: response = b'' response = base64.b64encode(response).decode(self.encoding) to_send = len(response) self._sasl_challenge = b'' # Send response in chunks. while to_send > 0: await self.rawmsg('AUTHENTICATE', response[:RESPONSE_LIMIT]) response = response[RESPONSE_LIMIT:] to_send -= RESPONSE_LIMIT # If our message fit exactly in SASL_RESPOSE_LIMIT-byte chunks, send an empty message to indicate we're done. if to_send == 0: await self.rawmsg('AUTHENTICATE', EMPTY_MESSAGE)
python
async def _sasl_respond(self): """ Respond to SASL challenge with response. """ # Formulate a response. if self._sasl_client: try: response = self._sasl_client.process(self._sasl_challenge) except puresasl.SASLError: response = None if response is None: self.logger.warning('SASL challenge processing failed: aborting SASL authentication.') await self._sasl_abort() else: response = b'' response = base64.b64encode(response).decode(self.encoding) to_send = len(response) self._sasl_challenge = b'' # Send response in chunks. while to_send > 0: await self.rawmsg('AUTHENTICATE', response[:RESPONSE_LIMIT]) response = response[RESPONSE_LIMIT:] to_send -= RESPONSE_LIMIT # If our message fit exactly in SASL_RESPOSE_LIMIT-byte chunks, send an empty message to indicate we're done. if to_send == 0: await self.rawmsg('AUTHENTICATE', EMPTY_MESSAGE)
[ "async", "def", "_sasl_respond", "(", "self", ")", ":", "# Formulate a response.", "if", "self", ".", "_sasl_client", ":", "try", ":", "response", "=", "self", ".", "_sasl_client", ".", "process", "(", "self", ".", "_sasl_challenge", ")", "except", "puresasl",...
Respond to SASL challenge with response.
[ "Respond", "to", "SASL", "challenge", "with", "response", "." ]
7ec7d65d097318ed0bcdc5d8401470287d8c7cf7
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/sasl.py#L76-L103
train
23,787
Shizmob/pydle
pydle/features/ircv3/sasl.py
SASLSupport.on_capability_sasl_available
async def on_capability_sasl_available(self, value): """ Check whether or not SASL is available. """ if value: self._sasl_mechanisms = value.upper().split(',') else: self._sasl_mechanisms = None if self.sasl_mechanism == 'EXTERNAL' or (self.sasl_username and self.sasl_password): if self.sasl_mechanism == 'EXTERNAL' or puresasl: return True self.logger.warning('SASL credentials set but puresasl module not found: not initiating SASL authentication.') return False
python
async def on_capability_sasl_available(self, value): """ Check whether or not SASL is available. """ if value: self._sasl_mechanisms = value.upper().split(',') else: self._sasl_mechanisms = None if self.sasl_mechanism == 'EXTERNAL' or (self.sasl_username and self.sasl_password): if self.sasl_mechanism == 'EXTERNAL' or puresasl: return True self.logger.warning('SASL credentials set but puresasl module not found: not initiating SASL authentication.') return False
[ "async", "def", "on_capability_sasl_available", "(", "self", ",", "value", ")", ":", "if", "value", ":", "self", ".", "_sasl_mechanisms", "=", "value", ".", "upper", "(", ")", ".", "split", "(", "','", ")", "else", ":", "self", ".", "_sasl_mechanisms", "...
Check whether or not SASL is available.
[ "Check", "whether", "or", "not", "SASL", "is", "available", "." ]
7ec7d65d097318ed0bcdc5d8401470287d8c7cf7
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/sasl.py#L108-L119
train
23,788
Shizmob/pydle
pydle/features/ircv3/sasl.py
SASLSupport.on_capability_sasl_enabled
async def on_capability_sasl_enabled(self): """ Start SASL authentication. """ if self.sasl_mechanism: if self._sasl_mechanisms and self.sasl_mechanism not in self._sasl_mechanisms: self.logger.warning('Requested SASL mechanism is not in server mechanism list: aborting SASL authentication.') return cap.failed mechanisms = [self.sasl_mechanism] else: mechanisms = self._sasl_mechanisms or ['PLAIN'] if mechanisms == ['EXTERNAL']: mechanism = 'EXTERNAL' else: self._sasl_client = puresasl.client.SASLClient(self.connection.hostname, 'irc', username=self.sasl_username, password=self.sasl_password, identity=self.sasl_identity ) try: self._sasl_client.choose_mechanism(mechanisms, allow_anonymous=False) except puresasl.SASLError: self.logger.exception('SASL mechanism choice failed: aborting SASL authentication.') return cap.FAILED mechanism = self._sasl_client.mechanism.upper() # Initialize SASL. await self._sasl_start(mechanism) # Tell caller we need more time, and to not end capability negotiation just yet. return cap.NEGOTIATING
python
async def on_capability_sasl_enabled(self): """ Start SASL authentication. """ if self.sasl_mechanism: if self._sasl_mechanisms and self.sasl_mechanism not in self._sasl_mechanisms: self.logger.warning('Requested SASL mechanism is not in server mechanism list: aborting SASL authentication.') return cap.failed mechanisms = [self.sasl_mechanism] else: mechanisms = self._sasl_mechanisms or ['PLAIN'] if mechanisms == ['EXTERNAL']: mechanism = 'EXTERNAL' else: self._sasl_client = puresasl.client.SASLClient(self.connection.hostname, 'irc', username=self.sasl_username, password=self.sasl_password, identity=self.sasl_identity ) try: self._sasl_client.choose_mechanism(mechanisms, allow_anonymous=False) except puresasl.SASLError: self.logger.exception('SASL mechanism choice failed: aborting SASL authentication.') return cap.FAILED mechanism = self._sasl_client.mechanism.upper() # Initialize SASL. await self._sasl_start(mechanism) # Tell caller we need more time, and to not end capability negotiation just yet. return cap.NEGOTIATING
[ "async", "def", "on_capability_sasl_enabled", "(", "self", ")", ":", "if", "self", ".", "sasl_mechanism", ":", "if", "self", ".", "_sasl_mechanisms", "and", "self", ".", "sasl_mechanism", "not", "in", "self", ".", "_sasl_mechanisms", ":", "self", ".", "logger"...
Start SASL authentication.
[ "Start", "SASL", "authentication", "." ]
7ec7d65d097318ed0bcdc5d8401470287d8c7cf7
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/sasl.py#L121-L150
train
23,789
Shizmob/pydle
pydle/features/ircv3/sasl.py
SASLSupport.on_raw_authenticate
async def on_raw_authenticate(self, message): """ Received part of the authentication challenge. """ # Cancel timeout timer. if self._sasl_timer: self._sasl_timer.cancel() self._sasl_timer = None # Add response data. response = ' '.join(message.params) if response != EMPTY_MESSAGE: self._sasl_challenge += base64.b64decode(response) # If the response ain't exactly SASL_RESPONSE_LIMIT bytes long, it's the end. Process. if len(response) % RESPONSE_LIMIT > 0: await self._sasl_respond() else: # Response not done yet. Restart timer. self._sasl_timer = self.eventloop.call_later(self.SASL_TIMEOUT, self._sasl_abort(timeout=True))
python
async def on_raw_authenticate(self, message): """ Received part of the authentication challenge. """ # Cancel timeout timer. if self._sasl_timer: self._sasl_timer.cancel() self._sasl_timer = None # Add response data. response = ' '.join(message.params) if response != EMPTY_MESSAGE: self._sasl_challenge += base64.b64decode(response) # If the response ain't exactly SASL_RESPONSE_LIMIT bytes long, it's the end. Process. if len(response) % RESPONSE_LIMIT > 0: await self._sasl_respond() else: # Response not done yet. Restart timer. self._sasl_timer = self.eventloop.call_later(self.SASL_TIMEOUT, self._sasl_abort(timeout=True))
[ "async", "def", "on_raw_authenticate", "(", "self", ",", "message", ")", ":", "# Cancel timeout timer.", "if", "self", ".", "_sasl_timer", ":", "self", ".", "_sasl_timer", ".", "cancel", "(", ")", "self", ".", "_sasl_timer", "=", "None", "# Add response data.", ...
Received part of the authentication challenge.
[ "Received", "part", "of", "the", "authentication", "challenge", "." ]
7ec7d65d097318ed0bcdc5d8401470287d8c7cf7
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/sasl.py#L155-L172
train
23,790
Shizmob/pydle
pydle/features/ircv3/monitor.py
MonitoringSupport.monitor
def monitor(self, target): """ Start monitoring the online status of a user. Returns whether or not the server supports monitoring. """ if 'monitor-notify' in self._capabilities and not self.is_monitoring(target): yield from self.rawmsg('MONITOR', '+', target) self._monitoring.add(target) return True else: return False
python
def monitor(self, target): """ Start monitoring the online status of a user. Returns whether or not the server supports monitoring. """ if 'monitor-notify' in self._capabilities and not self.is_monitoring(target): yield from self.rawmsg('MONITOR', '+', target) self._monitoring.add(target) return True else: return False
[ "def", "monitor", "(", "self", ",", "target", ")", ":", "if", "'monitor-notify'", "in", "self", ".", "_capabilities", "and", "not", "self", ".", "is_monitoring", "(", "target", ")", ":", "yield", "from", "self", ".", "rawmsg", "(", "'MONITOR'", ",", "'+'...
Start monitoring the online status of a user. Returns whether or not the server supports monitoring.
[ "Start", "monitoring", "the", "online", "status", "of", "a", "user", ".", "Returns", "whether", "or", "not", "the", "server", "supports", "monitoring", "." ]
7ec7d65d097318ed0bcdc5d8401470287d8c7cf7
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/monitor.py#L39-L46
train
23,791
Shizmob/pydle
pydle/features/ircv3/monitor.py
MonitoringSupport.unmonitor
def unmonitor(self, target): """ Stop monitoring the online status of a user. Returns whether or not the server supports monitoring. """ if 'monitor-notify' in self._capabilities and self.is_monitoring(target): yield from self.rawmsg('MONITOR', '-', target) self._monitoring.remove(target) return True else: return False
python
def unmonitor(self, target): """ Stop monitoring the online status of a user. Returns whether or not the server supports monitoring. """ if 'monitor-notify' in self._capabilities and self.is_monitoring(target): yield from self.rawmsg('MONITOR', '-', target) self._monitoring.remove(target) return True else: return False
[ "def", "unmonitor", "(", "self", ",", "target", ")", ":", "if", "'monitor-notify'", "in", "self", ".", "_capabilities", "and", "self", ".", "is_monitoring", "(", "target", ")", ":", "yield", "from", "self", ".", "rawmsg", "(", "'MONITOR'", ",", "'-'", ",...
Stop monitoring the online status of a user. Returns whether or not the server supports monitoring.
[ "Stop", "monitoring", "the", "online", "status", "of", "a", "user", ".", "Returns", "whether", "or", "not", "the", "server", "supports", "monitoring", "." ]
7ec7d65d097318ed0bcdc5d8401470287d8c7cf7
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/monitor.py#L48-L55
train
23,792
Shizmob/pydle
pydle/features/ircv3/monitor.py
MonitoringSupport.on_raw_730
async def on_raw_730(self, message): """ Someone we are monitoring just came online. """ for nick in message.params[1].split(','): self._create_user(nick) await self.on_user_online(nickname)
python
async def on_raw_730(self, message): """ Someone we are monitoring just came online. """ for nick in message.params[1].split(','): self._create_user(nick) await self.on_user_online(nickname)
[ "async", "def", "on_raw_730", "(", "self", ",", "message", ")", ":", "for", "nick", "in", "message", ".", "params", "[", "1", "]", ".", "split", "(", "','", ")", ":", "self", ".", "_create_user", "(", "nick", ")", "await", "self", ".", "on_user_onlin...
Someone we are monitoring just came online.
[ "Someone", "we", "are", "monitoring", "just", "came", "online", "." ]
7ec7d65d097318ed0bcdc5d8401470287d8c7cf7
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/monitor.py#L78-L82
train
23,793
Shizmob/pydle
pydle/features/ircv3/monitor.py
MonitoringSupport.on_raw_731
async def on_raw_731(self, message): """ Someone we are monitoring got offline. """ for nick in message.params[1].split(','): self._destroy_user(nick, monitor_override=True) await self.on_user_offline(nickname)
python
async def on_raw_731(self, message): """ Someone we are monitoring got offline. """ for nick in message.params[1].split(','): self._destroy_user(nick, monitor_override=True) await self.on_user_offline(nickname)
[ "async", "def", "on_raw_731", "(", "self", ",", "message", ")", ":", "for", "nick", "in", "message", ".", "params", "[", "1", "]", ".", "split", "(", "','", ")", ":", "self", ".", "_destroy_user", "(", "nick", ",", "monitor_override", "=", "True", ")...
Someone we are monitoring got offline.
[ "Someone", "we", "are", "monitoring", "got", "offline", "." ]
7ec7d65d097318ed0bcdc5d8401470287d8c7cf7
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/monitor.py#L84-L88
train
23,794
Shizmob/pydle
pydle/features/ircv3/ircv3_1.py
IRCv3_1Support.on_raw_account
async def on_raw_account(self, message): """ Changes in the associated account for a nickname. """ if not self._capabilities.get('account-notify', False): return nick, metadata = self._parse_user(message.source) account = message.params[0] if nick not in self.users: return self._sync_user(nick, metadata) if account == NO_ACCOUNT: self._sync_user(nick, { 'account': None, 'identified': False }) else: self._sync_user(nick, { 'account': account, 'identified': True })
python
async def on_raw_account(self, message): """ Changes in the associated account for a nickname. """ if not self._capabilities.get('account-notify', False): return nick, metadata = self._parse_user(message.source) account = message.params[0] if nick not in self.users: return self._sync_user(nick, metadata) if account == NO_ACCOUNT: self._sync_user(nick, { 'account': None, 'identified': False }) else: self._sync_user(nick, { 'account': account, 'identified': True })
[ "async", "def", "on_raw_account", "(", "self", ",", "message", ")", ":", "if", "not", "self", ".", "_capabilities", ".", "get", "(", "'account-notify'", ",", "False", ")", ":", "return", "nick", ",", "metadata", "=", "self", ".", "_parse_user", "(", "mes...
Changes in the associated account for a nickname.
[ "Changes", "in", "the", "associated", "account", "for", "a", "nickname", "." ]
7ec7d65d097318ed0bcdc5d8401470287d8c7cf7
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/ircv3_1.py#L52-L67
train
23,795
Shizmob/pydle
pydle/features/ircv3/ircv3_1.py
IRCv3_1Support.on_raw_away
async def on_raw_away(self, message): """ Process AWAY messages. """ if 'away-notify' not in self._capabilities or not self._capabilities['away-notify']: return nick, metadata = self._parse_user(message.source) if nick not in self.users: return self._sync_user(nick, metadata) self.users[nick]['away'] = len(message.params) > 0 self.users[nick]['away_message'] = message.params[0] if len(message.params) > 0 else None
python
async def on_raw_away(self, message): """ Process AWAY messages. """ if 'away-notify' not in self._capabilities or not self._capabilities['away-notify']: return nick, metadata = self._parse_user(message.source) if nick not in self.users: return self._sync_user(nick, metadata) self.users[nick]['away'] = len(message.params) > 0 self.users[nick]['away_message'] = message.params[0] if len(message.params) > 0 else None
[ "async", "def", "on_raw_away", "(", "self", ",", "message", ")", ":", "if", "'away-notify'", "not", "in", "self", ".", "_capabilities", "or", "not", "self", ".", "_capabilities", "[", "'away-notify'", "]", ":", "return", "nick", ",", "metadata", "=", "self...
Process AWAY messages.
[ "Process", "AWAY", "messages", "." ]
7ec7d65d097318ed0bcdc5d8401470287d8c7cf7
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/ircv3_1.py#L69-L80
train
23,796
Shizmob/pydle
pydle/features/ircv3/ircv3_1.py
IRCv3_1Support.on_raw_join
async def on_raw_join(self, message): """ Process extended JOIN messages. """ if 'extended-join' in self._capabilities and self._capabilities['extended-join']: nick, metadata = self._parse_user(message.source) channels, account, realname = message.params self._sync_user(nick, metadata) # Emit a fake join message. fakemsg = self._create_message('JOIN', channels, source=message.source) await super().on_raw_join(fakemsg) if account == NO_ACCOUNT: account = None self.users[nick]['account'] = account self.users[nick]['realname'] = realname else: await super().on_raw_join(message)
python
async def on_raw_join(self, message): """ Process extended JOIN messages. """ if 'extended-join' in self._capabilities and self._capabilities['extended-join']: nick, metadata = self._parse_user(message.source) channels, account, realname = message.params self._sync_user(nick, metadata) # Emit a fake join message. fakemsg = self._create_message('JOIN', channels, source=message.source) await super().on_raw_join(fakemsg) if account == NO_ACCOUNT: account = None self.users[nick]['account'] = account self.users[nick]['realname'] = realname else: await super().on_raw_join(message)
[ "async", "def", "on_raw_join", "(", "self", ",", "message", ")", ":", "if", "'extended-join'", "in", "self", ".", "_capabilities", "and", "self", ".", "_capabilities", "[", "'extended-join'", "]", ":", "nick", ",", "metadata", "=", "self", ".", "_parse_user"...
Process extended JOIN messages.
[ "Process", "extended", "JOIN", "messages", "." ]
7ec7d65d097318ed0bcdc5d8401470287d8c7cf7
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/ircv3_1.py#L82-L99
train
23,797
Shizmob/pydle
pydle/features/ircv3/metadata.py
MetadataSupport.on_raw_metadata
async def on_raw_metadata(self, message): """ Metadata event. """ target, targetmeta = self._parse_user(message.params[0]) key, visibility, value = message.params[1:4] if visibility == VISIBLITY_ALL: visibility = None if target in self.users: self._sync_user(target, targetmeta) await self.on_metadata(target, key, value, visibility=visibility)
python
async def on_raw_metadata(self, message): """ Metadata event. """ target, targetmeta = self._parse_user(message.params[0]) key, visibility, value = message.params[1:4] if visibility == VISIBLITY_ALL: visibility = None if target in self.users: self._sync_user(target, targetmeta) await self.on_metadata(target, key, value, visibility=visibility)
[ "async", "def", "on_raw_metadata", "(", "self", ",", "message", ")", ":", "target", ",", "targetmeta", "=", "self", ".", "_parse_user", "(", "message", ".", "params", "[", "0", "]", ")", "key", ",", "visibility", ",", "value", "=", "message", ".", "par...
Metadata event.
[ "Metadata", "event", "." ]
7ec7d65d097318ed0bcdc5d8401470287d8c7cf7
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/metadata.py#L56-L65
train
23,798
Shizmob/pydle
pydle/features/ircv3/metadata.py
MetadataSupport.on_raw_762
async def on_raw_762(self, message): """ End of metadata. """ # No way to figure out whose query this belongs to, so make a best guess # it was the first one. if not self._metadata_queue: return nickname = self._metadata_queue.pop() future = self._pending['metadata'].pop(nickname) future.set_result(self._metadata_info.pop(nickname))
python
async def on_raw_762(self, message): """ End of metadata. """ # No way to figure out whose query this belongs to, so make a best guess # it was the first one. if not self._metadata_queue: return nickname = self._metadata_queue.pop() future = self._pending['metadata'].pop(nickname) future.set_result(self._metadata_info.pop(nickname))
[ "async", "def", "on_raw_762", "(", "self", ",", "message", ")", ":", "# No way to figure out whose query this belongs to, so make a best guess", "# it was the first one.", "if", "not", "self", ".", "_metadata_queue", ":", "return", "nickname", "=", "self", ".", "_metadata...
End of metadata.
[ "End", "of", "metadata", "." ]
7ec7d65d097318ed0bcdc5d8401470287d8c7cf7
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/ircv3/metadata.py#L93-L102
train
23,799