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
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
uber/doubles
doubles/call_count_accumulator.py
CallCountAccumulator.error_string
def error_string(self): """Returns a well formed error message e.g at least 5 times but was called 4 times :rtype string """ if self.has_correct_call_count(): return '' return '{} instead of {} {} '.format( self._restriction_string(), self.count, pluralize('time', self.count) )
python
def error_string(self): """Returns a well formed error message e.g at least 5 times but was called 4 times :rtype string """ if self.has_correct_call_count(): return '' return '{} instead of {} {} '.format( self._restriction_string(), self.count, pluralize('time', self.count) )
[ "def", "error_string", "(", "self", ")", ":", "if", "self", ".", "has_correct_call_count", "(", ")", ":", "return", "''", "return", "'{} instead of {} {} '", ".", "format", "(", "self", ".", "_restriction_string", "(", ")", ",", "self", ".", "count", ",", "pluralize", "(", "'time'", ",", "self", ".", "count", ")", ")" ]
Returns a well formed error message e.g at least 5 times but was called 4 times :rtype string
[ "Returns", "a", "well", "formed", "error", "message" ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/call_count_accumulator.py#L146-L161
train
uber/doubles
doubles/space.py
Space.patch_for
def patch_for(self, path): """Returns the ``Patch`` for the target path, creating it if necessary. :param str path: The absolute module path to the target. :return: The mapped ``Patch``. :rtype: Patch """ if path not in self._patches: self._patches[path] = Patch(path) return self._patches[path]
python
def patch_for(self, path): """Returns the ``Patch`` for the target path, creating it if necessary. :param str path: The absolute module path to the target. :return: The mapped ``Patch``. :rtype: Patch """ if path not in self._patches: self._patches[path] = Patch(path) return self._patches[path]
[ "def", "patch_for", "(", "self", ",", "path", ")", ":", "if", "path", "not", "in", "self", ".", "_patches", ":", "self", ".", "_patches", "[", "path", "]", "=", "Patch", "(", "path", ")", "return", "self", ".", "_patches", "[", "path", "]" ]
Returns the ``Patch`` for the target path, creating it if necessary. :param str path: The absolute module path to the target. :return: The mapped ``Patch``. :rtype: Patch
[ "Returns", "the", "Patch", "for", "the", "target", "path", "creating", "it", "if", "necessary", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/space.py#L18-L29
train
uber/doubles
doubles/space.py
Space.proxy_for
def proxy_for(self, obj): """Returns the ``Proxy`` for the target object, creating it if necessary. :param object obj: The object that will be doubled. :return: The mapped ``Proxy``. :rtype: Proxy """ obj_id = id(obj) if obj_id not in self._proxies: self._proxies[obj_id] = Proxy(obj) return self._proxies[obj_id]
python
def proxy_for(self, obj): """Returns the ``Proxy`` for the target object, creating it if necessary. :param object obj: The object that will be doubled. :return: The mapped ``Proxy``. :rtype: Proxy """ obj_id = id(obj) if obj_id not in self._proxies: self._proxies[obj_id] = Proxy(obj) return self._proxies[obj_id]
[ "def", "proxy_for", "(", "self", ",", "obj", ")", ":", "obj_id", "=", "id", "(", "obj", ")", "if", "obj_id", "not", "in", "self", ".", "_proxies", ":", "self", ".", "_proxies", "[", "obj_id", "]", "=", "Proxy", "(", "obj", ")", "return", "self", ".", "_proxies", "[", "obj_id", "]" ]
Returns the ``Proxy`` for the target object, creating it if necessary. :param object obj: The object that will be doubled. :return: The mapped ``Proxy``. :rtype: Proxy
[ "Returns", "the", "Proxy", "for", "the", "target", "object", "creating", "it", "if", "necessary", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/space.py#L31-L44
train
uber/doubles
doubles/space.py
Space.teardown
def teardown(self): """Restores all doubled objects to their original state.""" for proxy in self._proxies.values(): proxy.restore_original_object() for patch in self._patches.values(): patch.restore_original_object()
python
def teardown(self): """Restores all doubled objects to their original state.""" for proxy in self._proxies.values(): proxy.restore_original_object() for patch in self._patches.values(): patch.restore_original_object()
[ "def", "teardown", "(", "self", ")", ":", "for", "proxy", "in", "self", ".", "_proxies", ".", "values", "(", ")", ":", "proxy", ".", "restore_original_object", "(", ")", "for", "patch", "in", "self", ".", "_patches", ".", "values", "(", ")", ":", "patch", ".", "restore_original_object", "(", ")" ]
Restores all doubled objects to their original state.
[ "Restores", "all", "doubled", "objects", "to", "their", "original", "state", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/space.py#L46-L53
train
uber/doubles
doubles/space.py
Space.verify
def verify(self): """Verifies expectations on all doubled objects. :raise: ``MockExpectationError`` on the first expectation that is not satisfied, if any. """ if self._is_verified: return for proxy in self._proxies.values(): proxy.verify() self._is_verified = True
python
def verify(self): """Verifies expectations on all doubled objects. :raise: ``MockExpectationError`` on the first expectation that is not satisfied, if any. """ if self._is_verified: return for proxy in self._proxies.values(): proxy.verify() self._is_verified = True
[ "def", "verify", "(", "self", ")", ":", "if", "self", ".", "_is_verified", ":", "return", "for", "proxy", "in", "self", ".", "_proxies", ".", "values", "(", ")", ":", "proxy", ".", "verify", "(", ")", "self", ".", "_is_verified", "=", "True" ]
Verifies expectations on all doubled objects. :raise: ``MockExpectationError`` on the first expectation that is not satisfied, if any.
[ "Verifies", "expectations", "on", "all", "doubled", "objects", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/space.py#L63-L75
train
uber/doubles
doubles/proxy_method.py
ProxyMethod.restore_original_method
def restore_original_method(self): """Replaces the proxy method on the target object with its original value.""" if self._target.is_class_or_module(): setattr(self._target.obj, self._method_name, self._original_method) if self._method_name == '__new__' and sys.version_info >= (3, 0): _restore__new__(self._target.obj, self._original_method) else: setattr(self._target.obj, self._method_name, self._original_method) elif self._attr.kind == 'property': setattr(self._target.obj.__class__, self._method_name, self._original_method) del self._target.obj.__dict__[double_name(self._method_name)] elif self._attr.kind == 'attribute': self._target.obj.__dict__[self._method_name] = self._original_method else: # TODO: Could there ever have been a value here that needs to be restored? del self._target.obj.__dict__[self._method_name] if self._method_name in ['__call__', '__enter__', '__exit__']: self._target.restore_attr(self._method_name)
python
def restore_original_method(self): """Replaces the proxy method on the target object with its original value.""" if self._target.is_class_or_module(): setattr(self._target.obj, self._method_name, self._original_method) if self._method_name == '__new__' and sys.version_info >= (3, 0): _restore__new__(self._target.obj, self._original_method) else: setattr(self._target.obj, self._method_name, self._original_method) elif self._attr.kind == 'property': setattr(self._target.obj.__class__, self._method_name, self._original_method) del self._target.obj.__dict__[double_name(self._method_name)] elif self._attr.kind == 'attribute': self._target.obj.__dict__[self._method_name] = self._original_method else: # TODO: Could there ever have been a value here that needs to be restored? del self._target.obj.__dict__[self._method_name] if self._method_name in ['__call__', '__enter__', '__exit__']: self._target.restore_attr(self._method_name)
[ "def", "restore_original_method", "(", "self", ")", ":", "if", "self", ".", "_target", ".", "is_class_or_module", "(", ")", ":", "setattr", "(", "self", ".", "_target", ".", "obj", ",", "self", ".", "_method_name", ",", "self", ".", "_original_method", ")", "if", "self", ".", "_method_name", "==", "'__new__'", "and", "sys", ".", "version_info", ">=", "(", "3", ",", "0", ")", ":", "_restore__new__", "(", "self", ".", "_target", ".", "obj", ",", "self", ".", "_original_method", ")", "else", ":", "setattr", "(", "self", ".", "_target", ".", "obj", ",", "self", ".", "_method_name", ",", "self", ".", "_original_method", ")", "elif", "self", ".", "_attr", ".", "kind", "==", "'property'", ":", "setattr", "(", "self", ".", "_target", ".", "obj", ".", "__class__", ",", "self", ".", "_method_name", ",", "self", ".", "_original_method", ")", "del", "self", ".", "_target", ".", "obj", ".", "__dict__", "[", "double_name", "(", "self", ".", "_method_name", ")", "]", "elif", "self", ".", "_attr", ".", "kind", "==", "'attribute'", ":", "self", ".", "_target", ".", "obj", ".", "__dict__", "[", "self", ".", "_method_name", "]", "=", "self", ".", "_original_method", "else", ":", "# TODO: Could there ever have been a value here that needs to be restored?", "del", "self", ".", "_target", ".", "obj", ".", "__dict__", "[", "self", ".", "_method_name", "]", "if", "self", ".", "_method_name", "in", "[", "'__call__'", ",", "'__enter__'", ",", "'__exit__'", "]", ":", "self", ".", "_target", ".", "restore_attr", "(", "self", ".", "_method_name", ")" ]
Replaces the proxy method on the target object with its original value.
[ "Replaces", "the", "proxy", "method", "on", "the", "target", "object", "with", "its", "original", "value", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/proxy_method.py#L105-L124
train
uber/doubles
doubles/proxy_method.py
ProxyMethod._hijack_target
def _hijack_target(self): """Replaces the target method on the target object with the proxy method.""" if self._target.is_class_or_module(): setattr(self._target.obj, self._method_name, self) elif self._attr.kind == 'property': proxy_property = ProxyProperty( double_name(self._method_name), self._original_method, ) setattr(self._target.obj.__class__, self._method_name, proxy_property) self._target.obj.__dict__[double_name(self._method_name)] = self else: self._target.obj.__dict__[self._method_name] = self if self._method_name in ['__call__', '__enter__', '__exit__']: self._target.hijack_attr(self._method_name)
python
def _hijack_target(self): """Replaces the target method on the target object with the proxy method.""" if self._target.is_class_or_module(): setattr(self._target.obj, self._method_name, self) elif self._attr.kind == 'property': proxy_property = ProxyProperty( double_name(self._method_name), self._original_method, ) setattr(self._target.obj.__class__, self._method_name, proxy_property) self._target.obj.__dict__[double_name(self._method_name)] = self else: self._target.obj.__dict__[self._method_name] = self if self._method_name in ['__call__', '__enter__', '__exit__']: self._target.hijack_attr(self._method_name)
[ "def", "_hijack_target", "(", "self", ")", ":", "if", "self", ".", "_target", ".", "is_class_or_module", "(", ")", ":", "setattr", "(", "self", ".", "_target", ".", "obj", ",", "self", ".", "_method_name", ",", "self", ")", "elif", "self", ".", "_attr", ".", "kind", "==", "'property'", ":", "proxy_property", "=", "ProxyProperty", "(", "double_name", "(", "self", ".", "_method_name", ")", ",", "self", ".", "_original_method", ",", ")", "setattr", "(", "self", ".", "_target", ".", "obj", ".", "__class__", ",", "self", ".", "_method_name", ",", "proxy_property", ")", "self", ".", "_target", ".", "obj", ".", "__dict__", "[", "double_name", "(", "self", ".", "_method_name", ")", "]", "=", "self", "else", ":", "self", ".", "_target", ".", "obj", ".", "__dict__", "[", "self", ".", "_method_name", "]", "=", "self", "if", "self", ".", "_method_name", "in", "[", "'__call__'", ",", "'__enter__'", ",", "'__exit__'", "]", ":", "self", ".", "_target", ".", "hijack_attr", "(", "self", ".", "_method_name", ")" ]
Replaces the target method on the target object with the proxy method.
[ "Replaces", "the", "target", "method", "on", "the", "target", "object", "with", "the", "proxy", "method", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/proxy_method.py#L131-L147
train
uber/doubles
doubles/proxy_method.py
ProxyMethod._raise_exception
def _raise_exception(self, args, kwargs): """ Raises an ``UnallowedMethodCallError`` with a useful message. :raise: ``UnallowedMethodCallError`` """ error_message = ( "Received unexpected call to '{}' on {!r}. The supplied arguments " "{} do not match any available allowances." ) raise UnallowedMethodCallError( error_message.format( self._method_name, self._target.obj, build_argument_repr_string(args, kwargs) ) )
python
def _raise_exception(self, args, kwargs): """ Raises an ``UnallowedMethodCallError`` with a useful message. :raise: ``UnallowedMethodCallError`` """ error_message = ( "Received unexpected call to '{}' on {!r}. The supplied arguments " "{} do not match any available allowances." ) raise UnallowedMethodCallError( error_message.format( self._method_name, self._target.obj, build_argument_repr_string(args, kwargs) ) )
[ "def", "_raise_exception", "(", "self", ",", "args", ",", "kwargs", ")", ":", "error_message", "=", "(", "\"Received unexpected call to '{}' on {!r}. The supplied arguments \"", "\"{} do not match any available allowances.\"", ")", "raise", "UnallowedMethodCallError", "(", "error_message", ".", "format", "(", "self", ".", "_method_name", ",", "self", ".", "_target", ".", "obj", ",", "build_argument_repr_string", "(", "args", ",", "kwargs", ")", ")", ")" ]
Raises an ``UnallowedMethodCallError`` with a useful message. :raise: ``UnallowedMethodCallError``
[ "Raises", "an", "UnallowedMethodCallError", "with", "a", "useful", "message", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/proxy_method.py#L149-L166
train
uber/doubles
doubles/proxy.py
Proxy.method_double_for
def method_double_for(self, method_name): """Returns the method double for the provided method name, creating one if necessary. :param str method_name: The name of the method to retrieve a method double for. :return: The mapped ``MethodDouble``. :rtype: MethodDouble """ if method_name not in self._method_doubles: self._method_doubles[method_name] = MethodDouble(method_name, self._target) return self._method_doubles[method_name]
python
def method_double_for(self, method_name): """Returns the method double for the provided method name, creating one if necessary. :param str method_name: The name of the method to retrieve a method double for. :return: The mapped ``MethodDouble``. :rtype: MethodDouble """ if method_name not in self._method_doubles: self._method_doubles[method_name] = MethodDouble(method_name, self._target) return self._method_doubles[method_name]
[ "def", "method_double_for", "(", "self", ",", "method_name", ")", ":", "if", "method_name", "not", "in", "self", ".", "_method_doubles", ":", "self", ".", "_method_doubles", "[", "method_name", "]", "=", "MethodDouble", "(", "method_name", ",", "self", ".", "_target", ")", "return", "self", ".", "_method_doubles", "[", "method_name", "]" ]
Returns the method double for the provided method name, creating one if necessary. :param str method_name: The name of the method to retrieve a method double for. :return: The mapped ``MethodDouble``. :rtype: MethodDouble
[ "Returns", "the", "method", "double", "for", "the", "provided", "method", "name", "creating", "one", "if", "necessary", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/proxy.py#L58-L69
train
uber/doubles
doubles/instance_double.py
_get_doubles_target
def _get_doubles_target(module, class_name, path): """Validate and return the class to be doubled. :param module module: The module that contains the class that will be doubled. :param str class_name: The name of the class that will be doubled. :param str path: The full path to the class that will be doubled. :return: The class that will be doubled. :rtype: type :raise: ``VerifyingDoubleImportError`` if the target object doesn't exist or isn't a class. """ try: doubles_target = getattr(module, class_name) if isinstance(doubles_target, ObjectDouble): return doubles_target._doubles_target if not isclass(doubles_target): raise VerifyingDoubleImportError( 'Path does not point to a class: {}.'.format(path) ) return doubles_target except AttributeError: raise VerifyingDoubleImportError( 'No object at path: {}.'.format(path) )
python
def _get_doubles_target(module, class_name, path): """Validate and return the class to be doubled. :param module module: The module that contains the class that will be doubled. :param str class_name: The name of the class that will be doubled. :param str path: The full path to the class that will be doubled. :return: The class that will be doubled. :rtype: type :raise: ``VerifyingDoubleImportError`` if the target object doesn't exist or isn't a class. """ try: doubles_target = getattr(module, class_name) if isinstance(doubles_target, ObjectDouble): return doubles_target._doubles_target if not isclass(doubles_target): raise VerifyingDoubleImportError( 'Path does not point to a class: {}.'.format(path) ) return doubles_target except AttributeError: raise VerifyingDoubleImportError( 'No object at path: {}.'.format(path) )
[ "def", "_get_doubles_target", "(", "module", ",", "class_name", ",", "path", ")", ":", "try", ":", "doubles_target", "=", "getattr", "(", "module", ",", "class_name", ")", "if", "isinstance", "(", "doubles_target", ",", "ObjectDouble", ")", ":", "return", "doubles_target", ".", "_doubles_target", "if", "not", "isclass", "(", "doubles_target", ")", ":", "raise", "VerifyingDoubleImportError", "(", "'Path does not point to a class: {}.'", ".", "format", "(", "path", ")", ")", "return", "doubles_target", "except", "AttributeError", ":", "raise", "VerifyingDoubleImportError", "(", "'No object at path: {}.'", ".", "format", "(", "path", ")", ")" ]
Validate and return the class to be doubled. :param module module: The module that contains the class that will be doubled. :param str class_name: The name of the class that will be doubled. :param str path: The full path to the class that will be doubled. :return: The class that will be doubled. :rtype: type :raise: ``VerifyingDoubleImportError`` if the target object doesn't exist or isn't a class.
[ "Validate", "and", "return", "the", "class", "to", "be", "doubled", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/instance_double.py#L8-L33
train
uber/doubles
doubles/allowance.py
Allowance.and_raise
def and_raise(self, exception, *args, **kwargs): """Causes the double to raise the provided exception when called. If provided, additional arguments (positional and keyword) passed to `and_raise` are used in the exception instantiation. :param Exception exception: The exception to raise. """ def proxy_exception(*proxy_args, **proxy_kwargs): raise exception self._return_value = proxy_exception return self
python
def and_raise(self, exception, *args, **kwargs): """Causes the double to raise the provided exception when called. If provided, additional arguments (positional and keyword) passed to `and_raise` are used in the exception instantiation. :param Exception exception: The exception to raise. """ def proxy_exception(*proxy_args, **proxy_kwargs): raise exception self._return_value = proxy_exception return self
[ "def", "and_raise", "(", "self", ",", "exception", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "proxy_exception", "(", "*", "proxy_args", ",", "*", "*", "proxy_kwargs", ")", ":", "raise", "exception", "self", ".", "_return_value", "=", "proxy_exception", "return", "self" ]
Causes the double to raise the provided exception when called. If provided, additional arguments (positional and keyword) passed to `and_raise` are used in the exception instantiation. :param Exception exception: The exception to raise.
[ "Causes", "the", "double", "to", "raise", "the", "provided", "exception", "when", "called", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/allowance.py#L71-L83
train
uber/doubles
doubles/allowance.py
Allowance.and_raise_future
def and_raise_future(self, exception): """Similar to `and_raise` but the doubled method returns a future. :param Exception exception: The exception to raise. """ future = _get_future() future.set_exception(exception) return self.and_return(future)
python
def and_raise_future(self, exception): """Similar to `and_raise` but the doubled method returns a future. :param Exception exception: The exception to raise. """ future = _get_future() future.set_exception(exception) return self.and_return(future)
[ "def", "and_raise_future", "(", "self", ",", "exception", ")", ":", "future", "=", "_get_future", "(", ")", "future", ".", "set_exception", "(", "exception", ")", "return", "self", ".", "and_return", "(", "future", ")" ]
Similar to `and_raise` but the doubled method returns a future. :param Exception exception: The exception to raise.
[ "Similar", "to", "and_raise", "but", "the", "doubled", "method", "returns", "a", "future", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/allowance.py#L85-L92
train
uber/doubles
doubles/allowance.py
Allowance.and_return_future
def and_return_future(self, *return_values): """Similar to `and_return` but the doubled method returns a future. :param object return_values: The values the double will return when called, """ futures = [] for value in return_values: future = _get_future() future.set_result(value) futures.append(future) return self.and_return(*futures)
python
def and_return_future(self, *return_values): """Similar to `and_return` but the doubled method returns a future. :param object return_values: The values the double will return when called, """ futures = [] for value in return_values: future = _get_future() future.set_result(value) futures.append(future) return self.and_return(*futures)
[ "def", "and_return_future", "(", "self", ",", "*", "return_values", ")", ":", "futures", "=", "[", "]", "for", "value", "in", "return_values", ":", "future", "=", "_get_future", "(", ")", "future", ".", "set_result", "(", "value", ")", "futures", ".", "append", "(", "future", ")", "return", "self", ".", "and_return", "(", "*", "futures", ")" ]
Similar to `and_return` but the doubled method returns a future. :param object return_values: The values the double will return when called,
[ "Similar", "to", "and_return", "but", "the", "doubled", "method", "returns", "a", "future", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/allowance.py#L94-L104
train
uber/doubles
doubles/allowance.py
Allowance.and_return
def and_return(self, *return_values): """Set a return value for an allowance Causes the double to return the provided values in order. If multiple values are provided, they are returned one at a time in sequence as the double is called. If the double is called more times than there are return values, it should continue to return the last value in the list. :param object return_values: The values the double will return when called, """ if not return_values: raise TypeError('and_return() expected at least 1 return value') return_values = list(return_values) final_value = return_values.pop() self.and_return_result_of( lambda: return_values.pop(0) if return_values else final_value ) return self
python
def and_return(self, *return_values): """Set a return value for an allowance Causes the double to return the provided values in order. If multiple values are provided, they are returned one at a time in sequence as the double is called. If the double is called more times than there are return values, it should continue to return the last value in the list. :param object return_values: The values the double will return when called, """ if not return_values: raise TypeError('and_return() expected at least 1 return value') return_values = list(return_values) final_value = return_values.pop() self.and_return_result_of( lambda: return_values.pop(0) if return_values else final_value ) return self
[ "def", "and_return", "(", "self", ",", "*", "return_values", ")", ":", "if", "not", "return_values", ":", "raise", "TypeError", "(", "'and_return() expected at least 1 return value'", ")", "return_values", "=", "list", "(", "return_values", ")", "final_value", "=", "return_values", ".", "pop", "(", ")", "self", ".", "and_return_result_of", "(", "lambda", ":", "return_values", ".", "pop", "(", "0", ")", "if", "return_values", "else", "final_value", ")", "return", "self" ]
Set a return value for an allowance Causes the double to return the provided values in order. If multiple values are provided, they are returned one at a time in sequence as the double is called. If the double is called more times than there are return values, it should continue to return the last value in the list. :param object return_values: The values the double will return when called,
[ "Set", "a", "return", "value", "for", "an", "allowance" ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/allowance.py#L106-L127
train
uber/doubles
doubles/allowance.py
Allowance.and_return_result_of
def and_return_result_of(self, return_value): """ Causes the double to return the result of calling the provided value. :param return_value: A callable that will be invoked to determine the double's return value. :type return_value: any callable object """ if not check_func_takes_args(return_value): self._return_value = lambda *args, **kwargs: return_value() else: self._return_value = return_value return self
python
def and_return_result_of(self, return_value): """ Causes the double to return the result of calling the provided value. :param return_value: A callable that will be invoked to determine the double's return value. :type return_value: any callable object """ if not check_func_takes_args(return_value): self._return_value = lambda *args, **kwargs: return_value() else: self._return_value = return_value return self
[ "def", "and_return_result_of", "(", "self", ",", "return_value", ")", ":", "if", "not", "check_func_takes_args", "(", "return_value", ")", ":", "self", ".", "_return_value", "=", "lambda", "*", "args", ",", "*", "*", "kwargs", ":", "return_value", "(", ")", "else", ":", "self", ".", "_return_value", "=", "return_value", "return", "self" ]
Causes the double to return the result of calling the provided value. :param return_value: A callable that will be invoked to determine the double's return value. :type return_value: any callable object
[ "Causes", "the", "double", "to", "return", "the", "result", "of", "calling", "the", "provided", "value", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/allowance.py#L129-L140
train
uber/doubles
doubles/allowance.py
Allowance.with_args
def with_args(self, *args, **kwargs): """Declares that the double can only be called with the provided arguments. :param args: Any positional arguments required for invocation. :param kwargs: Any keyword arguments required for invocation. """ self.args = args self.kwargs = kwargs self.verify_arguments() return self
python
def with_args(self, *args, **kwargs): """Declares that the double can only be called with the provided arguments. :param args: Any positional arguments required for invocation. :param kwargs: Any keyword arguments required for invocation. """ self.args = args self.kwargs = kwargs self.verify_arguments() return self
[ "def", "with_args", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "args", "=", "args", "self", ".", "kwargs", "=", "kwargs", "self", ".", "verify_arguments", "(", ")", "return", "self" ]
Declares that the double can only be called with the provided arguments. :param args: Any positional arguments required for invocation. :param kwargs: Any keyword arguments required for invocation.
[ "Declares", "that", "the", "double", "can", "only", "be", "called", "with", "the", "provided", "arguments", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/allowance.py#L153-L163
train
uber/doubles
doubles/allowance.py
Allowance.with_args_validator
def with_args_validator(self, matching_function): """Define a custom function for testing arguments :param func matching_function: The function used to test arguments passed to the stub. """ self.args = None self.kwargs = None self._custom_matcher = matching_function return self
python
def with_args_validator(self, matching_function): """Define a custom function for testing arguments :param func matching_function: The function used to test arguments passed to the stub. """ self.args = None self.kwargs = None self._custom_matcher = matching_function return self
[ "def", "with_args_validator", "(", "self", ",", "matching_function", ")", ":", "self", ".", "args", "=", "None", "self", ".", "kwargs", "=", "None", "self", ".", "_custom_matcher", "=", "matching_function", "return", "self" ]
Define a custom function for testing arguments :param func matching_function: The function used to test arguments passed to the stub.
[ "Define", "a", "custom", "function", "for", "testing", "arguments" ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/allowance.py#L165-L173
train
uber/doubles
doubles/allowance.py
Allowance.satisfy_exact_match
def satisfy_exact_match(self, args, kwargs): """Returns a boolean indicating whether or not the stub will accept the provided arguments. :return: Whether or not the stub accepts the provided arguments. :rtype: bool """ if self.args is None and self.kwargs is None: return False elif self.args is _any and self.kwargs is _any: return True elif args == self.args and kwargs == self.kwargs: return True elif len(args) != len(self.args) or len(kwargs) != len(self.kwargs): return False if not all(x == y or y == x for x, y in zip(args, self.args)): return False for key, value in self.kwargs.items(): if key not in kwargs: return False elif not (kwargs[key] == value or value == kwargs[key]): return False return True
python
def satisfy_exact_match(self, args, kwargs): """Returns a boolean indicating whether or not the stub will accept the provided arguments. :return: Whether or not the stub accepts the provided arguments. :rtype: bool """ if self.args is None and self.kwargs is None: return False elif self.args is _any and self.kwargs is _any: return True elif args == self.args and kwargs == self.kwargs: return True elif len(args) != len(self.args) or len(kwargs) != len(self.kwargs): return False if not all(x == y or y == x for x, y in zip(args, self.args)): return False for key, value in self.kwargs.items(): if key not in kwargs: return False elif not (kwargs[key] == value or value == kwargs[key]): return False return True
[ "def", "satisfy_exact_match", "(", "self", ",", "args", ",", "kwargs", ")", ":", "if", "self", ".", "args", "is", "None", "and", "self", ".", "kwargs", "is", "None", ":", "return", "False", "elif", "self", ".", "args", "is", "_any", "and", "self", ".", "kwargs", "is", "_any", ":", "return", "True", "elif", "args", "==", "self", ".", "args", "and", "kwargs", "==", "self", ".", "kwargs", ":", "return", "True", "elif", "len", "(", "args", ")", "!=", "len", "(", "self", ".", "args", ")", "or", "len", "(", "kwargs", ")", "!=", "len", "(", "self", ".", "kwargs", ")", ":", "return", "False", "if", "not", "all", "(", "x", "==", "y", "or", "y", "==", "x", "for", "x", ",", "y", "in", "zip", "(", "args", ",", "self", ".", "args", ")", ")", ":", "return", "False", "for", "key", ",", "value", "in", "self", ".", "kwargs", ".", "items", "(", ")", ":", "if", "key", "not", "in", "kwargs", ":", "return", "False", "elif", "not", "(", "kwargs", "[", "key", "]", "==", "value", "or", "value", "==", "kwargs", "[", "key", "]", ")", ":", "return", "False", "return", "True" ]
Returns a boolean indicating whether or not the stub will accept the provided arguments. :return: Whether or not the stub accepts the provided arguments. :rtype: bool
[ "Returns", "a", "boolean", "indicating", "whether", "or", "not", "the", "stub", "will", "accept", "the", "provided", "arguments", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/allowance.py#L208-L233
train
uber/doubles
doubles/allowance.py
Allowance.satisfy_custom_matcher
def satisfy_custom_matcher(self, args, kwargs): """Return a boolean indicating if the args satisfy the stub :return: Whether or not the stub accepts the provided arguments. :rtype: bool """ if not self._custom_matcher: return False try: return self._custom_matcher(*args, **kwargs) except Exception: return False
python
def satisfy_custom_matcher(self, args, kwargs): """Return a boolean indicating if the args satisfy the stub :return: Whether or not the stub accepts the provided arguments. :rtype: bool """ if not self._custom_matcher: return False try: return self._custom_matcher(*args, **kwargs) except Exception: return False
[ "def", "satisfy_custom_matcher", "(", "self", ",", "args", ",", "kwargs", ")", ":", "if", "not", "self", ".", "_custom_matcher", ":", "return", "False", "try", ":", "return", "self", ".", "_custom_matcher", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", ":", "return", "False" ]
Return a boolean indicating if the args satisfy the stub :return: Whether or not the stub accepts the provided arguments. :rtype: bool
[ "Return", "a", "boolean", "indicating", "if", "the", "args", "satisfy", "the", "stub" ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/allowance.py#L235-L246
train
uber/doubles
doubles/allowance.py
Allowance.return_value
def return_value(self, *args, **kwargs): """Extracts the real value to be returned from the wrapping callable. :return: The value the double should return when called. """ self._called() return self._return_value(*args, **kwargs)
python
def return_value(self, *args, **kwargs): """Extracts the real value to be returned from the wrapping callable. :return: The value the double should return when called. """ self._called() return self._return_value(*args, **kwargs)
[ "def", "return_value", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_called", "(", ")", "return", "self", ".", "_return_value", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Extracts the real value to be returned from the wrapping callable. :return: The value the double should return when called.
[ "Extracts", "the", "real", "value", "to", "be", "returned", "from", "the", "wrapping", "callable", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/allowance.py#L248-L255
train
uber/doubles
doubles/allowance.py
Allowance.verify_arguments
def verify_arguments(self, args=None, kwargs=None): """Ensures that the arguments specified match the signature of the real method. :raise: ``VerifyingDoubleError`` if the arguments do not match. """ args = self.args if args is None else args kwargs = self.kwargs if kwargs is None else kwargs try: verify_arguments(self._target, self._method_name, args, kwargs) except VerifyingBuiltinDoubleArgumentError: if doubles.lifecycle.ignore_builtin_verification(): raise
python
def verify_arguments(self, args=None, kwargs=None): """Ensures that the arguments specified match the signature of the real method. :raise: ``VerifyingDoubleError`` if the arguments do not match. """ args = self.args if args is None else args kwargs = self.kwargs if kwargs is None else kwargs try: verify_arguments(self._target, self._method_name, args, kwargs) except VerifyingBuiltinDoubleArgumentError: if doubles.lifecycle.ignore_builtin_verification(): raise
[ "def", "verify_arguments", "(", "self", ",", "args", "=", "None", ",", "kwargs", "=", "None", ")", ":", "args", "=", "self", ".", "args", "if", "args", "is", "None", "else", "args", "kwargs", "=", "self", ".", "kwargs", "if", "kwargs", "is", "None", "else", "kwargs", "try", ":", "verify_arguments", "(", "self", ".", "_target", ",", "self", ".", "_method_name", ",", "args", ",", "kwargs", ")", "except", "VerifyingBuiltinDoubleArgumentError", ":", "if", "doubles", ".", "lifecycle", ".", "ignore_builtin_verification", "(", ")", ":", "raise" ]
Ensures that the arguments specified match the signature of the real method. :raise: ``VerifyingDoubleError`` if the arguments do not match.
[ "Ensures", "that", "the", "arguments", "specified", "match", "the", "signature", "of", "the", "real", "method", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/allowance.py#L257-L270
train
uber/doubles
doubles/allowance.py
Allowance.raise_failure_exception
def raise_failure_exception(self, expect_or_allow='Allowed'): """Raises a ``MockExpectationError`` with a useful message. :raise: ``MockExpectationError`` """ raise MockExpectationError( "{} '{}' to be called {}on {!r} with {}, but was not. ({}:{})".format( expect_or_allow, self._method_name, self._call_counter.error_string(), self._target.obj, self._expected_argument_string(), self._caller.filename, self._caller.lineno, ) )
python
def raise_failure_exception(self, expect_or_allow='Allowed'): """Raises a ``MockExpectationError`` with a useful message. :raise: ``MockExpectationError`` """ raise MockExpectationError( "{} '{}' to be called {}on {!r} with {}, but was not. ({}:{})".format( expect_or_allow, self._method_name, self._call_counter.error_string(), self._target.obj, self._expected_argument_string(), self._caller.filename, self._caller.lineno, ) )
[ "def", "raise_failure_exception", "(", "self", ",", "expect_or_allow", "=", "'Allowed'", ")", ":", "raise", "MockExpectationError", "(", "\"{} '{}' to be called {}on {!r} with {}, but was not. ({}:{})\"", ".", "format", "(", "expect_or_allow", ",", "self", ".", "_method_name", ",", "self", ".", "_call_counter", ".", "error_string", "(", ")", ",", "self", ".", "_target", ".", "obj", ",", "self", ".", "_expected_argument_string", "(", ")", ",", "self", ".", "_caller", ".", "filename", ",", "self", ".", "_caller", ".", "lineno", ",", ")", ")" ]
Raises a ``MockExpectationError`` with a useful message. :raise: ``MockExpectationError``
[ "Raises", "a", "MockExpectationError", "with", "a", "useful", "message", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/allowance.py#L334-L350
train
uber/doubles
doubles/allowance.py
Allowance._expected_argument_string
def _expected_argument_string(self): """Generates a string describing what arguments the double expected. :return: A string describing expected arguments. :rtype: str """ if self.args is _any and self.kwargs is _any: return 'any args' elif self._custom_matcher: return "custom matcher: '{}'".format(self._custom_matcher.__name__) else: return build_argument_repr_string(self.args, self.kwargs)
python
def _expected_argument_string(self): """Generates a string describing what arguments the double expected. :return: A string describing expected arguments. :rtype: str """ if self.args is _any and self.kwargs is _any: return 'any args' elif self._custom_matcher: return "custom matcher: '{}'".format(self._custom_matcher.__name__) else: return build_argument_repr_string(self.args, self.kwargs)
[ "def", "_expected_argument_string", "(", "self", ")", ":", "if", "self", ".", "args", "is", "_any", "and", "self", ".", "kwargs", "is", "_any", ":", "return", "'any args'", "elif", "self", ".", "_custom_matcher", ":", "return", "\"custom matcher: '{}'\"", ".", "format", "(", "self", ".", "_custom_matcher", ".", "__name__", ")", "else", ":", "return", "build_argument_repr_string", "(", "self", ".", "args", ",", "self", ".", "kwargs", ")" ]
Generates a string describing what arguments the double expected. :return: A string describing expected arguments. :rtype: str
[ "Generates", "a", "string", "describing", "what", "arguments", "the", "double", "expected", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/allowance.py#L352-L364
train
uber/doubles
doubles/target.py
Target.is_class_or_module
def is_class_or_module(self): """Determines if the object is a class or a module :return: True if the object is a class or a module, False otherwise. :rtype: bool """ if isinstance(self.obj, ObjectDouble): return self.obj.is_class return isclass(self.doubled_obj) or ismodule(self.doubled_obj)
python
def is_class_or_module(self): """Determines if the object is a class or a module :return: True if the object is a class or a module, False otherwise. :rtype: bool """ if isinstance(self.obj, ObjectDouble): return self.obj.is_class return isclass(self.doubled_obj) or ismodule(self.doubled_obj)
[ "def", "is_class_or_module", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "obj", ",", "ObjectDouble", ")", ":", "return", "self", ".", "obj", ".", "is_class", "return", "isclass", "(", "self", ".", "doubled_obj", ")", "or", "ismodule", "(", "self", ".", "doubled_obj", ")" ]
Determines if the object is a class or a module :return: True if the object is a class or a module, False otherwise. :rtype: bool
[ "Determines", "if", "the", "object", "is", "a", "class", "or", "a", "module" ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/target.py#L36-L46
train
uber/doubles
doubles/target.py
Target._determine_doubled_obj
def _determine_doubled_obj(self): """Return the target object. Returns the object that should be treated as the target object. For partial doubles, this will be the same as ``self.obj``, but for pure doubles, it's pulled from the special ``_doubles_target`` attribute. :return: The object to be doubled. :rtype: object """ if isinstance(self.obj, ObjectDouble): return self.obj._doubles_target else: return self.obj
python
def _determine_doubled_obj(self): """Return the target object. Returns the object that should be treated as the target object. For partial doubles, this will be the same as ``self.obj``, but for pure doubles, it's pulled from the special ``_doubles_target`` attribute. :return: The object to be doubled. :rtype: object """ if isinstance(self.obj, ObjectDouble): return self.obj._doubles_target else: return self.obj
[ "def", "_determine_doubled_obj", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "obj", ",", "ObjectDouble", ")", ":", "return", "self", ".", "obj", ".", "_doubles_target", "else", ":", "return", "self", ".", "obj" ]
Return the target object. Returns the object that should be treated as the target object. For partial doubles, this will be the same as ``self.obj``, but for pure doubles, it's pulled from the special ``_doubles_target`` attribute. :return: The object to be doubled. :rtype: object
[ "Return", "the", "target", "object", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/target.py#L48-L62
train
uber/doubles
doubles/target.py
Target._generate_attrs
def _generate_attrs(self): """Get detailed info about target object. Uses ``inspect.classify_class_attrs`` to get several important details about each attribute on the target object. :return: The attribute details dict. :rtype: dict """ attrs = {} if ismodule(self.doubled_obj): for name, func in getmembers(self.doubled_obj, is_callable): attrs[name] = Attribute(func, 'toplevel', self.doubled_obj) else: for attr in classify_class_attrs(self.doubled_obj_type): attrs[attr.name] = attr return attrs
python
def _generate_attrs(self): """Get detailed info about target object. Uses ``inspect.classify_class_attrs`` to get several important details about each attribute on the target object. :return: The attribute details dict. :rtype: dict """ attrs = {} if ismodule(self.doubled_obj): for name, func in getmembers(self.doubled_obj, is_callable): attrs[name] = Attribute(func, 'toplevel', self.doubled_obj) else: for attr in classify_class_attrs(self.doubled_obj_type): attrs[attr.name] = attr return attrs
[ "def", "_generate_attrs", "(", "self", ")", ":", "attrs", "=", "{", "}", "if", "ismodule", "(", "self", ".", "doubled_obj", ")", ":", "for", "name", ",", "func", "in", "getmembers", "(", "self", ".", "doubled_obj", ",", "is_callable", ")", ":", "attrs", "[", "name", "]", "=", "Attribute", "(", "func", ",", "'toplevel'", ",", "self", ".", "doubled_obj", ")", "else", ":", "for", "attr", "in", "classify_class_attrs", "(", "self", ".", "doubled_obj_type", ")", ":", "attrs", "[", "attr", ".", "name", "]", "=", "attr", "return", "attrs" ]
Get detailed info about target object. Uses ``inspect.classify_class_attrs`` to get several important details about each attribute on the target object. :return: The attribute details dict. :rtype: dict
[ "Get", "detailed", "info", "about", "target", "object", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/target.py#L76-L94
train
uber/doubles
doubles/target.py
Target.hijack_attr
def hijack_attr(self, attr_name): """Hijack an attribute on the target object. Updates the underlying class and delegating the call to the instance. This allows specially-handled attributes like __call__, __enter__, and __exit__ to be mocked on a per-instance basis. :param str attr_name: the name of the attribute to hijack """ if not self._original_attr(attr_name): setattr( self.obj.__class__, attr_name, _proxy_class_method_to_instance( getattr(self.obj.__class__, attr_name, None), attr_name ), )
python
def hijack_attr(self, attr_name): """Hijack an attribute on the target object. Updates the underlying class and delegating the call to the instance. This allows specially-handled attributes like __call__, __enter__, and __exit__ to be mocked on a per-instance basis. :param str attr_name: the name of the attribute to hijack """ if not self._original_attr(attr_name): setattr( self.obj.__class__, attr_name, _proxy_class_method_to_instance( getattr(self.obj.__class__, attr_name, None), attr_name ), )
[ "def", "hijack_attr", "(", "self", ",", "attr_name", ")", ":", "if", "not", "self", ".", "_original_attr", "(", "attr_name", ")", ":", "setattr", "(", "self", ".", "obj", ".", "__class__", ",", "attr_name", ",", "_proxy_class_method_to_instance", "(", "getattr", "(", "self", ".", "obj", ".", "__class__", ",", "attr_name", ",", "None", ")", ",", "attr_name", ")", ",", ")" ]
Hijack an attribute on the target object. Updates the underlying class and delegating the call to the instance. This allows specially-handled attributes like __call__, __enter__, and __exit__ to be mocked on a per-instance basis. :param str attr_name: the name of the attribute to hijack
[ "Hijack", "an", "attribute", "on", "the", "target", "object", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/target.py#L96-L112
train
uber/doubles
doubles/target.py
Target.restore_attr
def restore_attr(self, attr_name): """Restore an attribute back onto the target object. :param str attr_name: the name of the attribute to restore """ original_attr = self._original_attr(attr_name) if self._original_attr(attr_name): setattr(self.obj.__class__, attr_name, original_attr)
python
def restore_attr(self, attr_name): """Restore an attribute back onto the target object. :param str attr_name: the name of the attribute to restore """ original_attr = self._original_attr(attr_name) if self._original_attr(attr_name): setattr(self.obj.__class__, attr_name, original_attr)
[ "def", "restore_attr", "(", "self", ",", "attr_name", ")", ":", "original_attr", "=", "self", ".", "_original_attr", "(", "attr_name", ")", "if", "self", ".", "_original_attr", "(", "attr_name", ")", ":", "setattr", "(", "self", ".", "obj", ".", "__class__", ",", "attr_name", ",", "original_attr", ")" ]
Restore an attribute back onto the target object. :param str attr_name: the name of the attribute to restore
[ "Restore", "an", "attribute", "back", "onto", "the", "target", "object", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/target.py#L114-L121
train
uber/doubles
doubles/target.py
Target._original_attr
def _original_attr(self, attr_name): """Return the original attribute off of the proxy on the target object. :param str attr_name: the name of the original attribute to return :return: Func or None. :rtype: func """ try: return getattr( getattr(self.obj.__class__, attr_name), '_doubles_target_method', None ) except AttributeError: return None
python
def _original_attr(self, attr_name): """Return the original attribute off of the proxy on the target object. :param str attr_name: the name of the original attribute to return :return: Func or None. :rtype: func """ try: return getattr( getattr(self.obj.__class__, attr_name), '_doubles_target_method', None ) except AttributeError: return None
[ "def", "_original_attr", "(", "self", ",", "attr_name", ")", ":", "try", ":", "return", "getattr", "(", "getattr", "(", "self", ".", "obj", ".", "__class__", ",", "attr_name", ")", ",", "'_doubles_target_method'", ",", "None", ")", "except", "AttributeError", ":", "return", "None" ]
Return the original attribute off of the proxy on the target object. :param str attr_name: the name of the original attribute to return :return: Func or None. :rtype: func
[ "Return", "the", "original", "attribute", "off", "of", "the", "proxy", "on", "the", "target", "object", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/target.py#L123-L135
train
uber/doubles
doubles/target.py
Target.get_callable_attr
def get_callable_attr(self, attr_name): """Used to double methods added to an object after creation :param str attr_name: the name of the original attribute to return :return: Attribute or None. :rtype: func """ if not hasattr(self.doubled_obj, attr_name): return None func = getattr(self.doubled_obj, attr_name) if not is_callable(func): return None attr = Attribute( func, 'attribute', self.doubled_obj if self.is_class_or_module() else self.doubled_obj_type, ) self.attrs[attr_name] = attr return attr
python
def get_callable_attr(self, attr_name): """Used to double methods added to an object after creation :param str attr_name: the name of the original attribute to return :return: Attribute or None. :rtype: func """ if not hasattr(self.doubled_obj, attr_name): return None func = getattr(self.doubled_obj, attr_name) if not is_callable(func): return None attr = Attribute( func, 'attribute', self.doubled_obj if self.is_class_or_module() else self.doubled_obj_type, ) self.attrs[attr_name] = attr return attr
[ "def", "get_callable_attr", "(", "self", ",", "attr_name", ")", ":", "if", "not", "hasattr", "(", "self", ".", "doubled_obj", ",", "attr_name", ")", ":", "return", "None", "func", "=", "getattr", "(", "self", ".", "doubled_obj", ",", "attr_name", ")", "if", "not", "is_callable", "(", "func", ")", ":", "return", "None", "attr", "=", "Attribute", "(", "func", ",", "'attribute'", ",", "self", ".", "doubled_obj", "if", "self", ".", "is_class_or_module", "(", ")", "else", "self", ".", "doubled_obj_type", ",", ")", "self", ".", "attrs", "[", "attr_name", "]", "=", "attr", "return", "attr" ]
Used to double methods added to an object after creation :param str attr_name: the name of the original attribute to return :return: Attribute or None. :rtype: func
[ "Used", "to", "double", "methods", "added", "to", "an", "object", "after", "creation" ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/target.py#L137-L158
train
uber/doubles
doubles/target.py
Target.get_attr
def get_attr(self, method_name): """Get attribute from the target object""" return self.attrs.get(method_name) or self.get_callable_attr(method_name)
python
def get_attr(self, method_name): """Get attribute from the target object""" return self.attrs.get(method_name) or self.get_callable_attr(method_name)
[ "def", "get_attr", "(", "self", ",", "method_name", ")", ":", "return", "self", ".", "attrs", ".", "get", "(", "method_name", ")", "or", "self", ".", "get_callable_attr", "(", "method_name", ")" ]
Get attribute from the target object
[ "Get", "attribute", "from", "the", "target", "object" ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/target.py#L160-L162
train
uber/doubles
doubles/method_double.py
MethodDouble.add_allowance
def add_allowance(self, caller): """Adds a new allowance for the method. :param: tuple caller: A tuple indicating where the method was called :return: The new ``Allowance``. :rtype: Allowance """ allowance = Allowance(self._target, self._method_name, caller) self._allowances.insert(0, allowance) return allowance
python
def add_allowance(self, caller): """Adds a new allowance for the method. :param: tuple caller: A tuple indicating where the method was called :return: The new ``Allowance``. :rtype: Allowance """ allowance = Allowance(self._target, self._method_name, caller) self._allowances.insert(0, allowance) return allowance
[ "def", "add_allowance", "(", "self", ",", "caller", ")", ":", "allowance", "=", "Allowance", "(", "self", ".", "_target", ",", "self", ".", "_method_name", ",", "caller", ")", "self", ".", "_allowances", ".", "insert", "(", "0", ",", "allowance", ")", "return", "allowance" ]
Adds a new allowance for the method. :param: tuple caller: A tuple indicating where the method was called :return: The new ``Allowance``. :rtype: Allowance
[ "Adds", "a", "new", "allowance", "for", "the", "method", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/method_double.py#L30-L40
train
uber/doubles
doubles/method_double.py
MethodDouble.add_expectation
def add_expectation(self, caller): """Adds a new expectation for the method. :return: The new ``Expectation``. :rtype: Expectation """ expectation = Expectation(self._target, self._method_name, caller) self._expectations.insert(0, expectation) return expectation
python
def add_expectation(self, caller): """Adds a new expectation for the method. :return: The new ``Expectation``. :rtype: Expectation """ expectation = Expectation(self._target, self._method_name, caller) self._expectations.insert(0, expectation) return expectation
[ "def", "add_expectation", "(", "self", ",", "caller", ")", ":", "expectation", "=", "Expectation", "(", "self", ".", "_target", ",", "self", ".", "_method_name", ",", "caller", ")", "self", ".", "_expectations", ".", "insert", "(", "0", ",", "expectation", ")", "return", "expectation" ]
Adds a new expectation for the method. :return: The new ``Expectation``. :rtype: Expectation
[ "Adds", "a", "new", "expectation", "for", "the", "method", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/method_double.py#L42-L51
train
uber/doubles
doubles/method_double.py
MethodDouble._find_matching_allowance
def _find_matching_allowance(self, args, kwargs): """Return a matching allowance. Returns the first allowance that matches the ones declared. Tries one with specific arguments first, then falls back to an allowance that allows arbitrary arguments. :return: The matching ``Allowance``, if one was found. :rtype: Allowance, None """ for allowance in self._allowances: if allowance.satisfy_exact_match(args, kwargs): return allowance for allowance in self._allowances: if allowance.satisfy_custom_matcher(args, kwargs): return allowance for allowance in self._allowances: if allowance.satisfy_any_args_match(): return allowance
python
def _find_matching_allowance(self, args, kwargs): """Return a matching allowance. Returns the first allowance that matches the ones declared. Tries one with specific arguments first, then falls back to an allowance that allows arbitrary arguments. :return: The matching ``Allowance``, if one was found. :rtype: Allowance, None """ for allowance in self._allowances: if allowance.satisfy_exact_match(args, kwargs): return allowance for allowance in self._allowances: if allowance.satisfy_custom_matcher(args, kwargs): return allowance for allowance in self._allowances: if allowance.satisfy_any_args_match(): return allowance
[ "def", "_find_matching_allowance", "(", "self", ",", "args", ",", "kwargs", ")", ":", "for", "allowance", "in", "self", ".", "_allowances", ":", "if", "allowance", ".", "satisfy_exact_match", "(", "args", ",", "kwargs", ")", ":", "return", "allowance", "for", "allowance", "in", "self", ".", "_allowances", ":", "if", "allowance", ".", "satisfy_custom_matcher", "(", "args", ",", "kwargs", ")", ":", "return", "allowance", "for", "allowance", "in", "self", ".", "_allowances", ":", "if", "allowance", ".", "satisfy_any_args_match", "(", ")", ":", "return", "allowance" ]
Return a matching allowance. Returns the first allowance that matches the ones declared. Tries one with specific arguments first, then falls back to an allowance that allows arbitrary arguments. :return: The matching ``Allowance``, if one was found. :rtype: Allowance, None
[ "Return", "a", "matching", "allowance", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/method_double.py#L68-L88
train
uber/doubles
doubles/method_double.py
MethodDouble._find_matching_double
def _find_matching_double(self, args, kwargs): """Returns the first matching expectation or allowance. Returns the first allowance or expectation that matches the ones declared. Tries one with specific arguments first, then falls back to an expectation that allows arbitrary arguments. :return: The matching ``Allowance`` or ``Expectation``, if one was found. :rtype: Allowance, Expectation, None """ expectation = self._find_matching_expectation(args, kwargs) if expectation: return expectation allowance = self._find_matching_allowance(args, kwargs) if allowance: return allowance
python
def _find_matching_double(self, args, kwargs): """Returns the first matching expectation or allowance. Returns the first allowance or expectation that matches the ones declared. Tries one with specific arguments first, then falls back to an expectation that allows arbitrary arguments. :return: The matching ``Allowance`` or ``Expectation``, if one was found. :rtype: Allowance, Expectation, None """ expectation = self._find_matching_expectation(args, kwargs) if expectation: return expectation allowance = self._find_matching_allowance(args, kwargs) if allowance: return allowance
[ "def", "_find_matching_double", "(", "self", ",", "args", ",", "kwargs", ")", ":", "expectation", "=", "self", ".", "_find_matching_expectation", "(", "args", ",", "kwargs", ")", "if", "expectation", ":", "return", "expectation", "allowance", "=", "self", ".", "_find_matching_allowance", "(", "args", ",", "kwargs", ")", "if", "allowance", ":", "return", "allowance" ]
Returns the first matching expectation or allowance. Returns the first allowance or expectation that matches the ones declared. Tries one with specific arguments first, then falls back to an expectation that allows arbitrary arguments. :return: The matching ``Allowance`` or ``Expectation``, if one was found. :rtype: Allowance, Expectation, None
[ "Returns", "the", "first", "matching", "expectation", "or", "allowance", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/method_double.py#L90-L109
train
uber/doubles
doubles/method_double.py
MethodDouble._find_matching_expectation
def _find_matching_expectation(self, args, kwargs): """Return a matching expectation. Returns the first expectation that matches the ones declared. Tries one with specific arguments first, then falls back to an expectation that allows arbitrary arguments. :return: The matching ``Expectation``, if one was found. :rtype: Expectation, None """ for expectation in self._expectations: if expectation.satisfy_exact_match(args, kwargs): return expectation for expectation in self._expectations: if expectation.satisfy_custom_matcher(args, kwargs): return expectation for expectation in self._expectations: if expectation.satisfy_any_args_match(): return expectation
python
def _find_matching_expectation(self, args, kwargs): """Return a matching expectation. Returns the first expectation that matches the ones declared. Tries one with specific arguments first, then falls back to an expectation that allows arbitrary arguments. :return: The matching ``Expectation``, if one was found. :rtype: Expectation, None """ for expectation in self._expectations: if expectation.satisfy_exact_match(args, kwargs): return expectation for expectation in self._expectations: if expectation.satisfy_custom_matcher(args, kwargs): return expectation for expectation in self._expectations: if expectation.satisfy_any_args_match(): return expectation
[ "def", "_find_matching_expectation", "(", "self", ",", "args", ",", "kwargs", ")", ":", "for", "expectation", "in", "self", ".", "_expectations", ":", "if", "expectation", ".", "satisfy_exact_match", "(", "args", ",", "kwargs", ")", ":", "return", "expectation", "for", "expectation", "in", "self", ".", "_expectations", ":", "if", "expectation", ".", "satisfy_custom_matcher", "(", "args", ",", "kwargs", ")", ":", "return", "expectation", "for", "expectation", "in", "self", ".", "_expectations", ":", "if", "expectation", ".", "satisfy_any_args_match", "(", ")", ":", "return", "expectation" ]
Return a matching expectation. Returns the first expectation that matches the ones declared. Tries one with specific arguments first, then falls back to an expectation that allows arbitrary arguments. :return: The matching ``Expectation``, if one was found. :rtype: Expectation, None
[ "Return", "a", "matching", "expectation", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/method_double.py#L111-L131
train
uber/doubles
doubles/method_double.py
MethodDouble._verify_method
def _verify_method(self): """Verify that a method may be doubled. Verifies that the target object has a method matching the name the user is attempting to double. :raise: ``VerifyingDoubleError`` if no matching method is found. """ class_level = self._target.is_class_or_module() verify_method(self._target, self._method_name, class_level=class_level)
python
def _verify_method(self): """Verify that a method may be doubled. Verifies that the target object has a method matching the name the user is attempting to double. :raise: ``VerifyingDoubleError`` if no matching method is found. """ class_level = self._target.is_class_or_module() verify_method(self._target, self._method_name, class_level=class_level)
[ "def", "_verify_method", "(", "self", ")", ":", "class_level", "=", "self", ".", "_target", ".", "is_class_or_module", "(", ")", "verify_method", "(", "self", ".", "_target", ",", "self", ".", "_method_name", ",", "class_level", "=", "class_level", ")" ]
Verify that a method may be doubled. Verifies that the target object has a method matching the name the user is attempting to double. :raise: ``VerifyingDoubleError`` if no matching method is found.
[ "Verify", "that", "a", "method", "may", "be", "doubled", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/method_double.py#L133-L144
train
uber/doubles
doubles/verification.py
verify_method
def verify_method(target, method_name, class_level=False): """Verifies that the provided method exists on the target object. :param Target target: A ``Target`` object containing the object with the method to double. :param str method_name: The name of the method to double. :raise: ``VerifyingDoubleError`` if the attribute doesn't exist, if it's not a callable object, and in the case where the target is a class, that the attribute isn't an instance method. """ attr = target.get_attr(method_name) if not attr: raise VerifyingDoubleError(method_name, target.doubled_obj).no_matching_method() if attr.kind == 'data' and not isbuiltin(attr.object) and not is_callable(attr.object): raise VerifyingDoubleError(method_name, target.doubled_obj).not_callable() if class_level and attr.kind == 'method' and method_name != '__new__': raise VerifyingDoubleError(method_name, target.doubled_obj).requires_instance()
python
def verify_method(target, method_name, class_level=False): """Verifies that the provided method exists on the target object. :param Target target: A ``Target`` object containing the object with the method to double. :param str method_name: The name of the method to double. :raise: ``VerifyingDoubleError`` if the attribute doesn't exist, if it's not a callable object, and in the case where the target is a class, that the attribute isn't an instance method. """ attr = target.get_attr(method_name) if not attr: raise VerifyingDoubleError(method_name, target.doubled_obj).no_matching_method() if attr.kind == 'data' and not isbuiltin(attr.object) and not is_callable(attr.object): raise VerifyingDoubleError(method_name, target.doubled_obj).not_callable() if class_level and attr.kind == 'method' and method_name != '__new__': raise VerifyingDoubleError(method_name, target.doubled_obj).requires_instance()
[ "def", "verify_method", "(", "target", ",", "method_name", ",", "class_level", "=", "False", ")", ":", "attr", "=", "target", ".", "get_attr", "(", "method_name", ")", "if", "not", "attr", ":", "raise", "VerifyingDoubleError", "(", "method_name", ",", "target", ".", "doubled_obj", ")", ".", "no_matching_method", "(", ")", "if", "attr", ".", "kind", "==", "'data'", "and", "not", "isbuiltin", "(", "attr", ".", "object", ")", "and", "not", "is_callable", "(", "attr", ".", "object", ")", ":", "raise", "VerifyingDoubleError", "(", "method_name", ",", "target", ".", "doubled_obj", ")", ".", "not_callable", "(", ")", "if", "class_level", "and", "attr", ".", "kind", "==", "'method'", "and", "method_name", "!=", "'__new__'", ":", "raise", "VerifyingDoubleError", "(", "method_name", ",", "target", ".", "doubled_obj", ")", ".", "requires_instance", "(", ")" ]
Verifies that the provided method exists on the target object. :param Target target: A ``Target`` object containing the object with the method to double. :param str method_name: The name of the method to double. :raise: ``VerifyingDoubleError`` if the attribute doesn't exist, if it's not a callable object, and in the case where the target is a class, that the attribute isn't an instance method.
[ "Verifies", "that", "the", "provided", "method", "exists", "on", "the", "target", "object", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/verification.py#L76-L94
train
uber/doubles
doubles/verification.py
verify_arguments
def verify_arguments(target, method_name, args, kwargs): """Verifies that the provided arguments match the signature of the provided method. :param Target target: A ``Target`` object containing the object with the method to double. :param str method_name: The name of the method to double. :param tuple args: The positional arguments the method should be called with. :param dict kwargs: The keyword arguments the method should be called with. :raise: ``VerifyingDoubleError`` if the provided arguments do not match the signature. """ if method_name == '_doubles__new__': return _verify_arguments_of_doubles__new__(target, args, kwargs) attr = target.get_attr(method_name) method = attr.object if attr.kind in ('data', 'attribute', 'toplevel', 'class method', 'static method'): try: method = method.__get__(None, attr.defining_class) except AttributeError: method = method.__call__ elif attr.kind == 'property': if args or kwargs: raise VerifyingDoubleArgumentError("Properties do not accept arguments.") return else: args = ['self_or_cls'] + list(args) _verify_arguments(method, method_name, args, kwargs)
python
def verify_arguments(target, method_name, args, kwargs): """Verifies that the provided arguments match the signature of the provided method. :param Target target: A ``Target`` object containing the object with the method to double. :param str method_name: The name of the method to double. :param tuple args: The positional arguments the method should be called with. :param dict kwargs: The keyword arguments the method should be called with. :raise: ``VerifyingDoubleError`` if the provided arguments do not match the signature. """ if method_name == '_doubles__new__': return _verify_arguments_of_doubles__new__(target, args, kwargs) attr = target.get_attr(method_name) method = attr.object if attr.kind in ('data', 'attribute', 'toplevel', 'class method', 'static method'): try: method = method.__get__(None, attr.defining_class) except AttributeError: method = method.__call__ elif attr.kind == 'property': if args or kwargs: raise VerifyingDoubleArgumentError("Properties do not accept arguments.") return else: args = ['self_or_cls'] + list(args) _verify_arguments(method, method_name, args, kwargs)
[ "def", "verify_arguments", "(", "target", ",", "method_name", ",", "args", ",", "kwargs", ")", ":", "if", "method_name", "==", "'_doubles__new__'", ":", "return", "_verify_arguments_of_doubles__new__", "(", "target", ",", "args", ",", "kwargs", ")", "attr", "=", "target", ".", "get_attr", "(", "method_name", ")", "method", "=", "attr", ".", "object", "if", "attr", ".", "kind", "in", "(", "'data'", ",", "'attribute'", ",", "'toplevel'", ",", "'class method'", ",", "'static method'", ")", ":", "try", ":", "method", "=", "method", ".", "__get__", "(", "None", ",", "attr", ".", "defining_class", ")", "except", "AttributeError", ":", "method", "=", "method", ".", "__call__", "elif", "attr", ".", "kind", "==", "'property'", ":", "if", "args", "or", "kwargs", ":", "raise", "VerifyingDoubleArgumentError", "(", "\"Properties do not accept arguments.\"", ")", "return", "else", ":", "args", "=", "[", "'self_or_cls'", "]", "+", "list", "(", "args", ")", "_verify_arguments", "(", "method", ",", "method_name", ",", "args", ",", "kwargs", ")" ]
Verifies that the provided arguments match the signature of the provided method. :param Target target: A ``Target`` object containing the object with the method to double. :param str method_name: The name of the method to double. :param tuple args: The positional arguments the method should be called with. :param dict kwargs: The keyword arguments the method should be called with. :raise: ``VerifyingDoubleError`` if the provided arguments do not match the signature.
[ "Verifies", "that", "the", "provided", "arguments", "match", "the", "signature", "of", "the", "provided", "method", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/verification.py#L97-L125
train
uber/doubles
doubles/targets/allowance_target.py
allow_constructor
def allow_constructor(target): """ Set an allowance on a ``ClassDouble`` constructor This allows the caller to control what a ClassDouble returns when a new instance is created. :param ClassDouble target: The ClassDouble to set the allowance on. :return: an ``Allowance`` for the __new__ method. :raise: ``ConstructorDoubleError`` if target is not a ClassDouble. """ if not isinstance(target, ClassDouble): raise ConstructorDoubleError( 'Cannot allow_constructor of {} since it is not a ClassDouble.'.format(target), ) return allow(target)._doubles__new__
python
def allow_constructor(target): """ Set an allowance on a ``ClassDouble`` constructor This allows the caller to control what a ClassDouble returns when a new instance is created. :param ClassDouble target: The ClassDouble to set the allowance on. :return: an ``Allowance`` for the __new__ method. :raise: ``ConstructorDoubleError`` if target is not a ClassDouble. """ if not isinstance(target, ClassDouble): raise ConstructorDoubleError( 'Cannot allow_constructor of {} since it is not a ClassDouble.'.format(target), ) return allow(target)._doubles__new__
[ "def", "allow_constructor", "(", "target", ")", ":", "if", "not", "isinstance", "(", "target", ",", "ClassDouble", ")", ":", "raise", "ConstructorDoubleError", "(", "'Cannot allow_constructor of {} since it is not a ClassDouble.'", ".", "format", "(", "target", ")", ",", ")", "return", "allow", "(", "target", ")", ".", "_doubles__new__" ]
Set an allowance on a ``ClassDouble`` constructor This allows the caller to control what a ClassDouble returns when a new instance is created. :param ClassDouble target: The ClassDouble to set the allowance on. :return: an ``Allowance`` for the __new__ method. :raise: ``ConstructorDoubleError`` if target is not a ClassDouble.
[ "Set", "an", "allowance", "on", "a", "ClassDouble", "constructor" ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/targets/allowance_target.py#L25-L40
train
uber/doubles
doubles/targets/patch_target.py
patch
def patch(target, value): """ Replace the specified object :param str target: A string pointing to the target to patch. :param object value: The value to replace the target with. :return: A ``Patch`` object. """ patch = current_space().patch_for(target) patch.set_value(value) return patch
python
def patch(target, value): """ Replace the specified object :param str target: A string pointing to the target to patch. :param object value: The value to replace the target with. :return: A ``Patch`` object. """ patch = current_space().patch_for(target) patch.set_value(value) return patch
[ "def", "patch", "(", "target", ",", "value", ")", ":", "patch", "=", "current_space", "(", ")", ".", "patch_for", "(", "target", ")", "patch", ".", "set_value", "(", "value", ")", "return", "patch" ]
Replace the specified object :param str target: A string pointing to the target to patch. :param object value: The value to replace the target with. :return: A ``Patch`` object.
[ "Replace", "the", "specified", "object" ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/targets/patch_target.py#L18-L28
train
uber/doubles
doubles/utils.py
get_path_components
def get_path_components(path): """Extract the module name and class name out of the fully qualified path to the class. :param str path: The full path to the class. :return: The module path and the class name. :rtype: str, str :raise: ``VerifyingDoubleImportError`` if the path is to a top-level module. """ path_segments = path.split('.') module_path = '.'.join(path_segments[:-1]) if module_path == '': raise VerifyingDoubleImportError('Invalid import path: {}.'.format(path)) class_name = path_segments[-1] return module_path, class_name
python
def get_path_components(path): """Extract the module name and class name out of the fully qualified path to the class. :param str path: The full path to the class. :return: The module path and the class name. :rtype: str, str :raise: ``VerifyingDoubleImportError`` if the path is to a top-level module. """ path_segments = path.split('.') module_path = '.'.join(path_segments[:-1]) if module_path == '': raise VerifyingDoubleImportError('Invalid import path: {}.'.format(path)) class_name = path_segments[-1] return module_path, class_name
[ "def", "get_path_components", "(", "path", ")", ":", "path_segments", "=", "path", ".", "split", "(", "'.'", ")", "module_path", "=", "'.'", ".", "join", "(", "path_segments", "[", ":", "-", "1", "]", ")", "if", "module_path", "==", "''", ":", "raise", "VerifyingDoubleImportError", "(", "'Invalid import path: {}.'", ".", "format", "(", "path", ")", ")", "class_name", "=", "path_segments", "[", "-", "1", "]", "return", "module_path", ",", "class_name" ]
Extract the module name and class name out of the fully qualified path to the class. :param str path: The full path to the class. :return: The module path and the class name. :rtype: str, str :raise: ``VerifyingDoubleImportError`` if the path is to a top-level module.
[ "Extract", "the", "module", "name", "and", "class", "name", "out", "of", "the", "fully", "qualified", "path", "to", "the", "class", "." ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/utils.py#L22-L39
train
uber/doubles
doubles/targets/expectation_target.py
expect_constructor
def expect_constructor(target): """ Set an expectation on a ``ClassDouble`` constructor :param ClassDouble target: The ClassDouble to set the expectation on. :return: an ``Expectation`` for the __new__ method. :raise: ``ConstructorDoubleError`` if target is not a ClassDouble. """ if not isinstance(target, ClassDouble): raise ConstructorDoubleError( 'Cannot allow_constructor of {} since it is not a ClassDouble.'.format(target), ) return expect(target)._doubles__new__
python
def expect_constructor(target): """ Set an expectation on a ``ClassDouble`` constructor :param ClassDouble target: The ClassDouble to set the expectation on. :return: an ``Expectation`` for the __new__ method. :raise: ``ConstructorDoubleError`` if target is not a ClassDouble. """ if not isinstance(target, ClassDouble): raise ConstructorDoubleError( 'Cannot allow_constructor of {} since it is not a ClassDouble.'.format(target), ) return expect(target)._doubles__new__
[ "def", "expect_constructor", "(", "target", ")", ":", "if", "not", "isinstance", "(", "target", ",", "ClassDouble", ")", ":", "raise", "ConstructorDoubleError", "(", "'Cannot allow_constructor of {} since it is not a ClassDouble.'", ".", "format", "(", "target", ")", ",", ")", "return", "expect", "(", "target", ")", ".", "_doubles__new__" ]
Set an expectation on a ``ClassDouble`` constructor :param ClassDouble target: The ClassDouble to set the expectation on. :return: an ``Expectation`` for the __new__ method. :raise: ``ConstructorDoubleError`` if target is not a ClassDouble.
[ "Set", "an", "expectation", "on", "a", "ClassDouble", "constructor" ]
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/targets/expectation_target.py#L25-L38
train
thombashi/pytablewriter
pytablewriter/writer/text/_markdown.py
MarkdownTableWriter.write_table
def write_table(self): """ |write_table| with Markdown table format. :raises pytablewriter.EmptyHeaderError: If the |headers| is empty. :Example: :ref:`example-markdown-table-writer` .. note:: - |None| values are written as an empty string - Vertical bar characters (``'|'``) in table items are escaped """ with self._logger: self._verify_property() self.__write_chapter() self._write_table() if self.is_write_null_line_after_table: self.write_null_line()
python
def write_table(self): """ |write_table| with Markdown table format. :raises pytablewriter.EmptyHeaderError: If the |headers| is empty. :Example: :ref:`example-markdown-table-writer` .. note:: - |None| values are written as an empty string - Vertical bar characters (``'|'``) in table items are escaped """ with self._logger: self._verify_property() self.__write_chapter() self._write_table() if self.is_write_null_line_after_table: self.write_null_line()
[ "def", "write_table", "(", "self", ")", ":", "with", "self", ".", "_logger", ":", "self", ".", "_verify_property", "(", ")", "self", ".", "__write_chapter", "(", ")", "self", ".", "_write_table", "(", ")", "if", "self", ".", "is_write_null_line_after_table", ":", "self", ".", "write_null_line", "(", ")" ]
|write_table| with Markdown table format. :raises pytablewriter.EmptyHeaderError: If the |headers| is empty. :Example: :ref:`example-markdown-table-writer` .. note:: - |None| values are written as an empty string - Vertical bar characters (``'|'``) in table items are escaped
[ "|write_table|", "with", "Markdown", "table", "format", "." ]
52ea85ed8e89097afa64f137c6a1b3acdfefdbda
https://github.com/thombashi/pytablewriter/blob/52ea85ed8e89097afa64f137c6a1b3acdfefdbda/pytablewriter/writer/text/_markdown.py#L86-L104
train
thombashi/pytablewriter
pytablewriter/writer/text/_html.py
HtmlTableWriter.write_table
def write_table(self): """ |write_table| with HTML table format. :Example: :ref:`example-html-table-writer` .. note:: - |None| is not written """ tags = _get_tags_module() with self._logger: self._verify_property() self._preprocess() if typepy.is_not_null_string(self.table_name): self._table_tag = tags.table(id=sanitize_python_var_name(self.table_name)) self._table_tag += tags.caption(MultiByteStrDecoder(self.table_name).unicode_str) else: self._table_tag = tags.table() try: self._write_header() except EmptyHeaderError: pass self._write_body()
python
def write_table(self): """ |write_table| with HTML table format. :Example: :ref:`example-html-table-writer` .. note:: - |None| is not written """ tags = _get_tags_module() with self._logger: self._verify_property() self._preprocess() if typepy.is_not_null_string(self.table_name): self._table_tag = tags.table(id=sanitize_python_var_name(self.table_name)) self._table_tag += tags.caption(MultiByteStrDecoder(self.table_name).unicode_str) else: self._table_tag = tags.table() try: self._write_header() except EmptyHeaderError: pass self._write_body()
[ "def", "write_table", "(", "self", ")", ":", "tags", "=", "_get_tags_module", "(", ")", "with", "self", ".", "_logger", ":", "self", ".", "_verify_property", "(", ")", "self", ".", "_preprocess", "(", ")", "if", "typepy", ".", "is_not_null_string", "(", "self", ".", "table_name", ")", ":", "self", ".", "_table_tag", "=", "tags", ".", "table", "(", "id", "=", "sanitize_python_var_name", "(", "self", ".", "table_name", ")", ")", "self", ".", "_table_tag", "+=", "tags", ".", "caption", "(", "MultiByteStrDecoder", "(", "self", ".", "table_name", ")", ".", "unicode_str", ")", "else", ":", "self", ".", "_table_tag", "=", "tags", ".", "table", "(", ")", "try", ":", "self", ".", "_write_header", "(", ")", "except", "EmptyHeaderError", ":", "pass", "self", ".", "_write_body", "(", ")" ]
|write_table| with HTML table format. :Example: :ref:`example-html-table-writer` .. note:: - |None| is not written
[ "|write_table|", "with", "HTML", "table", "format", "." ]
52ea85ed8e89097afa64f137c6a1b3acdfefdbda
https://github.com/thombashi/pytablewriter/blob/52ea85ed8e89097afa64f137c6a1b3acdfefdbda/pytablewriter/writer/text/_html.py#L57-L85
train
thombashi/pytablewriter
pytablewriter/writer/text/_text_writer.py
TextTableWriter.dump
def dump(self, output, close_after_write=True): """Write data to the output with tabular format. Args: output (file descriptor or str): file descriptor or path to the output file. close_after_write (bool, optional): Close the output after write. Defaults to |True|. """ try: output.write self.stream = output except AttributeError: self.stream = io.open(output, "w", encoding="utf-8") try: self.write_table() finally: if close_after_write: self.stream.close() self.stream = sys.stdout
python
def dump(self, output, close_after_write=True): """Write data to the output with tabular format. Args: output (file descriptor or str): file descriptor or path to the output file. close_after_write (bool, optional): Close the output after write. Defaults to |True|. """ try: output.write self.stream = output except AttributeError: self.stream = io.open(output, "w", encoding="utf-8") try: self.write_table() finally: if close_after_write: self.stream.close() self.stream = sys.stdout
[ "def", "dump", "(", "self", ",", "output", ",", "close_after_write", "=", "True", ")", ":", "try", ":", "output", ".", "write", "self", ".", "stream", "=", "output", "except", "AttributeError", ":", "self", ".", "stream", "=", "io", ".", "open", "(", "output", ",", "\"w\"", ",", "encoding", "=", "\"utf-8\"", ")", "try", ":", "self", ".", "write_table", "(", ")", "finally", ":", "if", "close_after_write", ":", "self", ".", "stream", ".", "close", "(", ")", "self", ".", "stream", "=", "sys", ".", "stdout" ]
Write data to the output with tabular format. Args: output (file descriptor or str): file descriptor or path to the output file. close_after_write (bool, optional): Close the output after write. Defaults to |True|.
[ "Write", "data", "to", "the", "output", "with", "tabular", "format", "." ]
52ea85ed8e89097afa64f137c6a1b3acdfefdbda
https://github.com/thombashi/pytablewriter/blob/52ea85ed8e89097afa64f137c6a1b3acdfefdbda/pytablewriter/writer/text/_text_writer.py#L179-L201
train
thombashi/pytablewriter
pytablewriter/writer/text/_text_writer.py
TextTableWriter.dumps
def dumps(self): """Get rendered tabular text from the table data. Only available for text format table writers. Returns: str: Rendered tabular text. """ old_stream = self.stream try: self.stream = six.StringIO() self.write_table() tabular_text = self.stream.getvalue() finally: self.stream = old_stream return tabular_text
python
def dumps(self): """Get rendered tabular text from the table data. Only available for text format table writers. Returns: str: Rendered tabular text. """ old_stream = self.stream try: self.stream = six.StringIO() self.write_table() tabular_text = self.stream.getvalue() finally: self.stream = old_stream return tabular_text
[ "def", "dumps", "(", "self", ")", ":", "old_stream", "=", "self", ".", "stream", "try", ":", "self", ".", "stream", "=", "six", ".", "StringIO", "(", ")", "self", ".", "write_table", "(", ")", "tabular_text", "=", "self", ".", "stream", ".", "getvalue", "(", ")", "finally", ":", "self", ".", "stream", "=", "old_stream", "return", "tabular_text" ]
Get rendered tabular text from the table data. Only available for text format table writers. Returns: str: Rendered tabular text.
[ "Get", "rendered", "tabular", "text", "from", "the", "table", "data", "." ]
52ea85ed8e89097afa64f137c6a1b3acdfefdbda
https://github.com/thombashi/pytablewriter/blob/52ea85ed8e89097afa64f137c6a1b3acdfefdbda/pytablewriter/writer/text/_text_writer.py#L203-L221
train
thombashi/pytablewriter
pytablewriter/writer/binary/_excel.py
ExcelTableWriter.open
def open(self, file_path): """ Open an Excel workbook file. :param str file_path: Excel workbook file path to open. """ if self.is_opened() and self.workbook.file_path == file_path: self._logger.logger.debug("workbook already opened: {}".format(self.workbook.file_path)) return self.close() self._open(file_path)
python
def open(self, file_path): """ Open an Excel workbook file. :param str file_path: Excel workbook file path to open. """ if self.is_opened() and self.workbook.file_path == file_path: self._logger.logger.debug("workbook already opened: {}".format(self.workbook.file_path)) return self.close() self._open(file_path)
[ "def", "open", "(", "self", ",", "file_path", ")", ":", "if", "self", ".", "is_opened", "(", ")", "and", "self", ".", "workbook", ".", "file_path", "==", "file_path", ":", "self", ".", "_logger", ".", "logger", ".", "debug", "(", "\"workbook already opened: {}\"", ".", "format", "(", "self", ".", "workbook", ".", "file_path", ")", ")", "return", "self", ".", "close", "(", ")", "self", ".", "_open", "(", "file_path", ")" ]
Open an Excel workbook file. :param str file_path: Excel workbook file path to open.
[ "Open", "an", "Excel", "workbook", "file", "." ]
52ea85ed8e89097afa64f137c6a1b3acdfefdbda
https://github.com/thombashi/pytablewriter/blob/52ea85ed8e89097afa64f137c6a1b3acdfefdbda/pytablewriter/writer/binary/_excel.py#L129-L141
train
thombashi/pytablewriter
pytablewriter/writer/binary/_excel.py
ExcelTableWriter.from_tabledata
def from_tabledata(self, value, is_overwrite_table_name=True): """ Set following attributes from |TableData| - :py:attr:`~.table_name`. - :py:attr:`~.headers`. - :py:attr:`~.value_matrix`. And create worksheet named from :py:attr:`~.table_name` ABC if not existed yet. :param tabledata.TableData value: Input table data. """ super(ExcelTableWriter, self).from_tabledata(value) if self.is_opened(): self.make_worksheet(self.table_name)
python
def from_tabledata(self, value, is_overwrite_table_name=True): """ Set following attributes from |TableData| - :py:attr:`~.table_name`. - :py:attr:`~.headers`. - :py:attr:`~.value_matrix`. And create worksheet named from :py:attr:`~.table_name` ABC if not existed yet. :param tabledata.TableData value: Input table data. """ super(ExcelTableWriter, self).from_tabledata(value) if self.is_opened(): self.make_worksheet(self.table_name)
[ "def", "from_tabledata", "(", "self", ",", "value", ",", "is_overwrite_table_name", "=", "True", ")", ":", "super", "(", "ExcelTableWriter", ",", "self", ")", ".", "from_tabledata", "(", "value", ")", "if", "self", ".", "is_opened", "(", ")", ":", "self", ".", "make_worksheet", "(", "self", ".", "table_name", ")" ]
Set following attributes from |TableData| - :py:attr:`~.table_name`. - :py:attr:`~.headers`. - :py:attr:`~.value_matrix`. And create worksheet named from :py:attr:`~.table_name` ABC if not existed yet. :param tabledata.TableData value: Input table data.
[ "Set", "following", "attributes", "from", "|TableData|" ]
52ea85ed8e89097afa64f137c6a1b3acdfefdbda
https://github.com/thombashi/pytablewriter/blob/52ea85ed8e89097afa64f137c6a1b3acdfefdbda/pytablewriter/writer/binary/_excel.py#L166-L183
train
thombashi/pytablewriter
pytablewriter/writer/binary/_excel.py
ExcelTableWriter.make_worksheet
def make_worksheet(self, sheet_name=None): """Make a worksheet to the current workbook. Args: sheet_name (str): Name of the worksheet to create. The name will be automatically generated (like ``"Sheet1"``) if the ``sheet_name`` is empty. """ if sheet_name is None: sheet_name = self.table_name if not sheet_name: sheet_name = "" self._stream = self.workbook.add_worksheet(sheet_name) self._current_data_row = self._first_data_row
python
def make_worksheet(self, sheet_name=None): """Make a worksheet to the current workbook. Args: sheet_name (str): Name of the worksheet to create. The name will be automatically generated (like ``"Sheet1"``) if the ``sheet_name`` is empty. """ if sheet_name is None: sheet_name = self.table_name if not sheet_name: sheet_name = "" self._stream = self.workbook.add_worksheet(sheet_name) self._current_data_row = self._first_data_row
[ "def", "make_worksheet", "(", "self", ",", "sheet_name", "=", "None", ")", ":", "if", "sheet_name", "is", "None", ":", "sheet_name", "=", "self", ".", "table_name", "if", "not", "sheet_name", ":", "sheet_name", "=", "\"\"", "self", ".", "_stream", "=", "self", ".", "workbook", ".", "add_worksheet", "(", "sheet_name", ")", "self", ".", "_current_data_row", "=", "self", ".", "_first_data_row" ]
Make a worksheet to the current workbook. Args: sheet_name (str): Name of the worksheet to create. The name will be automatically generated (like ``"Sheet1"``) if the ``sheet_name`` is empty.
[ "Make", "a", "worksheet", "to", "the", "current", "workbook", "." ]
52ea85ed8e89097afa64f137c6a1b3acdfefdbda
https://github.com/thombashi/pytablewriter/blob/52ea85ed8e89097afa64f137c6a1b3acdfefdbda/pytablewriter/writer/binary/_excel.py#L185-L200
train
thombashi/pytablewriter
pytablewriter/writer/binary/_excel.py
ExcelTableWriter.dump
def dump(self, output, close_after_write=True): """Write a worksheet to the current workbook. Args: output (str): Path to the workbook file to write. close_after_write (bool, optional): Close the workbook after write. Defaults to |True|. """ self.open(output) try: self.make_worksheet(self.table_name) self.write_table() finally: if close_after_write: self.close()
python
def dump(self, output, close_after_write=True): """Write a worksheet to the current workbook. Args: output (str): Path to the workbook file to write. close_after_write (bool, optional): Close the workbook after write. Defaults to |True|. """ self.open(output) try: self.make_worksheet(self.table_name) self.write_table() finally: if close_after_write: self.close()
[ "def", "dump", "(", "self", ",", "output", ",", "close_after_write", "=", "True", ")", ":", "self", ".", "open", "(", "output", ")", "try", ":", "self", ".", "make_worksheet", "(", "self", ".", "table_name", ")", "self", ".", "write_table", "(", ")", "finally", ":", "if", "close_after_write", ":", "self", ".", "close", "(", ")" ]
Write a worksheet to the current workbook. Args: output (str): Path to the workbook file to write. close_after_write (bool, optional): Close the workbook after write. Defaults to |True|.
[ "Write", "a", "worksheet", "to", "the", "current", "workbook", "." ]
52ea85ed8e89097afa64f137c6a1b3acdfefdbda
https://github.com/thombashi/pytablewriter/blob/52ea85ed8e89097afa64f137c6a1b3acdfefdbda/pytablewriter/writer/binary/_excel.py#L202-L219
train
thombashi/pytablewriter
pytablewriter/writer/binary/_sqlite.py
SqliteTableWriter.open
def open(self, file_path): """ Open a SQLite database file. :param str file_path: SQLite database file path to open. """ from simplesqlite import SimpleSQLite if self.is_opened(): if self.stream.database_path == abspath(file_path): self._logger.logger.debug( "database already opened: {}".format(self.stream.database_path) ) return self.close() self._stream = SimpleSQLite(file_path, "w")
python
def open(self, file_path): """ Open a SQLite database file. :param str file_path: SQLite database file path to open. """ from simplesqlite import SimpleSQLite if self.is_opened(): if self.stream.database_path == abspath(file_path): self._logger.logger.debug( "database already opened: {}".format(self.stream.database_path) ) return self.close() self._stream = SimpleSQLite(file_path, "w")
[ "def", "open", "(", "self", ",", "file_path", ")", ":", "from", "simplesqlite", "import", "SimpleSQLite", "if", "self", ".", "is_opened", "(", ")", ":", "if", "self", ".", "stream", ".", "database_path", "==", "abspath", "(", "file_path", ")", ":", "self", ".", "_logger", ".", "logger", ".", "debug", "(", "\"database already opened: {}\"", ".", "format", "(", "self", ".", "stream", ".", "database_path", ")", ")", "return", "self", ".", "close", "(", ")", "self", ".", "_stream", "=", "SimpleSQLite", "(", "file_path", ",", "\"w\"", ")" ]
Open a SQLite database file. :param str file_path: SQLite database file path to open.
[ "Open", "a", "SQLite", "database", "file", "." ]
52ea85ed8e89097afa64f137c6a1b3acdfefdbda
https://github.com/thombashi/pytablewriter/blob/52ea85ed8e89097afa64f137c6a1b3acdfefdbda/pytablewriter/writer/binary/_sqlite.py#L61-L79
train
thombashi/pytablewriter
pytablewriter/writer/_table_writer.py
AbstractTableWriter.set_style
def set_style(self, column, style): """Set |Style| for a specific column. Args: column (|int| or |str|): Column specifier. column index or header name correlated with the column. style (|Style|): Style value to be set to the column. Raises: ValueError: If the column specifier is invalid. """ column_idx = None while len(self.headers) > len(self.__style_list): self.__style_list.append(None) if isinstance(column, six.integer_types): column_idx = column elif isinstance(column, six.string_types): try: column_idx = self.headers.index(column) except ValueError: pass if column_idx is not None: self.__style_list[column_idx] = style self.__clear_preprocess() self._dp_extractor.format_flags_list = [ _ts_to_flag[self.__get_thousand_separator(col_idx)] for col_idx in range(len(self.__style_list)) ] return raise ValueError("column must be an int or string: actual={}".format(column))
python
def set_style(self, column, style): """Set |Style| for a specific column. Args: column (|int| or |str|): Column specifier. column index or header name correlated with the column. style (|Style|): Style value to be set to the column. Raises: ValueError: If the column specifier is invalid. """ column_idx = None while len(self.headers) > len(self.__style_list): self.__style_list.append(None) if isinstance(column, six.integer_types): column_idx = column elif isinstance(column, six.string_types): try: column_idx = self.headers.index(column) except ValueError: pass if column_idx is not None: self.__style_list[column_idx] = style self.__clear_preprocess() self._dp_extractor.format_flags_list = [ _ts_to_flag[self.__get_thousand_separator(col_idx)] for col_idx in range(len(self.__style_list)) ] return raise ValueError("column must be an int or string: actual={}".format(column))
[ "def", "set_style", "(", "self", ",", "column", ",", "style", ")", ":", "column_idx", "=", "None", "while", "len", "(", "self", ".", "headers", ")", ">", "len", "(", "self", ".", "__style_list", ")", ":", "self", ".", "__style_list", ".", "append", "(", "None", ")", "if", "isinstance", "(", "column", ",", "six", ".", "integer_types", ")", ":", "column_idx", "=", "column", "elif", "isinstance", "(", "column", ",", "six", ".", "string_types", ")", ":", "try", ":", "column_idx", "=", "self", ".", "headers", ".", "index", "(", "column", ")", "except", "ValueError", ":", "pass", "if", "column_idx", "is", "not", "None", ":", "self", ".", "__style_list", "[", "column_idx", "]", "=", "style", "self", ".", "__clear_preprocess", "(", ")", "self", ".", "_dp_extractor", ".", "format_flags_list", "=", "[", "_ts_to_flag", "[", "self", ".", "__get_thousand_separator", "(", "col_idx", ")", "]", "for", "col_idx", "in", "range", "(", "len", "(", "self", ".", "__style_list", ")", ")", "]", "return", "raise", "ValueError", "(", "\"column must be an int or string: actual={}\"", ".", "format", "(", "column", ")", ")" ]
Set |Style| for a specific column. Args: column (|int| or |str|): Column specifier. column index or header name correlated with the column. style (|Style|): Style value to be set to the column. Raises: ValueError: If the column specifier is invalid.
[ "Set", "|Style|", "for", "a", "specific", "column", "." ]
52ea85ed8e89097afa64f137c6a1b3acdfefdbda
https://github.com/thombashi/pytablewriter/blob/52ea85ed8e89097afa64f137c6a1b3acdfefdbda/pytablewriter/writer/_table_writer.py#L458-L493
train
thombashi/pytablewriter
pytablewriter/writer/_table_writer.py
AbstractTableWriter.close
def close(self): """ Close the current |stream|. """ if self.stream is None: return try: self.stream.isatty() if self.stream.name in ["<stdin>", "<stdout>", "<stderr>"]: return except AttributeError: pass except ValueError: # raised when executing an operation to a closed stream pass try: from _pytest.compat import CaptureIO from _pytest.capture import EncodedFile if isinstance(self.stream, (CaptureIO, EncodedFile)): # avoid closing streams for pytest return except ImportError: pass try: from ipykernel.iostream import OutStream if isinstance(self.stream, OutStream): # avoid closing streams for Jupyter Notebook return except ImportError: pass try: self.stream.close() except AttributeError: self._logger.logger.warn( "the stream has no close method implementation: type={}".format(type(self.stream)) ) finally: self._stream = None
python
def close(self): """ Close the current |stream|. """ if self.stream is None: return try: self.stream.isatty() if self.stream.name in ["<stdin>", "<stdout>", "<stderr>"]: return except AttributeError: pass except ValueError: # raised when executing an operation to a closed stream pass try: from _pytest.compat import CaptureIO from _pytest.capture import EncodedFile if isinstance(self.stream, (CaptureIO, EncodedFile)): # avoid closing streams for pytest return except ImportError: pass try: from ipykernel.iostream import OutStream if isinstance(self.stream, OutStream): # avoid closing streams for Jupyter Notebook return except ImportError: pass try: self.stream.close() except AttributeError: self._logger.logger.warn( "the stream has no close method implementation: type={}".format(type(self.stream)) ) finally: self._stream = None
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "stream", "is", "None", ":", "return", "try", ":", "self", ".", "stream", ".", "isatty", "(", ")", "if", "self", ".", "stream", ".", "name", "in", "[", "\"<stdin>\"", ",", "\"<stdout>\"", ",", "\"<stderr>\"", "]", ":", "return", "except", "AttributeError", ":", "pass", "except", "ValueError", ":", "# raised when executing an operation to a closed stream", "pass", "try", ":", "from", "_pytest", ".", "compat", "import", "CaptureIO", "from", "_pytest", ".", "capture", "import", "EncodedFile", "if", "isinstance", "(", "self", ".", "stream", ",", "(", "CaptureIO", ",", "EncodedFile", ")", ")", ":", "# avoid closing streams for pytest", "return", "except", "ImportError", ":", "pass", "try", ":", "from", "ipykernel", ".", "iostream", "import", "OutStream", "if", "isinstance", "(", "self", ".", "stream", ",", "OutStream", ")", ":", "# avoid closing streams for Jupyter Notebook", "return", "except", "ImportError", ":", "pass", "try", ":", "self", ".", "stream", ".", "close", "(", ")", "except", "AttributeError", ":", "self", ".", "_logger", ".", "logger", ".", "warn", "(", "\"the stream has no close method implementation: type={}\"", ".", "format", "(", "type", "(", "self", ".", "stream", ")", ")", ")", "finally", ":", "self", ".", "_stream", "=", "None" ]
Close the current |stream|.
[ "Close", "the", "current", "|stream|", "." ]
52ea85ed8e89097afa64f137c6a1b3acdfefdbda
https://github.com/thombashi/pytablewriter/blob/52ea85ed8e89097afa64f137c6a1b3acdfefdbda/pytablewriter/writer/_table_writer.py#L495-L540
train
heroku/heroku.py
heroku/models.py
BaseResource._ids
def _ids(self): """The list of primary keys to validate against.""" for pk in self._pks: yield getattr(self, pk) for pk in self._pks: try: yield str(getattr(self, pk)) except ValueError: pass
python
def _ids(self): """The list of primary keys to validate against.""" for pk in self._pks: yield getattr(self, pk) for pk in self._pks: try: yield str(getattr(self, pk)) except ValueError: pass
[ "def", "_ids", "(", "self", ")", ":", "for", "pk", "in", "self", ".", "_pks", ":", "yield", "getattr", "(", "self", ",", "pk", ")", "for", "pk", "in", "self", ".", "_pks", ":", "try", ":", "yield", "str", "(", "getattr", "(", "self", ",", "pk", ")", ")", "except", "ValueError", ":", "pass" ]
The list of primary keys to validate against.
[ "The", "list", "of", "primary", "keys", "to", "validate", "against", "." ]
cadc0a074896cf29c65a457c5c5bdb2069470af0
https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/models.py#L57-L67
train
heroku/heroku.py
heroku/models.py
Addon.upgrade
def upgrade(self, name, params=None): """Upgrades an addon to the given tier.""" # Allow non-namespaced upgrades. (e.g. advanced vs logging:advanced) if ':' not in name: name = '{0}:{1}'.format(self.type, name) r = self._h._http_resource( method='PUT', resource=('apps', self.app.name, 'addons', quote(name)), params=params, data=' ' # Server weirdness. ) r.raise_for_status() return self.app.addons[name]
python
def upgrade(self, name, params=None): """Upgrades an addon to the given tier.""" # Allow non-namespaced upgrades. (e.g. advanced vs logging:advanced) if ':' not in name: name = '{0}:{1}'.format(self.type, name) r = self._h._http_resource( method='PUT', resource=('apps', self.app.name, 'addons', quote(name)), params=params, data=' ' # Server weirdness. ) r.raise_for_status() return self.app.addons[name]
[ "def", "upgrade", "(", "self", ",", "name", ",", "params", "=", "None", ")", ":", "# Allow non-namespaced upgrades. (e.g. advanced vs logging:advanced)", "if", "':'", "not", "in", "name", ":", "name", "=", "'{0}:{1}'", ".", "format", "(", "self", ".", "type", ",", "name", ")", "r", "=", "self", ".", "_h", ".", "_http_resource", "(", "method", "=", "'PUT'", ",", "resource", "=", "(", "'apps'", ",", "self", ".", "app", ".", "name", ",", "'addons'", ",", "quote", "(", "name", ")", ")", ",", "params", "=", "params", ",", "data", "=", "' '", "# Server weirdness.", ")", "r", ".", "raise_for_status", "(", ")", "return", "self", ".", "app", ".", "addons", "[", "name", "]" ]
Upgrades an addon to the given tier.
[ "Upgrades", "an", "addon", "to", "the", "given", "tier", "." ]
cadc0a074896cf29c65a457c5c5bdb2069470af0
https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/models.py#L153-L166
train
heroku/heroku.py
heroku/models.py
App.new
def new(self, name=None, stack='cedar', region=None): """Creates a new app.""" payload = {} if name: payload['app[name]'] = name if stack: payload['app[stack]'] = stack if region: payload['app[region]'] = region r = self._h._http_resource( method='POST', resource=('apps',), data=payload ) name = json.loads(r.content).get('name') return self._h.apps.get(name)
python
def new(self, name=None, stack='cedar', region=None): """Creates a new app.""" payload = {} if name: payload['app[name]'] = name if stack: payload['app[stack]'] = stack if region: payload['app[region]'] = region r = self._h._http_resource( method='POST', resource=('apps',), data=payload ) name = json.loads(r.content).get('name') return self._h.apps.get(name)
[ "def", "new", "(", "self", ",", "name", "=", "None", ",", "stack", "=", "'cedar'", ",", "region", "=", "None", ")", ":", "payload", "=", "{", "}", "if", "name", ":", "payload", "[", "'app[name]'", "]", "=", "name", "if", "stack", ":", "payload", "[", "'app[stack]'", "]", "=", "stack", "if", "region", ":", "payload", "[", "'app[region]'", "]", "=", "region", "r", "=", "self", ".", "_h", ".", "_http_resource", "(", "method", "=", "'POST'", ",", "resource", "=", "(", "'apps'", ",", ")", ",", "data", "=", "payload", ")", "name", "=", "json", ".", "loads", "(", "r", ".", "content", ")", ".", "get", "(", "'name'", ")", "return", "self", ".", "_h", ".", "apps", ".", "get", "(", "name", ")" ]
Creates a new app.
[ "Creates", "a", "new", "app", "." ]
cadc0a074896cf29c65a457c5c5bdb2069470af0
https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/models.py#L183-L204
train
heroku/heroku.py
heroku/models.py
App.collaborators
def collaborators(self): """The collaborators for this app.""" return self._h._get_resources( resource=('apps', self.name, 'collaborators'), obj=Collaborator, app=self )
python
def collaborators(self): """The collaborators for this app.""" return self._h._get_resources( resource=('apps', self.name, 'collaborators'), obj=Collaborator, app=self )
[ "def", "collaborators", "(", "self", ")", ":", "return", "self", ".", "_h", ".", "_get_resources", "(", "resource", "=", "(", "'apps'", ",", "self", ".", "name", ",", "'collaborators'", ")", ",", "obj", "=", "Collaborator", ",", "app", "=", "self", ")" ]
The collaborators for this app.
[ "The", "collaborators", "for", "this", "app", "." ]
cadc0a074896cf29c65a457c5c5bdb2069470af0
https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/models.py#L214-L219
train
heroku/heroku.py
heroku/models.py
App.domains
def domains(self): """The domains for this app.""" return self._h._get_resources( resource=('apps', self.name, 'domains'), obj=Domain, app=self )
python
def domains(self): """The domains for this app.""" return self._h._get_resources( resource=('apps', self.name, 'domains'), obj=Domain, app=self )
[ "def", "domains", "(", "self", ")", ":", "return", "self", ".", "_h", ".", "_get_resources", "(", "resource", "=", "(", "'apps'", ",", "self", ".", "name", ",", "'domains'", ")", ",", "obj", "=", "Domain", ",", "app", "=", "self", ")" ]
The domains for this app.
[ "The", "domains", "for", "this", "app", "." ]
cadc0a074896cf29c65a457c5c5bdb2069470af0
https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/models.py#L222-L227
train
heroku/heroku.py
heroku/models.py
App.releases
def releases(self): """The releases for this app.""" return self._h._get_resources( resource=('apps', self.name, 'releases'), obj=Release, app=self )
python
def releases(self): """The releases for this app.""" return self._h._get_resources( resource=('apps', self.name, 'releases'), obj=Release, app=self )
[ "def", "releases", "(", "self", ")", ":", "return", "self", ".", "_h", ".", "_get_resources", "(", "resource", "=", "(", "'apps'", ",", "self", ".", "name", ",", "'releases'", ")", ",", "obj", "=", "Release", ",", "app", "=", "self", ")" ]
The releases for this app.
[ "The", "releases", "for", "this", "app", "." ]
cadc0a074896cf29c65a457c5c5bdb2069470af0
https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/models.py#L230-L235
train
heroku/heroku.py
heroku/models.py
App.processes
def processes(self): """The proccesses for this app.""" return self._h._get_resources( resource=('apps', self.name, 'ps'), obj=Process, app=self, map=ProcessListResource )
python
def processes(self): """The proccesses for this app.""" return self._h._get_resources( resource=('apps', self.name, 'ps'), obj=Process, app=self, map=ProcessListResource )
[ "def", "processes", "(", "self", ")", ":", "return", "self", ".", "_h", ".", "_get_resources", "(", "resource", "=", "(", "'apps'", ",", "self", ".", "name", ",", "'ps'", ")", ",", "obj", "=", "Process", ",", "app", "=", "self", ",", "map", "=", "ProcessListResource", ")" ]
The proccesses for this app.
[ "The", "proccesses", "for", "this", "app", "." ]
cadc0a074896cf29c65a457c5c5bdb2069470af0
https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/models.py#L238-L243
train
heroku/heroku.py
heroku/models.py
App.config
def config(self): """The envs for this app.""" return self._h._get_resource( resource=('apps', self.name, 'config_vars'), obj=ConfigVars, app=self )
python
def config(self): """The envs for this app.""" return self._h._get_resource( resource=('apps', self.name, 'config_vars'), obj=ConfigVars, app=self )
[ "def", "config", "(", "self", ")", ":", "return", "self", ".", "_h", ".", "_get_resource", "(", "resource", "=", "(", "'apps'", ",", "self", ".", "name", ",", "'config_vars'", ")", ",", "obj", "=", "ConfigVars", ",", "app", "=", "self", ")" ]
The envs for this app.
[ "The", "envs", "for", "this", "app", "." ]
cadc0a074896cf29c65a457c5c5bdb2069470af0
https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/models.py#L246-L252
train
heroku/heroku.py
heroku/models.py
App.info
def info(self): """Returns current info for this app.""" return self._h._get_resource( resource=('apps', self.name), obj=App, )
python
def info(self): """Returns current info for this app.""" return self._h._get_resource( resource=('apps', self.name), obj=App, )
[ "def", "info", "(", "self", ")", ":", "return", "self", ".", "_h", ".", "_get_resource", "(", "resource", "=", "(", "'apps'", ",", "self", ".", "name", ")", ",", "obj", "=", "App", ",", ")" ]
Returns current info for this app.
[ "Returns", "current", "info", "for", "this", "app", "." ]
cadc0a074896cf29c65a457c5c5bdb2069470af0
https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/models.py#L255-L261
train
heroku/heroku.py
heroku/models.py
App.rollback
def rollback(self, release): """Rolls back the release to the given version.""" r = self._h._http_resource( method='POST', resource=('apps', self.name, 'releases'), data={'rollback': release} ) return self.releases[-1]
python
def rollback(self, release): """Rolls back the release to the given version.""" r = self._h._http_resource( method='POST', resource=('apps', self.name, 'releases'), data={'rollback': release} ) return self.releases[-1]
[ "def", "rollback", "(", "self", ",", "release", ")", ":", "r", "=", "self", ".", "_h", ".", "_http_resource", "(", "method", "=", "'POST'", ",", "resource", "=", "(", "'apps'", ",", "self", ".", "name", ",", "'releases'", ")", ",", "data", "=", "{", "'rollback'", ":", "release", "}", ")", "return", "self", ".", "releases", "[", "-", "1", "]" ]
Rolls back the release to the given version.
[ "Rolls", "back", "the", "release", "to", "the", "given", "version", "." ]
cadc0a074896cf29c65a457c5c5bdb2069470af0
https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/models.py#L270-L277
train
heroku/heroku.py
heroku/models.py
App.rename
def rename(self, name): """Renames app to given name.""" r = self._h._http_resource( method='PUT', resource=('apps', self.name), data={'app[name]': name} ) return r.ok
python
def rename(self, name): """Renames app to given name.""" r = self._h._http_resource( method='PUT', resource=('apps', self.name), data={'app[name]': name} ) return r.ok
[ "def", "rename", "(", "self", ",", "name", ")", ":", "r", "=", "self", ".", "_h", ".", "_http_resource", "(", "method", "=", "'PUT'", ",", "resource", "=", "(", "'apps'", ",", "self", ".", "name", ")", ",", "data", "=", "{", "'app[name]'", ":", "name", "}", ")", "return", "r", ".", "ok" ]
Renames app to given name.
[ "Renames", "app", "to", "given", "name", "." ]
cadc0a074896cf29c65a457c5c5bdb2069470af0
https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/models.py#L280-L288
train
heroku/heroku.py
heroku/models.py
App.transfer
def transfer(self, user): """Transfers app to given username's account.""" r = self._h._http_resource( method='PUT', resource=('apps', self.name), data={'app[transfer_owner]': user} ) return r.ok
python
def transfer(self, user): """Transfers app to given username's account.""" r = self._h._http_resource( method='PUT', resource=('apps', self.name), data={'app[transfer_owner]': user} ) return r.ok
[ "def", "transfer", "(", "self", ",", "user", ")", ":", "r", "=", "self", ".", "_h", ".", "_http_resource", "(", "method", "=", "'PUT'", ",", "resource", "=", "(", "'apps'", ",", "self", ".", "name", ")", ",", "data", "=", "{", "'app[transfer_owner]'", ":", "user", "}", ")", "return", "r", ".", "ok" ]
Transfers app to given username's account.
[ "Transfers", "app", "to", "given", "username", "s", "account", "." ]
cadc0a074896cf29c65a457c5c5bdb2069470af0
https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/models.py#L290-L298
train
heroku/heroku.py
heroku/models.py
App.maintenance
def maintenance(self, on=True): """Toggles maintenance mode.""" r = self._h._http_resource( method='POST', resource=('apps', self.name, 'server', 'maintenance'), data={'maintenance_mode': int(on)} ) return r.ok
python
def maintenance(self, on=True): """Toggles maintenance mode.""" r = self._h._http_resource( method='POST', resource=('apps', self.name, 'server', 'maintenance'), data={'maintenance_mode': int(on)} ) return r.ok
[ "def", "maintenance", "(", "self", ",", "on", "=", "True", ")", ":", "r", "=", "self", ".", "_h", ".", "_http_resource", "(", "method", "=", "'POST'", ",", "resource", "=", "(", "'apps'", ",", "self", ".", "name", ",", "'server'", ",", "'maintenance'", ")", ",", "data", "=", "{", "'maintenance_mode'", ":", "int", "(", "on", ")", "}", ")", "return", "r", ".", "ok" ]
Toggles maintenance mode.
[ "Toggles", "maintenance", "mode", "." ]
cadc0a074896cf29c65a457c5c5bdb2069470af0
https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/models.py#L300-L308
train
heroku/heroku.py
heroku/models.py
App.destroy
def destroy(self): """Destoys the app. Do be careful.""" r = self._h._http_resource( method='DELETE', resource=('apps', self.name) ) return r.ok
python
def destroy(self): """Destoys the app. Do be careful.""" r = self._h._http_resource( method='DELETE', resource=('apps', self.name) ) return r.ok
[ "def", "destroy", "(", "self", ")", ":", "r", "=", "self", ".", "_h", ".", "_http_resource", "(", "method", "=", "'DELETE'", ",", "resource", "=", "(", "'apps'", ",", "self", ".", "name", ")", ")", "return", "r", ".", "ok" ]
Destoys the app. Do be careful.
[ "Destoys", "the", "app", ".", "Do", "be", "careful", "." ]
cadc0a074896cf29c65a457c5c5bdb2069470af0
https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/models.py#L310-L317
train
heroku/heroku.py
heroku/models.py
App.logs
def logs(self, num=None, source=None, ps=None, tail=False): """Returns the requested log.""" # Bootstrap payload package. payload = {'logplex': 'true'} if num: payload['num'] = num if source: payload['source'] = source if ps: payload['ps'] = ps if tail: payload['tail'] = 1 # Grab the URL of the logplex endpoint. r = self._h._http_resource( method='GET', resource=('apps', self.name, 'logs'), data=payload ) # Grab the actual logs. r = requests.get(r.content.decode("utf-8"), verify=False, stream=True) if not tail: return r.content else: # Return line iterator for tail! return r.iter_lines()
python
def logs(self, num=None, source=None, ps=None, tail=False): """Returns the requested log.""" # Bootstrap payload package. payload = {'logplex': 'true'} if num: payload['num'] = num if source: payload['source'] = source if ps: payload['ps'] = ps if tail: payload['tail'] = 1 # Grab the URL of the logplex endpoint. r = self._h._http_resource( method='GET', resource=('apps', self.name, 'logs'), data=payload ) # Grab the actual logs. r = requests.get(r.content.decode("utf-8"), verify=False, stream=True) if not tail: return r.content else: # Return line iterator for tail! return r.iter_lines()
[ "def", "logs", "(", "self", ",", "num", "=", "None", ",", "source", "=", "None", ",", "ps", "=", "None", ",", "tail", "=", "False", ")", ":", "# Bootstrap payload package.", "payload", "=", "{", "'logplex'", ":", "'true'", "}", "if", "num", ":", "payload", "[", "'num'", "]", "=", "num", "if", "source", ":", "payload", "[", "'source'", "]", "=", "source", "if", "ps", ":", "payload", "[", "'ps'", "]", "=", "ps", "if", "tail", ":", "payload", "[", "'tail'", "]", "=", "1", "# Grab the URL of the logplex endpoint.", "r", "=", "self", ".", "_h", ".", "_http_resource", "(", "method", "=", "'GET'", ",", "resource", "=", "(", "'apps'", ",", "self", ".", "name", ",", "'logs'", ")", ",", "data", "=", "payload", ")", "# Grab the actual logs.", "r", "=", "requests", ".", "get", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ",", "verify", "=", "False", ",", "stream", "=", "True", ")", "if", "not", "tail", ":", "return", "r", ".", "content", "else", ":", "# Return line iterator for tail!", "return", "r", ".", "iter_lines", "(", ")" ]
Returns the requested log.
[ "Returns", "the", "requested", "log", "." ]
cadc0a074896cf29c65a457c5c5bdb2069470af0
https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/models.py#L319-L351
train
heroku/heroku.py
heroku/models.py
Key.delete
def delete(self): """Deletes the key.""" r = self._h._http_resource( method='DELETE', resource=('user', 'keys', self.id) ) r.raise_for_status()
python
def delete(self): """Deletes the key.""" r = self._h._http_resource( method='DELETE', resource=('user', 'keys', self.id) ) r.raise_for_status()
[ "def", "delete", "(", "self", ")", ":", "r", "=", "self", ".", "_h", ".", "_http_resource", "(", "method", "=", "'DELETE'", ",", "resource", "=", "(", "'user'", ",", "'keys'", ",", "self", ".", "id", ")", ")", "r", ".", "raise_for_status", "(", ")" ]
Deletes the key.
[ "Deletes", "the", "key", "." ]
cadc0a074896cf29c65a457c5c5bdb2069470af0
https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/models.py#L492-L499
train
heroku/heroku.py
heroku/models.py
Process.restart
def restart(self, all=False): """Restarts the given process.""" if all: data = {'type': self.type} else: data = {'ps': self.process} r = self._h._http_resource( method='POST', resource=('apps', self.app.name, 'ps', 'restart'), data=data ) r.raise_for_status()
python
def restart(self, all=False): """Restarts the given process.""" if all: data = {'type': self.type} else: data = {'ps': self.process} r = self._h._http_resource( method='POST', resource=('apps', self.app.name, 'ps', 'restart'), data=data ) r.raise_for_status()
[ "def", "restart", "(", "self", ",", "all", "=", "False", ")", ":", "if", "all", ":", "data", "=", "{", "'type'", ":", "self", ".", "type", "}", "else", ":", "data", "=", "{", "'ps'", ":", "self", ".", "process", "}", "r", "=", "self", ".", "_h", ".", "_http_resource", "(", "method", "=", "'POST'", ",", "resource", "=", "(", "'apps'", ",", "self", ".", "app", ".", "name", ",", "'ps'", ",", "'restart'", ")", ",", "data", "=", "data", ")", "r", ".", "raise_for_status", "(", ")" ]
Restarts the given process.
[ "Restarts", "the", "given", "process", "." ]
cadc0a074896cf29c65a457c5c5bdb2069470af0
https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/models.py#L547-L562
train
heroku/heroku.py
heroku/models.py
Process.scale
def scale(self, quantity): """Scales the given process to the given number of dynos.""" r = self._h._http_resource( method='POST', resource=('apps', self.app.name, 'ps', 'scale'), data={'type': self.type, 'qty': quantity} ) r.raise_for_status() try: return self.app.processes[self.type] except KeyError: return ProcessListResource()
python
def scale(self, quantity): """Scales the given process to the given number of dynos.""" r = self._h._http_resource( method='POST', resource=('apps', self.app.name, 'ps', 'scale'), data={'type': self.type, 'qty': quantity} ) r.raise_for_status() try: return self.app.processes[self.type] except KeyError: return ProcessListResource()
[ "def", "scale", "(", "self", ",", "quantity", ")", ":", "r", "=", "self", ".", "_h", ".", "_http_resource", "(", "method", "=", "'POST'", ",", "resource", "=", "(", "'apps'", ",", "self", ".", "app", ".", "name", ",", "'ps'", ",", "'scale'", ")", ",", "data", "=", "{", "'type'", ":", "self", ".", "type", ",", "'qty'", ":", "quantity", "}", ")", "r", ".", "raise_for_status", "(", ")", "try", ":", "return", "self", ".", "app", ".", "processes", "[", "self", ".", "type", "]", "except", "KeyError", ":", "return", "ProcessListResource", "(", ")" ]
Scales the given process to the given number of dynos.
[ "Scales", "the", "given", "process", "to", "the", "given", "number", "of", "dynos", "." ]
cadc0a074896cf29c65a457c5c5bdb2069470af0
https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/models.py#L581-L595
train
heroku/heroku.py
heroku/helpers.py
is_collection
def is_collection(obj): """Tests if an object is a collection.""" col = getattr(obj, '__getitem__', False) val = False if (not col) else True if isinstance(obj, basestring): val = False return val
python
def is_collection(obj): """Tests if an object is a collection.""" col = getattr(obj, '__getitem__', False) val = False if (not col) else True if isinstance(obj, basestring): val = False return val
[ "def", "is_collection", "(", "obj", ")", ":", "col", "=", "getattr", "(", "obj", ",", "'__getitem__'", ",", "False", ")", "val", "=", "False", "if", "(", "not", "col", ")", "else", "True", "if", "isinstance", "(", "obj", ",", "basestring", ")", ":", "val", "=", "False", "return", "val" ]
Tests if an object is a collection.
[ "Tests", "if", "an", "object", "is", "a", "collection", "." ]
cadc0a074896cf29c65a457c5c5bdb2069470af0
https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/helpers.py#L19-L28
train
heroku/heroku.py
heroku/helpers.py
to_python
def to_python(obj, in_dict, str_keys=None, date_keys=None, int_keys=None, object_map=None, bool_keys=None, dict_keys=None, **kwargs): """Extends a given object for API Consumption. :param obj: Object to extend. :param in_dict: Dict to extract data from. :param string_keys: List of in_dict keys that will be extracted as strings. :param date_keys: List of in_dict keys that will be extrad as datetimes. :param object_map: Dict of {key, obj} map, for nested object results. """ d = dict() if str_keys: for in_key in str_keys: d[in_key] = in_dict.get(in_key) if date_keys: for in_key in date_keys: in_date = in_dict.get(in_key) try: out_date = parse_datetime(in_date) except TypeError as e: raise e out_date = None d[in_key] = out_date if int_keys: for in_key in int_keys: if (in_dict is not None) and (in_dict.get(in_key) is not None): d[in_key] = int(in_dict.get(in_key)) if bool_keys: for in_key in bool_keys: if in_dict.get(in_key) is not None: d[in_key] = bool(in_dict.get(in_key)) if dict_keys: for in_key in dict_keys: if in_dict.get(in_key) is not None: d[in_key] = dict(in_dict.get(in_key)) if object_map: for (k, v) in object_map.items(): if in_dict.get(k): d[k] = v.new_from_dict(in_dict.get(k)) obj.__dict__.update(d) obj.__dict__.update(kwargs) # Save the dictionary, for write comparisons. # obj._cache = d # obj.__cache = in_dict return obj
python
def to_python(obj, in_dict, str_keys=None, date_keys=None, int_keys=None, object_map=None, bool_keys=None, dict_keys=None, **kwargs): """Extends a given object for API Consumption. :param obj: Object to extend. :param in_dict: Dict to extract data from. :param string_keys: List of in_dict keys that will be extracted as strings. :param date_keys: List of in_dict keys that will be extrad as datetimes. :param object_map: Dict of {key, obj} map, for nested object results. """ d = dict() if str_keys: for in_key in str_keys: d[in_key] = in_dict.get(in_key) if date_keys: for in_key in date_keys: in_date = in_dict.get(in_key) try: out_date = parse_datetime(in_date) except TypeError as e: raise e out_date = None d[in_key] = out_date if int_keys: for in_key in int_keys: if (in_dict is not None) and (in_dict.get(in_key) is not None): d[in_key] = int(in_dict.get(in_key)) if bool_keys: for in_key in bool_keys: if in_dict.get(in_key) is not None: d[in_key] = bool(in_dict.get(in_key)) if dict_keys: for in_key in dict_keys: if in_dict.get(in_key) is not None: d[in_key] = dict(in_dict.get(in_key)) if object_map: for (k, v) in object_map.items(): if in_dict.get(k): d[k] = v.new_from_dict(in_dict.get(k)) obj.__dict__.update(d) obj.__dict__.update(kwargs) # Save the dictionary, for write comparisons. # obj._cache = d # obj.__cache = in_dict return obj
[ "def", "to_python", "(", "obj", ",", "in_dict", ",", "str_keys", "=", "None", ",", "date_keys", "=", "None", ",", "int_keys", "=", "None", ",", "object_map", "=", "None", ",", "bool_keys", "=", "None", ",", "dict_keys", "=", "None", ",", "*", "*", "kwargs", ")", ":", "d", "=", "dict", "(", ")", "if", "str_keys", ":", "for", "in_key", "in", "str_keys", ":", "d", "[", "in_key", "]", "=", "in_dict", ".", "get", "(", "in_key", ")", "if", "date_keys", ":", "for", "in_key", "in", "date_keys", ":", "in_date", "=", "in_dict", ".", "get", "(", "in_key", ")", "try", ":", "out_date", "=", "parse_datetime", "(", "in_date", ")", "except", "TypeError", "as", "e", ":", "raise", "e", "out_date", "=", "None", "d", "[", "in_key", "]", "=", "out_date", "if", "int_keys", ":", "for", "in_key", "in", "int_keys", ":", "if", "(", "in_dict", "is", "not", "None", ")", "and", "(", "in_dict", ".", "get", "(", "in_key", ")", "is", "not", "None", ")", ":", "d", "[", "in_key", "]", "=", "int", "(", "in_dict", ".", "get", "(", "in_key", ")", ")", "if", "bool_keys", ":", "for", "in_key", "in", "bool_keys", ":", "if", "in_dict", ".", "get", "(", "in_key", ")", "is", "not", "None", ":", "d", "[", "in_key", "]", "=", "bool", "(", "in_dict", ".", "get", "(", "in_key", ")", ")", "if", "dict_keys", ":", "for", "in_key", "in", "dict_keys", ":", "if", "in_dict", ".", "get", "(", "in_key", ")", "is", "not", "None", ":", "d", "[", "in_key", "]", "=", "dict", "(", "in_dict", ".", "get", "(", "in_key", ")", ")", "if", "object_map", ":", "for", "(", "k", ",", "v", ")", "in", "object_map", ".", "items", "(", ")", ":", "if", "in_dict", ".", "get", "(", "k", ")", ":", "d", "[", "k", "]", "=", "v", ".", "new_from_dict", "(", "in_dict", ".", "get", "(", "k", ")", ")", "obj", ".", "__dict__", ".", "update", "(", "d", ")", "obj", ".", "__dict__", ".", "update", "(", "kwargs", ")", "# Save the dictionary, for write comparisons.", "# obj._cache = d", "# obj.__cache = in_dict", "return", "obj" ]
Extends a given object for API Consumption. :param obj: Object to extend. :param in_dict: Dict to extract data from. :param string_keys: List of in_dict keys that will be extracted as strings. :param date_keys: List of in_dict keys that will be extrad as datetimes. :param object_map: Dict of {key, obj} map, for nested object results.
[ "Extends", "a", "given", "object", "for", "API", "Consumption", "." ]
cadc0a074896cf29c65a457c5c5bdb2069470af0
https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/helpers.py#L33-L95
train
heroku/heroku.py
heroku/helpers.py
to_api
def to_api(in_dict, int_keys=None, date_keys=None, bool_keys=None): """Extends a given object for API Production.""" # Cast all int_keys to int() if int_keys: for in_key in int_keys: if (in_key in in_dict) and (in_dict.get(in_key, None) is not None): in_dict[in_key] = int(in_dict[in_key]) # Cast all date_keys to datetime.isoformat if date_keys: for in_key in date_keys: if (in_key in in_dict) and (in_dict.get(in_key, None) is not None): _from = in_dict[in_key] if isinstance(_from, basestring): dtime = parse_datetime(_from) elif isinstance(_from, datetime): dtime = _from in_dict[in_key] = dtime.isoformat() elif (in_key in in_dict) and in_dict.get(in_key, None) is None: del in_dict[in_key] # Remove all Nones for k, v in in_dict.items(): if v is None: del in_dict[k] return in_dict
python
def to_api(in_dict, int_keys=None, date_keys=None, bool_keys=None): """Extends a given object for API Production.""" # Cast all int_keys to int() if int_keys: for in_key in int_keys: if (in_key in in_dict) and (in_dict.get(in_key, None) is not None): in_dict[in_key] = int(in_dict[in_key]) # Cast all date_keys to datetime.isoformat if date_keys: for in_key in date_keys: if (in_key in in_dict) and (in_dict.get(in_key, None) is not None): _from = in_dict[in_key] if isinstance(_from, basestring): dtime = parse_datetime(_from) elif isinstance(_from, datetime): dtime = _from in_dict[in_key] = dtime.isoformat() elif (in_key in in_dict) and in_dict.get(in_key, None) is None: del in_dict[in_key] # Remove all Nones for k, v in in_dict.items(): if v is None: del in_dict[k] return in_dict
[ "def", "to_api", "(", "in_dict", ",", "int_keys", "=", "None", ",", "date_keys", "=", "None", ",", "bool_keys", "=", "None", ")", ":", "# Cast all int_keys to int()", "if", "int_keys", ":", "for", "in_key", "in", "int_keys", ":", "if", "(", "in_key", "in", "in_dict", ")", "and", "(", "in_dict", ".", "get", "(", "in_key", ",", "None", ")", "is", "not", "None", ")", ":", "in_dict", "[", "in_key", "]", "=", "int", "(", "in_dict", "[", "in_key", "]", ")", "# Cast all date_keys to datetime.isoformat", "if", "date_keys", ":", "for", "in_key", "in", "date_keys", ":", "if", "(", "in_key", "in", "in_dict", ")", "and", "(", "in_dict", ".", "get", "(", "in_key", ",", "None", ")", "is", "not", "None", ")", ":", "_from", "=", "in_dict", "[", "in_key", "]", "if", "isinstance", "(", "_from", ",", "basestring", ")", ":", "dtime", "=", "parse_datetime", "(", "_from", ")", "elif", "isinstance", "(", "_from", ",", "datetime", ")", ":", "dtime", "=", "_from", "in_dict", "[", "in_key", "]", "=", "dtime", ".", "isoformat", "(", ")", "elif", "(", "in_key", "in", "in_dict", ")", "and", "in_dict", ".", "get", "(", "in_key", ",", "None", ")", "is", "None", ":", "del", "in_dict", "[", "in_key", "]", "# Remove all Nones", "for", "k", ",", "v", "in", "in_dict", ".", "items", "(", ")", ":", "if", "v", "is", "None", ":", "del", "in_dict", "[", "k", "]", "return", "in_dict" ]
Extends a given object for API Production.
[ "Extends", "a", "given", "object", "for", "API", "Production", "." ]
cadc0a074896cf29c65a457c5c5bdb2069470af0
https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/helpers.py#L99-L131
train
heroku/heroku.py
heroku/structures.py
SSHKeyListResource.clear
def clear(self): """Removes all SSH keys from a user's system.""" r = self._h._http_resource( method='DELETE', resource=('user', 'keys'), ) return r.ok
python
def clear(self): """Removes all SSH keys from a user's system.""" r = self._h._http_resource( method='DELETE', resource=('user', 'keys'), ) return r.ok
[ "def", "clear", "(", "self", ")", ":", "r", "=", "self", ".", "_h", ".", "_http_resource", "(", "method", "=", "'DELETE'", ",", "resource", "=", "(", "'user'", ",", "'keys'", ")", ",", ")", "return", "r", ".", "ok" ]
Removes all SSH keys from a user's system.
[ "Removes", "all", "SSH", "keys", "from", "a", "user", "s", "system", "." ]
cadc0a074896cf29c65a457c5c5bdb2069470af0
https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/structures.py#L108-L116
train
heroku/heroku.py
heroku/api.py
HerokuCore.authenticate
def authenticate(self, api_key): """Logs user into Heroku with given api_key.""" self._api_key = api_key # Attach auth to session. self._session.auth = ('', self._api_key) return self._verify_api_key()
python
def authenticate(self, api_key): """Logs user into Heroku with given api_key.""" self._api_key = api_key # Attach auth to session. self._session.auth = ('', self._api_key) return self._verify_api_key()
[ "def", "authenticate", "(", "self", ",", "api_key", ")", ":", "self", ".", "_api_key", "=", "api_key", "# Attach auth to session.", "self", ".", "_session", ".", "auth", "=", "(", "''", ",", "self", ".", "_api_key", ")", "return", "self", ".", "_verify_api_key", "(", ")" ]
Logs user into Heroku with given api_key.
[ "Logs", "user", "into", "Heroku", "with", "given", "api_key", "." ]
cadc0a074896cf29c65a457c5c5bdb2069470af0
https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/api.py#L40-L47
train
heroku/heroku.py
heroku/api.py
HerokuCore._get_resource
def _get_resource(self, resource, obj, params=None, **kwargs): """Returns a mapped object from an HTTP resource.""" r = self._http_resource('GET', resource, params=params) item = self._resource_deserialize(r.content.decode("utf-8")) return obj.new_from_dict(item, h=self, **kwargs)
python
def _get_resource(self, resource, obj, params=None, **kwargs): """Returns a mapped object from an HTTP resource.""" r = self._http_resource('GET', resource, params=params) item = self._resource_deserialize(r.content.decode("utf-8")) return obj.new_from_dict(item, h=self, **kwargs)
[ "def", "_get_resource", "(", "self", ",", "resource", ",", "obj", ",", "params", "=", "None", ",", "*", "*", "kwargs", ")", ":", "r", "=", "self", ".", "_http_resource", "(", "'GET'", ",", "resource", ",", "params", "=", "params", ")", "item", "=", "self", ".", "_resource_deserialize", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", "return", "obj", ".", "new_from_dict", "(", "item", ",", "h", "=", "self", ",", "*", "*", "kwargs", ")" ]
Returns a mapped object from an HTTP resource.
[ "Returns", "a", "mapped", "object", "from", "an", "HTTP", "resource", "." ]
cadc0a074896cf29c65a457c5c5bdb2069470af0
https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/api.py#L110-L115
train
heroku/heroku.py
heroku/api.py
HerokuCore._get_resources
def _get_resources(self, resource, obj, params=None, map=None, **kwargs): """Returns a list of mapped objects from an HTTP resource.""" r = self._http_resource('GET', resource, params=params) d_items = self._resource_deserialize(r.content.decode("utf-8")) items = [obj.new_from_dict(item, h=self, **kwargs) for item in d_items] if map is None: map = KeyedListResource list_resource = map(items=items) list_resource._h = self list_resource._obj = obj list_resource._kwargs = kwargs return list_resource
python
def _get_resources(self, resource, obj, params=None, map=None, **kwargs): """Returns a list of mapped objects from an HTTP resource.""" r = self._http_resource('GET', resource, params=params) d_items = self._resource_deserialize(r.content.decode("utf-8")) items = [obj.new_from_dict(item, h=self, **kwargs) for item in d_items] if map is None: map = KeyedListResource list_resource = map(items=items) list_resource._h = self list_resource._obj = obj list_resource._kwargs = kwargs return list_resource
[ "def", "_get_resources", "(", "self", ",", "resource", ",", "obj", ",", "params", "=", "None", ",", "map", "=", "None", ",", "*", "*", "kwargs", ")", ":", "r", "=", "self", ".", "_http_resource", "(", "'GET'", ",", "resource", ",", "params", "=", "params", ")", "d_items", "=", "self", ".", "_resource_deserialize", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", "items", "=", "[", "obj", ".", "new_from_dict", "(", "item", ",", "h", "=", "self", ",", "*", "*", "kwargs", ")", "for", "item", "in", "d_items", "]", "if", "map", "is", "None", ":", "map", "=", "KeyedListResource", "list_resource", "=", "map", "(", "items", "=", "items", ")", "list_resource", ".", "_h", "=", "self", "list_resource", ".", "_obj", "=", "obj", "list_resource", ".", "_kwargs", "=", "kwargs", "return", "list_resource" ]
Returns a list of mapped objects from an HTTP resource.
[ "Returns", "a", "list", "of", "mapped", "objects", "from", "an", "HTTP", "resource", "." ]
cadc0a074896cf29c65a457c5c5bdb2069470af0
https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/api.py#L117-L132
train
heroku/heroku.py
heroku/core.py
from_key
def from_key(api_key, **kwargs): """Returns an authenticated Heroku instance, via API Key.""" h = Heroku(**kwargs) # Login. h.authenticate(api_key) return h
python
def from_key(api_key, **kwargs): """Returns an authenticated Heroku instance, via API Key.""" h = Heroku(**kwargs) # Login. h.authenticate(api_key) return h
[ "def", "from_key", "(", "api_key", ",", "*", "*", "kwargs", ")", ":", "h", "=", "Heroku", "(", "*", "*", "kwargs", ")", "# Login.", "h", ".", "authenticate", "(", "api_key", ")", "return", "h" ]
Returns an authenticated Heroku instance, via API Key.
[ "Returns", "an", "authenticated", "Heroku", "instance", "via", "API", "Key", "." ]
cadc0a074896cf29c65a457c5c5bdb2069470af0
https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/core.py#L12-L20
train
pyviz/param
param/version.py
OldDeprecatedVersion.abbrev
def abbrev(self,dev_suffix=""): """ Abbreviated string representation, optionally declaring whether it is a development version. """ return '.'.join(str(el) for el in self.release) + \ (dev_suffix if self.commit_count > 0 or self.dirty else "")
python
def abbrev(self,dev_suffix=""): """ Abbreviated string representation, optionally declaring whether it is a development version. """ return '.'.join(str(el) for el in self.release) + \ (dev_suffix if self.commit_count > 0 or self.dirty else "")
[ "def", "abbrev", "(", "self", ",", "dev_suffix", "=", "\"\"", ")", ":", "return", "'.'", ".", "join", "(", "str", "(", "el", ")", "for", "el", "in", "self", ".", "release", ")", "+", "(", "dev_suffix", "if", "self", ".", "commit_count", ">", "0", "or", "self", ".", "dirty", "else", "\"\"", ")" ]
Abbreviated string representation, optionally declaring whether it is a development version.
[ "Abbreviated", "string", "representation", "optionally", "declaring", "whether", "it", "is", "a", "development", "version", "." ]
8f0dafa78defa883247b40635f96cc6d5c1b3481
https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/version.py#L704-L710
train
pyviz/param
param/version.py
OldDeprecatedVersion.verify
def verify(self, string_version=None): """ Check that the version information is consistent with the VCS before doing a release. If supplied with a string version, this is also checked against the current version. Should be called from setup.py with the declared package version before releasing to PyPI. """ if string_version and string_version != str(self): raise Exception("Supplied string version does not match current version.") if self.dirty: raise Exception("Current working directory is dirty.") if self.release != self.expected_release: raise Exception("Declared release does not match current release tag.") if self.commit_count !=0: raise Exception("Please update the VCS version tag before release.") if self._expected_commit not in [None, "$Format:%h$"]: raise Exception("Declared release does not match the VCS version tag")
python
def verify(self, string_version=None): """ Check that the version information is consistent with the VCS before doing a release. If supplied with a string version, this is also checked against the current version. Should be called from setup.py with the declared package version before releasing to PyPI. """ if string_version and string_version != str(self): raise Exception("Supplied string version does not match current version.") if self.dirty: raise Exception("Current working directory is dirty.") if self.release != self.expected_release: raise Exception("Declared release does not match current release tag.") if self.commit_count !=0: raise Exception("Please update the VCS version tag before release.") if self._expected_commit not in [None, "$Format:%h$"]: raise Exception("Declared release does not match the VCS version tag")
[ "def", "verify", "(", "self", ",", "string_version", "=", "None", ")", ":", "if", "string_version", "and", "string_version", "!=", "str", "(", "self", ")", ":", "raise", "Exception", "(", "\"Supplied string version does not match current version.\"", ")", "if", "self", ".", "dirty", ":", "raise", "Exception", "(", "\"Current working directory is dirty.\"", ")", "if", "self", ".", "release", "!=", "self", ".", "expected_release", ":", "raise", "Exception", "(", "\"Declared release does not match current release tag.\"", ")", "if", "self", ".", "commit_count", "!=", "0", ":", "raise", "Exception", "(", "\"Please update the VCS version tag before release.\"", ")", "if", "self", ".", "_expected_commit", "not", "in", "[", "None", ",", "\"$Format:%h$\"", "]", ":", "raise", "Exception", "(", "\"Declared release does not match the VCS version tag\"", ")" ]
Check that the version information is consistent with the VCS before doing a release. If supplied with a string version, this is also checked against the current version. Should be called from setup.py with the declared package version before releasing to PyPI.
[ "Check", "that", "the", "version", "information", "is", "consistent", "with", "the", "VCS", "before", "doing", "a", "release", ".", "If", "supplied", "with", "a", "string", "version", "this", "is", "also", "checked", "against", "the", "current", "version", ".", "Should", "be", "called", "from", "setup", ".", "py", "with", "the", "declared", "package", "version", "before", "releasing", "to", "PyPI", "." ]
8f0dafa78defa883247b40635f96cc6d5c1b3481
https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/version.py#L743-L764
train
pyviz/param
numbergen/__init__.py
TimeAware._check_time_fn
def _check_time_fn(self, time_instance=False): """ If time_fn is the global time function supplied by param.Dynamic.time_fn, make sure Dynamic parameters are using this time function to control their behaviour. If time_instance is True, time_fn must be a param.Time instance. """ if time_instance and not isinstance(self.time_fn, param.Time): raise AssertionError("%s requires a Time object" % self.__class__.__name__) if self.time_dependent: global_timefn = self.time_fn is param.Dynamic.time_fn if global_timefn and not param.Dynamic.time_dependent: raise AssertionError("Cannot use Dynamic.time_fn as" " parameters are ignoring time.")
python
def _check_time_fn(self, time_instance=False): """ If time_fn is the global time function supplied by param.Dynamic.time_fn, make sure Dynamic parameters are using this time function to control their behaviour. If time_instance is True, time_fn must be a param.Time instance. """ if time_instance and not isinstance(self.time_fn, param.Time): raise AssertionError("%s requires a Time object" % self.__class__.__name__) if self.time_dependent: global_timefn = self.time_fn is param.Dynamic.time_fn if global_timefn and not param.Dynamic.time_dependent: raise AssertionError("Cannot use Dynamic.time_fn as" " parameters are ignoring time.")
[ "def", "_check_time_fn", "(", "self", ",", "time_instance", "=", "False", ")", ":", "if", "time_instance", "and", "not", "isinstance", "(", "self", ".", "time_fn", ",", "param", ".", "Time", ")", ":", "raise", "AssertionError", "(", "\"%s requires a Time object\"", "%", "self", ".", "__class__", ".", "__name__", ")", "if", "self", ".", "time_dependent", ":", "global_timefn", "=", "self", ".", "time_fn", "is", "param", ".", "Dynamic", ".", "time_fn", "if", "global_timefn", "and", "not", "param", ".", "Dynamic", ".", "time_dependent", ":", "raise", "AssertionError", "(", "\"Cannot use Dynamic.time_fn as\"", "\" parameters are ignoring time.\"", ")" ]
If time_fn is the global time function supplied by param.Dynamic.time_fn, make sure Dynamic parameters are using this time function to control their behaviour. If time_instance is True, time_fn must be a param.Time instance.
[ "If", "time_fn", "is", "the", "global", "time", "function", "supplied", "by", "param", ".", "Dynamic", ".", "time_fn", "make", "sure", "Dynamic", "parameters", "are", "using", "this", "time", "function", "to", "control", "their", "behaviour", "." ]
8f0dafa78defa883247b40635f96cc6d5c1b3481
https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/numbergen/__init__.py#L48-L64
train
pyviz/param
numbergen/__init__.py
Hash._rational
def _rational(self, val): """Convert the given value to a rational, if necessary.""" I32 = 4294967296 # Maximum 32 bit unsigned int (i.e. 'I') value if isinstance(val, int): numer, denom = val, 1 elif isinstance(val, fractions.Fraction): numer, denom = val.numerator, val.denominator elif hasattr(val, 'numer'): (numer, denom) = (int(val.numer()), int(val.denom())) else: param.main.param.warning("Casting type '%s' to Fraction.fraction" % type(val).__name__) frac = fractions.Fraction(str(val)) numer, denom = frac.numerator, frac.denominator return numer % I32, denom % I32
python
def _rational(self, val): """Convert the given value to a rational, if necessary.""" I32 = 4294967296 # Maximum 32 bit unsigned int (i.e. 'I') value if isinstance(val, int): numer, denom = val, 1 elif isinstance(val, fractions.Fraction): numer, denom = val.numerator, val.denominator elif hasattr(val, 'numer'): (numer, denom) = (int(val.numer()), int(val.denom())) else: param.main.param.warning("Casting type '%s' to Fraction.fraction" % type(val).__name__) frac = fractions.Fraction(str(val)) numer, denom = frac.numerator, frac.denominator return numer % I32, denom % I32
[ "def", "_rational", "(", "self", ",", "val", ")", ":", "I32", "=", "4294967296", "# Maximum 32 bit unsigned int (i.e. 'I') value", "if", "isinstance", "(", "val", ",", "int", ")", ":", "numer", ",", "denom", "=", "val", ",", "1", "elif", "isinstance", "(", "val", ",", "fractions", ".", "Fraction", ")", ":", "numer", ",", "denom", "=", "val", ".", "numerator", ",", "val", ".", "denominator", "elif", "hasattr", "(", "val", ",", "'numer'", ")", ":", "(", "numer", ",", "denom", ")", "=", "(", "int", "(", "val", ".", "numer", "(", ")", ")", ",", "int", "(", "val", ".", "denom", "(", ")", ")", ")", "else", ":", "param", ".", "main", ".", "param", ".", "warning", "(", "\"Casting type '%s' to Fraction.fraction\"", "%", "type", "(", "val", ")", ".", "__name__", ")", "frac", "=", "fractions", ".", "Fraction", "(", "str", "(", "val", ")", ")", "numer", ",", "denom", "=", "frac", ".", "numerator", ",", "frac", ".", "denominator", "return", "numer", "%", "I32", ",", "denom", "%", "I32" ]
Convert the given value to a rational, if necessary.
[ "Convert", "the", "given", "value", "to", "a", "rational", "if", "necessary", "." ]
8f0dafa78defa883247b40635f96cc6d5c1b3481
https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/numbergen/__init__.py#L200-L215
train
pyviz/param
numbergen/__init__.py
TimeAwareRandomState._initialize_random_state
def _initialize_random_state(self, seed=None, shared=True, name=None): """ Initialization method to be called in the constructor of subclasses to initialize the random state correctly. If seed is None, there is no control over the random stream (no reproducibility of the stream). If shared is True (and not time-dependent), the random state is shared across all objects of the given class. This can be overridden per object by creating new random state to assign to the random_generator parameter. """ if seed is None: # Equivalent to an uncontrolled seed. seed = random.Random().randint(0, 1000000) suffix = '' else: suffix = str(seed) # If time_dependent, independent state required: otherwise # time-dependent seeding (via hash) will affect shared # state. Note that if all objects have time_dependent=True # shared random state is safe and more memory efficient. if self.time_dependent or not shared: self.random_generator = type(self.random_generator)(seed) # Seed appropriately (if not shared) if not shared: self.random_generator.seed(seed) if name is None: self._verify_constrained_hash() hash_name = name if name else self.name if not shared: hash_name += suffix self._hashfn = Hash(hash_name, input_count=2) if self.time_dependent: self._hash_and_seed()
python
def _initialize_random_state(self, seed=None, shared=True, name=None): """ Initialization method to be called in the constructor of subclasses to initialize the random state correctly. If seed is None, there is no control over the random stream (no reproducibility of the stream). If shared is True (and not time-dependent), the random state is shared across all objects of the given class. This can be overridden per object by creating new random state to assign to the random_generator parameter. """ if seed is None: # Equivalent to an uncontrolled seed. seed = random.Random().randint(0, 1000000) suffix = '' else: suffix = str(seed) # If time_dependent, independent state required: otherwise # time-dependent seeding (via hash) will affect shared # state. Note that if all objects have time_dependent=True # shared random state is safe and more memory efficient. if self.time_dependent or not shared: self.random_generator = type(self.random_generator)(seed) # Seed appropriately (if not shared) if not shared: self.random_generator.seed(seed) if name is None: self._verify_constrained_hash() hash_name = name if name else self.name if not shared: hash_name += suffix self._hashfn = Hash(hash_name, input_count=2) if self.time_dependent: self._hash_and_seed()
[ "def", "_initialize_random_state", "(", "self", ",", "seed", "=", "None", ",", "shared", "=", "True", ",", "name", "=", "None", ")", ":", "if", "seed", "is", "None", ":", "# Equivalent to an uncontrolled seed.", "seed", "=", "random", ".", "Random", "(", ")", ".", "randint", "(", "0", ",", "1000000", ")", "suffix", "=", "''", "else", ":", "suffix", "=", "str", "(", "seed", ")", "# If time_dependent, independent state required: otherwise", "# time-dependent seeding (via hash) will affect shared", "# state. Note that if all objects have time_dependent=True", "# shared random state is safe and more memory efficient.", "if", "self", ".", "time_dependent", "or", "not", "shared", ":", "self", ".", "random_generator", "=", "type", "(", "self", ".", "random_generator", ")", "(", "seed", ")", "# Seed appropriately (if not shared)", "if", "not", "shared", ":", "self", ".", "random_generator", ".", "seed", "(", "seed", ")", "if", "name", "is", "None", ":", "self", ".", "_verify_constrained_hash", "(", ")", "hash_name", "=", "name", "if", "name", "else", "self", ".", "name", "if", "not", "shared", ":", "hash_name", "+=", "suffix", "self", ".", "_hashfn", "=", "Hash", "(", "hash_name", ",", "input_count", "=", "2", ")", "if", "self", ".", "time_dependent", ":", "self", ".", "_hash_and_seed", "(", ")" ]
Initialization method to be called in the constructor of subclasses to initialize the random state correctly. If seed is None, there is no control over the random stream (no reproducibility of the stream). If shared is True (and not time-dependent), the random state is shared across all objects of the given class. This can be overridden per object by creating new random state to assign to the random_generator parameter.
[ "Initialization", "method", "to", "be", "called", "in", "the", "constructor", "of", "subclasses", "to", "initialize", "the", "random", "state", "correctly", "." ]
8f0dafa78defa883247b40635f96cc6d5c1b3481
https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/numbergen/__init__.py#L300-L338
train
pyviz/param
numbergen/__init__.py
TimeAwareRandomState._verify_constrained_hash
def _verify_constrained_hash(self): """ Warn if the object name is not explicitly set. """ changed_params = dict(self.param.get_param_values(onlychanged=True)) if self.time_dependent and ('name' not in changed_params): self.param.warning("Default object name used to set the seed: " "random values conditional on object instantiation order.")
python
def _verify_constrained_hash(self): """ Warn if the object name is not explicitly set. """ changed_params = dict(self.param.get_param_values(onlychanged=True)) if self.time_dependent and ('name' not in changed_params): self.param.warning("Default object name used to set the seed: " "random values conditional on object instantiation order.")
[ "def", "_verify_constrained_hash", "(", "self", ")", ":", "changed_params", "=", "dict", "(", "self", ".", "param", ".", "get_param_values", "(", "onlychanged", "=", "True", ")", ")", "if", "self", ".", "time_dependent", "and", "(", "'name'", "not", "in", "changed_params", ")", ":", "self", ".", "param", ".", "warning", "(", "\"Default object name used to set the seed: \"", "\"random values conditional on object instantiation order.\"", ")" ]
Warn if the object name is not explicitly set.
[ "Warn", "if", "the", "object", "name", "is", "not", "explicitly", "set", "." ]
8f0dafa78defa883247b40635f96cc6d5c1b3481
https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/numbergen/__init__.py#L341-L348
train
pyviz/param
setup.py
get_setup_version
def get_setup_version(reponame): """Use autover to get up to date version.""" # importing self into setup.py is unorthodox, but param has no # required dependencies outside of python from param.version import Version return Version.setup_version(os.path.dirname(__file__),reponame,archive_commit="$Format:%h$")
python
def get_setup_version(reponame): """Use autover to get up to date version.""" # importing self into setup.py is unorthodox, but param has no # required dependencies outside of python from param.version import Version return Version.setup_version(os.path.dirname(__file__),reponame,archive_commit="$Format:%h$")
[ "def", "get_setup_version", "(", "reponame", ")", ":", "# importing self into setup.py is unorthodox, but param has no", "# required dependencies outside of python", "from", "param", ".", "version", "import", "Version", "return", "Version", ".", "setup_version", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "reponame", ",", "archive_commit", "=", "\"$Format:%h$\"", ")" ]
Use autover to get up to date version.
[ "Use", "autover", "to", "get", "up", "to", "date", "version", "." ]
8f0dafa78defa883247b40635f96cc6d5c1b3481
https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/setup.py#L8-L13
train
pyviz/param
param/ipython.py
ParamPager.get_param_info
def get_param_info(self, obj, include_super=True): """ Get the parameter dictionary, the list of modifed parameters and the dictionary or parameter values. If include_super is True, parameters are also collected from the super classes. """ params = dict(obj.param.objects('existing')) if isinstance(obj,type): changed = [] val_dict = dict((k,p.default) for (k,p) in params.items()) self_class = obj else: changed = [name for (name,_) in obj.param.get_param_values(onlychanged=True)] val_dict = dict(obj.param.get_param_values()) self_class = obj.__class__ if not include_super: params = dict((k,v) for (k,v) in params.items() if k in self_class.__dict__) params.pop('name') # Already displayed in the title. return (params, val_dict, changed)
python
def get_param_info(self, obj, include_super=True): """ Get the parameter dictionary, the list of modifed parameters and the dictionary or parameter values. If include_super is True, parameters are also collected from the super classes. """ params = dict(obj.param.objects('existing')) if isinstance(obj,type): changed = [] val_dict = dict((k,p.default) for (k,p) in params.items()) self_class = obj else: changed = [name for (name,_) in obj.param.get_param_values(onlychanged=True)] val_dict = dict(obj.param.get_param_values()) self_class = obj.__class__ if not include_super: params = dict((k,v) for (k,v) in params.items() if k in self_class.__dict__) params.pop('name') # Already displayed in the title. return (params, val_dict, changed)
[ "def", "get_param_info", "(", "self", ",", "obj", ",", "include_super", "=", "True", ")", ":", "params", "=", "dict", "(", "obj", ".", "param", ".", "objects", "(", "'existing'", ")", ")", "if", "isinstance", "(", "obj", ",", "type", ")", ":", "changed", "=", "[", "]", "val_dict", "=", "dict", "(", "(", "k", ",", "p", ".", "default", ")", "for", "(", "k", ",", "p", ")", "in", "params", ".", "items", "(", ")", ")", "self_class", "=", "obj", "else", ":", "changed", "=", "[", "name", "for", "(", "name", ",", "_", ")", "in", "obj", ".", "param", ".", "get_param_values", "(", "onlychanged", "=", "True", ")", "]", "val_dict", "=", "dict", "(", "obj", ".", "param", ".", "get_param_values", "(", ")", ")", "self_class", "=", "obj", ".", "__class__", "if", "not", "include_super", ":", "params", "=", "dict", "(", "(", "k", ",", "v", ")", "for", "(", "k", ",", "v", ")", "in", "params", ".", "items", "(", ")", "if", "k", "in", "self_class", ".", "__dict__", ")", "params", ".", "pop", "(", "'name'", ")", "# Already displayed in the title.", "return", "(", "params", ",", "val_dict", ",", "changed", ")" ]
Get the parameter dictionary, the list of modifed parameters and the dictionary or parameter values. If include_super is True, parameters are also collected from the super classes.
[ "Get", "the", "parameter", "dictionary", "the", "list", "of", "modifed", "parameters", "and", "the", "dictionary", "or", "parameter", "values", ".", "If", "include_super", "is", "True", "parameters", "are", "also", "collected", "from", "the", "super", "classes", "." ]
8f0dafa78defa883247b40635f96cc6d5c1b3481
https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/ipython.py#L55-L77
train
pyviz/param
param/ipython.py
ParamPager._build_table
def _build_table(self, info, order, max_col_len=40, only_changed=False): """ Collect the information about parameters needed to build a properly formatted table and then tabulate it. """ info_dict, bounds_dict = {}, {} (params, val_dict, changed) = info col_widths = dict((k,0) for k in order) for name, p in params.items(): if only_changed and not (name in changed): continue constant = 'C' if p.constant else 'V' readonly = 'RO' if p.readonly else 'RW' allow_None = ' AN' if hasattr(p, 'allow_None') and p.allow_None else '' mode = '%s %s%s' % (constant, readonly, allow_None) info_dict[name] = {'name': name, 'type':p.__class__.__name__, 'mode':mode} if hasattr(p, 'bounds'): lbound, ubound = (None,None) if p.bounds is None else p.bounds mark_lbound, mark_ubound = False, False # Use soft_bounds when bounds not defined. if hasattr(p, 'get_soft_bounds'): soft_lbound, soft_ubound = p.get_soft_bounds() if lbound is None and soft_lbound is not None: lbound = soft_lbound mark_lbound = True if ubound is None and soft_ubound is not None: ubound = soft_ubound mark_ubound = True if (lbound, ubound) != (None,None): bounds_dict[name] = (mark_lbound, mark_ubound) info_dict[name]['bounds'] = '(%s, %s)' % (lbound, ubound) value = repr(val_dict[name]) if len(value) > (max_col_len - 3): value = value[:max_col_len-3] + '...' info_dict[name]['value'] = value for col in info_dict[name]: max_width = max([col_widths[col], len(info_dict[name][col])]) col_widths[col] = max_width return self._tabulate(info_dict, col_widths, changed, order, bounds_dict)
python
def _build_table(self, info, order, max_col_len=40, only_changed=False): """ Collect the information about parameters needed to build a properly formatted table and then tabulate it. """ info_dict, bounds_dict = {}, {} (params, val_dict, changed) = info col_widths = dict((k,0) for k in order) for name, p in params.items(): if only_changed and not (name in changed): continue constant = 'C' if p.constant else 'V' readonly = 'RO' if p.readonly else 'RW' allow_None = ' AN' if hasattr(p, 'allow_None') and p.allow_None else '' mode = '%s %s%s' % (constant, readonly, allow_None) info_dict[name] = {'name': name, 'type':p.__class__.__name__, 'mode':mode} if hasattr(p, 'bounds'): lbound, ubound = (None,None) if p.bounds is None else p.bounds mark_lbound, mark_ubound = False, False # Use soft_bounds when bounds not defined. if hasattr(p, 'get_soft_bounds'): soft_lbound, soft_ubound = p.get_soft_bounds() if lbound is None and soft_lbound is not None: lbound = soft_lbound mark_lbound = True if ubound is None and soft_ubound is not None: ubound = soft_ubound mark_ubound = True if (lbound, ubound) != (None,None): bounds_dict[name] = (mark_lbound, mark_ubound) info_dict[name]['bounds'] = '(%s, %s)' % (lbound, ubound) value = repr(val_dict[name]) if len(value) > (max_col_len - 3): value = value[:max_col_len-3] + '...' info_dict[name]['value'] = value for col in info_dict[name]: max_width = max([col_widths[col], len(info_dict[name][col])]) col_widths[col] = max_width return self._tabulate(info_dict, col_widths, changed, order, bounds_dict)
[ "def", "_build_table", "(", "self", ",", "info", ",", "order", ",", "max_col_len", "=", "40", ",", "only_changed", "=", "False", ")", ":", "info_dict", ",", "bounds_dict", "=", "{", "}", ",", "{", "}", "(", "params", ",", "val_dict", ",", "changed", ")", "=", "info", "col_widths", "=", "dict", "(", "(", "k", ",", "0", ")", "for", "k", "in", "order", ")", "for", "name", ",", "p", "in", "params", ".", "items", "(", ")", ":", "if", "only_changed", "and", "not", "(", "name", "in", "changed", ")", ":", "continue", "constant", "=", "'C'", "if", "p", ".", "constant", "else", "'V'", "readonly", "=", "'RO'", "if", "p", ".", "readonly", "else", "'RW'", "allow_None", "=", "' AN'", "if", "hasattr", "(", "p", ",", "'allow_None'", ")", "and", "p", ".", "allow_None", "else", "''", "mode", "=", "'%s %s%s'", "%", "(", "constant", ",", "readonly", ",", "allow_None", ")", "info_dict", "[", "name", "]", "=", "{", "'name'", ":", "name", ",", "'type'", ":", "p", ".", "__class__", ".", "__name__", ",", "'mode'", ":", "mode", "}", "if", "hasattr", "(", "p", ",", "'bounds'", ")", ":", "lbound", ",", "ubound", "=", "(", "None", ",", "None", ")", "if", "p", ".", "bounds", "is", "None", "else", "p", ".", "bounds", "mark_lbound", ",", "mark_ubound", "=", "False", ",", "False", "# Use soft_bounds when bounds not defined.", "if", "hasattr", "(", "p", ",", "'get_soft_bounds'", ")", ":", "soft_lbound", ",", "soft_ubound", "=", "p", ".", "get_soft_bounds", "(", ")", "if", "lbound", "is", "None", "and", "soft_lbound", "is", "not", "None", ":", "lbound", "=", "soft_lbound", "mark_lbound", "=", "True", "if", "ubound", "is", "None", "and", "soft_ubound", "is", "not", "None", ":", "ubound", "=", "soft_ubound", "mark_ubound", "=", "True", "if", "(", "lbound", ",", "ubound", ")", "!=", "(", "None", ",", "None", ")", ":", "bounds_dict", "[", "name", "]", "=", "(", "mark_lbound", ",", "mark_ubound", ")", "info_dict", "[", "name", "]", "[", "'bounds'", "]", "=", "'(%s, %s)'", "%", "(", "lbound", ",", "ubound", ")", "value", "=", "repr", "(", "val_dict", "[", "name", "]", ")", "if", "len", "(", "value", ")", ">", "(", "max_col_len", "-", "3", ")", ":", "value", "=", "value", "[", ":", "max_col_len", "-", "3", "]", "+", "'...'", "info_dict", "[", "name", "]", "[", "'value'", "]", "=", "value", "for", "col", "in", "info_dict", "[", "name", "]", ":", "max_width", "=", "max", "(", "[", "col_widths", "[", "col", "]", ",", "len", "(", "info_dict", "[", "name", "]", "[", "col", "]", ")", "]", ")", "col_widths", "[", "col", "]", "=", "max_width", "return", "self", ".", "_tabulate", "(", "info_dict", ",", "col_widths", ",", "changed", ",", "order", ",", "bounds_dict", ")" ]
Collect the information about parameters needed to build a properly formatted table and then tabulate it.
[ "Collect", "the", "information", "about", "parameters", "needed", "to", "build", "a", "properly", "formatted", "table", "and", "then", "tabulate", "it", "." ]
8f0dafa78defa883247b40635f96cc6d5c1b3481
https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/ipython.py#L127-L176
train
pyviz/param
param/ipython.py
ParamPager._tabulate
def _tabulate(self, info_dict, col_widths, changed, order, bounds_dict): """ Returns the supplied information as a table suitable for printing or paging. info_dict: Dictionary of the parameters name, type and mode. col_widths: Dictionary of column widths in characters changed: List of parameters modified from their defaults. order: The order of the table columns bound_dict: Dictionary of appropriately formatted bounds """ contents, tail = [], [] column_set = set(k for row in info_dict.values() for k in row) columns = [col for col in order if col in column_set] title_row = [] # Generate the column headings for i, col in enumerate(columns): width = col_widths[col]+2 col = col.capitalize() formatted = col.ljust(width) if i == 0 else col.center(width) title_row.append(formatted) contents.append(blue % ''.join(title_row)+"\n") # Format the table rows for row in sorted(info_dict): row_list = [] info = info_dict[row] for i,col in enumerate(columns): width = col_widths[col]+2 val = info[col] if (col in info) else '' formatted = val.ljust(width) if i==0 else val.center(width) if col == 'bounds' and bounds_dict.get(row,False): (mark_lbound, mark_ubound) = bounds_dict[row] lval, uval = formatted.rsplit(',') lspace, lstr = lval.rsplit('(') ustr, uspace = uval.rsplit(')') lbound = lspace + '('+(cyan % lstr) if mark_lbound else lval ubound = (cyan % ustr)+')'+uspace if mark_ubound else uval formatted = "%s,%s" % (lbound, ubound) row_list.append(formatted) row_text = ''.join(row_list) if row in changed: row_text = red % row_text contents.append(row_text) return '\n'.join(contents+tail)
python
def _tabulate(self, info_dict, col_widths, changed, order, bounds_dict): """ Returns the supplied information as a table suitable for printing or paging. info_dict: Dictionary of the parameters name, type and mode. col_widths: Dictionary of column widths in characters changed: List of parameters modified from their defaults. order: The order of the table columns bound_dict: Dictionary of appropriately formatted bounds """ contents, tail = [], [] column_set = set(k for row in info_dict.values() for k in row) columns = [col for col in order if col in column_set] title_row = [] # Generate the column headings for i, col in enumerate(columns): width = col_widths[col]+2 col = col.capitalize() formatted = col.ljust(width) if i == 0 else col.center(width) title_row.append(formatted) contents.append(blue % ''.join(title_row)+"\n") # Format the table rows for row in sorted(info_dict): row_list = [] info = info_dict[row] for i,col in enumerate(columns): width = col_widths[col]+2 val = info[col] if (col in info) else '' formatted = val.ljust(width) if i==0 else val.center(width) if col == 'bounds' and bounds_dict.get(row,False): (mark_lbound, mark_ubound) = bounds_dict[row] lval, uval = formatted.rsplit(',') lspace, lstr = lval.rsplit('(') ustr, uspace = uval.rsplit(')') lbound = lspace + '('+(cyan % lstr) if mark_lbound else lval ubound = (cyan % ustr)+')'+uspace if mark_ubound else uval formatted = "%s,%s" % (lbound, ubound) row_list.append(formatted) row_text = ''.join(row_list) if row in changed: row_text = red % row_text contents.append(row_text) return '\n'.join(contents+tail)
[ "def", "_tabulate", "(", "self", ",", "info_dict", ",", "col_widths", ",", "changed", ",", "order", ",", "bounds_dict", ")", ":", "contents", ",", "tail", "=", "[", "]", ",", "[", "]", "column_set", "=", "set", "(", "k", "for", "row", "in", "info_dict", ".", "values", "(", ")", "for", "k", "in", "row", ")", "columns", "=", "[", "col", "for", "col", "in", "order", "if", "col", "in", "column_set", "]", "title_row", "=", "[", "]", "# Generate the column headings", "for", "i", ",", "col", "in", "enumerate", "(", "columns", ")", ":", "width", "=", "col_widths", "[", "col", "]", "+", "2", "col", "=", "col", ".", "capitalize", "(", ")", "formatted", "=", "col", ".", "ljust", "(", "width", ")", "if", "i", "==", "0", "else", "col", ".", "center", "(", "width", ")", "title_row", ".", "append", "(", "formatted", ")", "contents", ".", "append", "(", "blue", "%", "''", ".", "join", "(", "title_row", ")", "+", "\"\\n\"", ")", "# Format the table rows", "for", "row", "in", "sorted", "(", "info_dict", ")", ":", "row_list", "=", "[", "]", "info", "=", "info_dict", "[", "row", "]", "for", "i", ",", "col", "in", "enumerate", "(", "columns", ")", ":", "width", "=", "col_widths", "[", "col", "]", "+", "2", "val", "=", "info", "[", "col", "]", "if", "(", "col", "in", "info", ")", "else", "''", "formatted", "=", "val", ".", "ljust", "(", "width", ")", "if", "i", "==", "0", "else", "val", ".", "center", "(", "width", ")", "if", "col", "==", "'bounds'", "and", "bounds_dict", ".", "get", "(", "row", ",", "False", ")", ":", "(", "mark_lbound", ",", "mark_ubound", ")", "=", "bounds_dict", "[", "row", "]", "lval", ",", "uval", "=", "formatted", ".", "rsplit", "(", "','", ")", "lspace", ",", "lstr", "=", "lval", ".", "rsplit", "(", "'('", ")", "ustr", ",", "uspace", "=", "uval", ".", "rsplit", "(", "')'", ")", "lbound", "=", "lspace", "+", "'('", "+", "(", "cyan", "%", "lstr", ")", "if", "mark_lbound", "else", "lval", "ubound", "=", "(", "cyan", "%", "ustr", ")", "+", "')'", "+", "uspace", "if", "mark_ubound", "else", "uval", "formatted", "=", "\"%s,%s\"", "%", "(", "lbound", ",", "ubound", ")", "row_list", ".", "append", "(", "formatted", ")", "row_text", "=", "''", ".", "join", "(", "row_list", ")", "if", "row", "in", "changed", ":", "row_text", "=", "red", "%", "row_text", "contents", ".", "append", "(", "row_text", ")", "return", "'\\n'", ".", "join", "(", "contents", "+", "tail", ")" ]
Returns the supplied information as a table suitable for printing or paging. info_dict: Dictionary of the parameters name, type and mode. col_widths: Dictionary of column widths in characters changed: List of parameters modified from their defaults. order: The order of the table columns bound_dict: Dictionary of appropriately formatted bounds
[ "Returns", "the", "supplied", "information", "as", "a", "table", "suitable", "for", "printing", "or", "paging", "." ]
8f0dafa78defa883247b40635f96cc6d5c1b3481
https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/ipython.py#L179-L229
train
pyviz/param
param/__init__.py
is_ordered_dict
def is_ordered_dict(d): """ Predicate checking for ordered dictionaries. OrderedDict is always ordered, and vanilla Python dictionaries are ordered for Python 3.6+ """ py3_ordered_dicts = (sys.version_info.major == 3) and (sys.version_info.minor >= 6) vanilla_odicts = (sys.version_info.major > 3) or py3_ordered_dicts return isinstance(d, (OrderedDict))or (vanilla_odicts and isinstance(d, dict))
python
def is_ordered_dict(d): """ Predicate checking for ordered dictionaries. OrderedDict is always ordered, and vanilla Python dictionaries are ordered for Python 3.6+ """ py3_ordered_dicts = (sys.version_info.major == 3) and (sys.version_info.minor >= 6) vanilla_odicts = (sys.version_info.major > 3) or py3_ordered_dicts return isinstance(d, (OrderedDict))or (vanilla_odicts and isinstance(d, dict))
[ "def", "is_ordered_dict", "(", "d", ")", ":", "py3_ordered_dicts", "=", "(", "sys", ".", "version_info", ".", "major", "==", "3", ")", "and", "(", "sys", ".", "version_info", ".", "minor", ">=", "6", ")", "vanilla_odicts", "=", "(", "sys", ".", "version_info", ".", "major", ">", "3", ")", "or", "py3_ordered_dicts", "return", "isinstance", "(", "d", ",", "(", "OrderedDict", ")", ")", "or", "(", "vanilla_odicts", "and", "isinstance", "(", "d", ",", "dict", ")", ")" ]
Predicate checking for ordered dictionaries. OrderedDict is always ordered, and vanilla Python dictionaries are ordered for Python 3.6+
[ "Predicate", "checking", "for", "ordered", "dictionaries", ".", "OrderedDict", "is", "always", "ordered", "and", "vanilla", "Python", "dictionaries", "are", "ordered", "for", "Python", "3", ".", "6", "+" ]
8f0dafa78defa883247b40635f96cc6d5c1b3481
https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/__init__.py#L91-L98
train
pyviz/param
param/__init__.py
named_objs
def named_objs(objlist, namesdict=None): """ Given a list of objects, returns a dictionary mapping from string name for the object to the object itself. Accepts an optional name,obj dictionary, which will override any other name if that item is present in the dictionary. """ objs = OrderedDict() if namesdict is not None: objtoname = {hashable(v): k for k, v in namesdict.items()} for obj in objlist: if namesdict is not None and hashable(obj) in objtoname: k = objtoname[hashable(obj)] elif hasattr(obj, "name"): k = obj.name elif hasattr(obj, '__name__'): k = obj.__name__ else: k = as_unicode(obj) objs[k] = obj return objs
python
def named_objs(objlist, namesdict=None): """ Given a list of objects, returns a dictionary mapping from string name for the object to the object itself. Accepts an optional name,obj dictionary, which will override any other name if that item is present in the dictionary. """ objs = OrderedDict() if namesdict is not None: objtoname = {hashable(v): k for k, v in namesdict.items()} for obj in objlist: if namesdict is not None and hashable(obj) in objtoname: k = objtoname[hashable(obj)] elif hasattr(obj, "name"): k = obj.name elif hasattr(obj, '__name__'): k = obj.__name__ else: k = as_unicode(obj) objs[k] = obj return objs
[ "def", "named_objs", "(", "objlist", ",", "namesdict", "=", "None", ")", ":", "objs", "=", "OrderedDict", "(", ")", "if", "namesdict", "is", "not", "None", ":", "objtoname", "=", "{", "hashable", "(", "v", ")", ":", "k", "for", "k", ",", "v", "in", "namesdict", ".", "items", "(", ")", "}", "for", "obj", "in", "objlist", ":", "if", "namesdict", "is", "not", "None", "and", "hashable", "(", "obj", ")", "in", "objtoname", ":", "k", "=", "objtoname", "[", "hashable", "(", "obj", ")", "]", "elif", "hasattr", "(", "obj", ",", "\"name\"", ")", ":", "k", "=", "obj", ".", "name", "elif", "hasattr", "(", "obj", ",", "'__name__'", ")", ":", "k", "=", "obj", ".", "__name__", "else", ":", "k", "=", "as_unicode", "(", "obj", ")", "objs", "[", "k", "]", "=", "obj", "return", "objs" ]
Given a list of objects, returns a dictionary mapping from string name for the object to the object itself. Accepts an optional name,obj dictionary, which will override any other name if that item is present in the dictionary.
[ "Given", "a", "list", "of", "objects", "returns", "a", "dictionary", "mapping", "from", "string", "name", "for", "the", "object", "to", "the", "object", "itself", ".", "Accepts", "an", "optional", "name", "obj", "dictionary", "which", "will", "override", "any", "other", "name", "if", "that", "item", "is", "present", "in", "the", "dictionary", "." ]
8f0dafa78defa883247b40635f96cc6d5c1b3481
https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/__init__.py#L117-L139
train
pyviz/param
param/__init__.py
guess_param_types
def guess_param_types(**kwargs): """ Given a set of keyword literals, promote to the appropriate parameter type based on some simple heuristics. """ params = {} for k, v in kwargs.items(): kws = dict(default=v, constant=True) if isinstance(v, Parameter): params[k] = v elif isinstance(v, dt_types): params[k] = Date(**kws) elif isinstance(v, bool): params[k] = Boolean(**kws) elif isinstance(v, int): params[k] = Integer(**kws) elif isinstance(v, float): params[k] = Number(**kws) elif isinstance(v, str): params[k] = String(**kws) elif isinstance(v, dict): params[k] = Dict(**kws) elif isinstance(v, tuple): if all(_is_number(el) for el in v): params[k] = NumericTuple(**kws) elif all(isinstance(el. dt_types) for el in v) and len(v)==2: params[k] = DateRange(**kws) else: params[k] = Tuple(**kws) elif isinstance(v, list): params[k] = List(**kws) elif isinstance(v, np.ndarray): params[k] = Array(**kws) else: from pandas import DataFrame as pdDFrame from pandas import Series as pdSeries if isinstance(v, pdDFrame): params[k] = DataFrame(**kws) elif isinstance(v, pdSeries): params[k] = Series(**kws) else: params[k] = Parameter(**kws) return params
python
def guess_param_types(**kwargs): """ Given a set of keyword literals, promote to the appropriate parameter type based on some simple heuristics. """ params = {} for k, v in kwargs.items(): kws = dict(default=v, constant=True) if isinstance(v, Parameter): params[k] = v elif isinstance(v, dt_types): params[k] = Date(**kws) elif isinstance(v, bool): params[k] = Boolean(**kws) elif isinstance(v, int): params[k] = Integer(**kws) elif isinstance(v, float): params[k] = Number(**kws) elif isinstance(v, str): params[k] = String(**kws) elif isinstance(v, dict): params[k] = Dict(**kws) elif isinstance(v, tuple): if all(_is_number(el) for el in v): params[k] = NumericTuple(**kws) elif all(isinstance(el. dt_types) for el in v) and len(v)==2: params[k] = DateRange(**kws) else: params[k] = Tuple(**kws) elif isinstance(v, list): params[k] = List(**kws) elif isinstance(v, np.ndarray): params[k] = Array(**kws) else: from pandas import DataFrame as pdDFrame from pandas import Series as pdSeries if isinstance(v, pdDFrame): params[k] = DataFrame(**kws) elif isinstance(v, pdSeries): params[k] = Series(**kws) else: params[k] = Parameter(**kws) return params
[ "def", "guess_param_types", "(", "*", "*", "kwargs", ")", ":", "params", "=", "{", "}", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "kws", "=", "dict", "(", "default", "=", "v", ",", "constant", "=", "True", ")", "if", "isinstance", "(", "v", ",", "Parameter", ")", ":", "params", "[", "k", "]", "=", "v", "elif", "isinstance", "(", "v", ",", "dt_types", ")", ":", "params", "[", "k", "]", "=", "Date", "(", "*", "*", "kws", ")", "elif", "isinstance", "(", "v", ",", "bool", ")", ":", "params", "[", "k", "]", "=", "Boolean", "(", "*", "*", "kws", ")", "elif", "isinstance", "(", "v", ",", "int", ")", ":", "params", "[", "k", "]", "=", "Integer", "(", "*", "*", "kws", ")", "elif", "isinstance", "(", "v", ",", "float", ")", ":", "params", "[", "k", "]", "=", "Number", "(", "*", "*", "kws", ")", "elif", "isinstance", "(", "v", ",", "str", ")", ":", "params", "[", "k", "]", "=", "String", "(", "*", "*", "kws", ")", "elif", "isinstance", "(", "v", ",", "dict", ")", ":", "params", "[", "k", "]", "=", "Dict", "(", "*", "*", "kws", ")", "elif", "isinstance", "(", "v", ",", "tuple", ")", ":", "if", "all", "(", "_is_number", "(", "el", ")", "for", "el", "in", "v", ")", ":", "params", "[", "k", "]", "=", "NumericTuple", "(", "*", "*", "kws", ")", "elif", "all", "(", "isinstance", "(", "el", ".", "dt_types", ")", "for", "el", "in", "v", ")", "and", "len", "(", "v", ")", "==", "2", ":", "params", "[", "k", "]", "=", "DateRange", "(", "*", "*", "kws", ")", "else", ":", "params", "[", "k", "]", "=", "Tuple", "(", "*", "*", "kws", ")", "elif", "isinstance", "(", "v", ",", "list", ")", ":", "params", "[", "k", "]", "=", "List", "(", "*", "*", "kws", ")", "elif", "isinstance", "(", "v", ",", "np", ".", "ndarray", ")", ":", "params", "[", "k", "]", "=", "Array", "(", "*", "*", "kws", ")", "else", ":", "from", "pandas", "import", "DataFrame", "as", "pdDFrame", "from", "pandas", "import", "Series", "as", "pdSeries", "if", "isinstance", "(", "v", ",", "pdDFrame", ")", ":", "params", "[", "k", "]", "=", "DataFrame", "(", "*", "*", "kws", ")", "elif", "isinstance", "(", "v", ",", "pdSeries", ")", ":", "params", "[", "k", "]", "=", "Series", "(", "*", "*", "kws", ")", "else", ":", "params", "[", "k", "]", "=", "Parameter", "(", "*", "*", "kws", ")", "return", "params" ]
Given a set of keyword literals, promote to the appropriate parameter type based on some simple heuristics.
[ "Given", "a", "set", "of", "keyword", "literals", "promote", "to", "the", "appropriate", "parameter", "type", "based", "on", "some", "simple", "heuristics", "." ]
8f0dafa78defa883247b40635f96cc6d5c1b3481
https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/__init__.py#L164-L208
train
pyviz/param
param/__init__.py
guess_bounds
def guess_bounds(params, **overrides): """ Given a dictionary of Parameter instances, return a corresponding set of copies with the bounds appropriately set. If given a set of override keywords, use those numeric tuple bounds. """ guessed = {} for name, p in params.items(): new_param = copy.copy(p) if isinstance(p, (Integer, Number)): if name in overrides: minv,maxv = overrides[name] else: minv, maxv, _ = _get_min_max_value(None, None, value=p.default) new_param.bounds = (minv, maxv) guessed[name] = new_param return guessed
python
def guess_bounds(params, **overrides): """ Given a dictionary of Parameter instances, return a corresponding set of copies with the bounds appropriately set. If given a set of override keywords, use those numeric tuple bounds. """ guessed = {} for name, p in params.items(): new_param = copy.copy(p) if isinstance(p, (Integer, Number)): if name in overrides: minv,maxv = overrides[name] else: minv, maxv, _ = _get_min_max_value(None, None, value=p.default) new_param.bounds = (minv, maxv) guessed[name] = new_param return guessed
[ "def", "guess_bounds", "(", "params", ",", "*", "*", "overrides", ")", ":", "guessed", "=", "{", "}", "for", "name", ",", "p", "in", "params", ".", "items", "(", ")", ":", "new_param", "=", "copy", ".", "copy", "(", "p", ")", "if", "isinstance", "(", "p", ",", "(", "Integer", ",", "Number", ")", ")", ":", "if", "name", "in", "overrides", ":", "minv", ",", "maxv", "=", "overrides", "[", "name", "]", "else", ":", "minv", ",", "maxv", ",", "_", "=", "_get_min_max_value", "(", "None", ",", "None", ",", "value", "=", "p", ".", "default", ")", "new_param", ".", "bounds", "=", "(", "minv", ",", "maxv", ")", "guessed", "[", "name", "]", "=", "new_param", "return", "guessed" ]
Given a dictionary of Parameter instances, return a corresponding set of copies with the bounds appropriately set. If given a set of override keywords, use those numeric tuple bounds.
[ "Given", "a", "dictionary", "of", "Parameter", "instances", "return", "a", "corresponding", "set", "of", "copies", "with", "the", "bounds", "appropriately", "set", "." ]
8f0dafa78defa883247b40635f96cc6d5c1b3481
https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/__init__.py#L221-L239
train
pyviz/param
param/__init__.py
Dynamic._initialize_generator
def _initialize_generator(self,gen,obj=None): """ Add 'last time' and 'last value' attributes to the generator. """ # CEBALERT: use a dictionary to hold these things. if hasattr(obj,"_Dynamic_time_fn"): gen._Dynamic_time_fn = obj._Dynamic_time_fn gen._Dynamic_last = None # CEB: I'd use None for this, except can't compare a fixedpoint # number with None (e.g. 1>None but FixedPoint(1)>None can't be done) gen._Dynamic_time = -1 gen._saved_Dynamic_last = [] gen._saved_Dynamic_time = []
python
def _initialize_generator(self,gen,obj=None): """ Add 'last time' and 'last value' attributes to the generator. """ # CEBALERT: use a dictionary to hold these things. if hasattr(obj,"_Dynamic_time_fn"): gen._Dynamic_time_fn = obj._Dynamic_time_fn gen._Dynamic_last = None # CEB: I'd use None for this, except can't compare a fixedpoint # number with None (e.g. 1>None but FixedPoint(1)>None can't be done) gen._Dynamic_time = -1 gen._saved_Dynamic_last = [] gen._saved_Dynamic_time = []
[ "def", "_initialize_generator", "(", "self", ",", "gen", ",", "obj", "=", "None", ")", ":", "# CEBALERT: use a dictionary to hold these things.", "if", "hasattr", "(", "obj", ",", "\"_Dynamic_time_fn\"", ")", ":", "gen", ".", "_Dynamic_time_fn", "=", "obj", ".", "_Dynamic_time_fn", "gen", ".", "_Dynamic_last", "=", "None", "# CEB: I'd use None for this, except can't compare a fixedpoint", "# number with None (e.g. 1>None but FixedPoint(1)>None can't be done)", "gen", ".", "_Dynamic_time", "=", "-", "1", "gen", ".", "_saved_Dynamic_last", "=", "[", "]", "gen", ".", "_saved_Dynamic_time", "=", "[", "]" ]
Add 'last time' and 'last value' attributes to the generator.
[ "Add", "last", "time", "and", "last", "value", "attributes", "to", "the", "generator", "." ]
8f0dafa78defa883247b40635f96cc6d5c1b3481
https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/__init__.py#L576-L590
train
pyviz/param
param/__init__.py
Dynamic._produce_value
def _produce_value(self,gen,force=False): """ Return a value from gen. If there is no time_fn, then a new value will be returned (i.e. gen will be asked to produce a new value). If force is True, or the value of time_fn() is different from what it was was last time produce_value was called, a new value will be produced and returned. Otherwise, the last value gen produced will be returned. """ if hasattr(gen,"_Dynamic_time_fn"): time_fn = gen._Dynamic_time_fn else: time_fn = self.time_fn if (time_fn is None) or (not self.time_dependent): value = produce_value(gen) gen._Dynamic_last = value else: time = time_fn() if force or time!=gen._Dynamic_time: value = produce_value(gen) gen._Dynamic_last = value gen._Dynamic_time = time else: value = gen._Dynamic_last return value
python
def _produce_value(self,gen,force=False): """ Return a value from gen. If there is no time_fn, then a new value will be returned (i.e. gen will be asked to produce a new value). If force is True, or the value of time_fn() is different from what it was was last time produce_value was called, a new value will be produced and returned. Otherwise, the last value gen produced will be returned. """ if hasattr(gen,"_Dynamic_time_fn"): time_fn = gen._Dynamic_time_fn else: time_fn = self.time_fn if (time_fn is None) or (not self.time_dependent): value = produce_value(gen) gen._Dynamic_last = value else: time = time_fn() if force or time!=gen._Dynamic_time: value = produce_value(gen) gen._Dynamic_last = value gen._Dynamic_time = time else: value = gen._Dynamic_last return value
[ "def", "_produce_value", "(", "self", ",", "gen", ",", "force", "=", "False", ")", ":", "if", "hasattr", "(", "gen", ",", "\"_Dynamic_time_fn\"", ")", ":", "time_fn", "=", "gen", ".", "_Dynamic_time_fn", "else", ":", "time_fn", "=", "self", ".", "time_fn", "if", "(", "time_fn", "is", "None", ")", "or", "(", "not", "self", ".", "time_dependent", ")", ":", "value", "=", "produce_value", "(", "gen", ")", "gen", ".", "_Dynamic_last", "=", "value", "else", ":", "time", "=", "time_fn", "(", ")", "if", "force", "or", "time", "!=", "gen", ".", "_Dynamic_time", ":", "value", "=", "produce_value", "(", "gen", ")", "gen", ".", "_Dynamic_last", "=", "value", "gen", ".", "_Dynamic_time", "=", "time", "else", ":", "value", "=", "gen", ".", "_Dynamic_last", "return", "value" ]
Return a value from gen. If there is no time_fn, then a new value will be returned (i.e. gen will be asked to produce a new value). If force is True, or the value of time_fn() is different from what it was was last time produce_value was called, a new value will be produced and returned. Otherwise, the last value gen produced will be returned.
[ "Return", "a", "value", "from", "gen", "." ]
8f0dafa78defa883247b40635f96cc6d5c1b3481
https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/__init__.py#L623-L655
train
pyviz/param
param/__init__.py
Dynamic._inspect
def _inspect(self,obj,objtype=None): """Return the last generated value for this parameter.""" gen=super(Dynamic,self).__get__(obj,objtype) if hasattr(gen,'_Dynamic_last'): return gen._Dynamic_last else: return gen
python
def _inspect(self,obj,objtype=None): """Return the last generated value for this parameter.""" gen=super(Dynamic,self).__get__(obj,objtype) if hasattr(gen,'_Dynamic_last'): return gen._Dynamic_last else: return gen
[ "def", "_inspect", "(", "self", ",", "obj", ",", "objtype", "=", "None", ")", ":", "gen", "=", "super", "(", "Dynamic", ",", "self", ")", ".", "__get__", "(", "obj", ",", "objtype", ")", "if", "hasattr", "(", "gen", ",", "'_Dynamic_last'", ")", ":", "return", "gen", ".", "_Dynamic_last", "else", ":", "return", "gen" ]
Return the last generated value for this parameter.
[ "Return", "the", "last", "generated", "value", "for", "this", "parameter", "." ]
8f0dafa78defa883247b40635f96cc6d5c1b3481
https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/__init__.py#L666-L673
train
pyviz/param
param/__init__.py
Dynamic._force
def _force(self,obj,objtype=None): """Force a new value to be generated, and return it.""" gen=super(Dynamic,self).__get__(obj,objtype) if hasattr(gen,'_Dynamic_last'): return self._produce_value(gen,force=True) else: return gen
python
def _force(self,obj,objtype=None): """Force a new value to be generated, and return it.""" gen=super(Dynamic,self).__get__(obj,objtype) if hasattr(gen,'_Dynamic_last'): return self._produce_value(gen,force=True) else: return gen
[ "def", "_force", "(", "self", ",", "obj", ",", "objtype", "=", "None", ")", ":", "gen", "=", "super", "(", "Dynamic", ",", "self", ")", ".", "__get__", "(", "obj", ",", "objtype", ")", "if", "hasattr", "(", "gen", ",", "'_Dynamic_last'", ")", ":", "return", "self", ".", "_produce_value", "(", "gen", ",", "force", "=", "True", ")", "else", ":", "return", "gen" ]
Force a new value to be generated, and return it.
[ "Force", "a", "new", "value", "to", "be", "generated", "and", "return", "it", "." ]
8f0dafa78defa883247b40635f96cc6d5c1b3481
https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/__init__.py#L676-L683
train
pyviz/param
param/__init__.py
Number.set_in_bounds
def set_in_bounds(self,obj,val): """ Set to the given value, but cropped to be within the legal bounds. All objects are accepted, and no exceptions will be raised. See crop_to_bounds for details on how cropping is done. """ if not callable(val): bounded_val = self.crop_to_bounds(val) else: bounded_val = val super(Number,self).__set__(obj,bounded_val)
python
def set_in_bounds(self,obj,val): """ Set to the given value, but cropped to be within the legal bounds. All objects are accepted, and no exceptions will be raised. See crop_to_bounds for details on how cropping is done. """ if not callable(val): bounded_val = self.crop_to_bounds(val) else: bounded_val = val super(Number,self).__set__(obj,bounded_val)
[ "def", "set_in_bounds", "(", "self", ",", "obj", ",", "val", ")", ":", "if", "not", "callable", "(", "val", ")", ":", "bounded_val", "=", "self", ".", "crop_to_bounds", "(", "val", ")", "else", ":", "bounded_val", "=", "val", "super", "(", "Number", ",", "self", ")", ".", "__set__", "(", "obj", ",", "bounded_val", ")" ]
Set to the given value, but cropped to be within the legal bounds. All objects are accepted, and no exceptions will be raised. See crop_to_bounds for details on how cropping is done.
[ "Set", "to", "the", "given", "value", "but", "cropped", "to", "be", "within", "the", "legal", "bounds", ".", "All", "objects", "are", "accepted", "and", "no", "exceptions", "will", "be", "raised", ".", "See", "crop_to_bounds", "for", "details", "on", "how", "cropping", "is", "done", "." ]
8f0dafa78defa883247b40635f96cc6d5c1b3481
https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/__init__.py#L786-L796
train
pyviz/param
param/__init__.py
Number.crop_to_bounds
def crop_to_bounds(self,val): """ Return the given value cropped to be within the hard bounds for this parameter. If a numeric value is passed in, check it is within the hard bounds. If it is larger than the high bound, return the high bound. If it's smaller, return the low bound. In either case, the returned value could be None. If a non-numeric value is passed in, set to be the default value (which could be None). In no case is an exception raised; all values are accepted. """ # Currently, values outside the bounds are silently cropped to # be inside the bounds; it may be appropriate to add a warning # in such cases. if _is_number(val): if self.bounds is None: return val vmin, vmax = self.bounds if vmin is not None: if val < vmin: return vmin if vmax is not None: if val > vmax: return vmax elif self.allow_None and val is None: return val else: # non-numeric value sent in: reverts to default value return self.default return val
python
def crop_to_bounds(self,val): """ Return the given value cropped to be within the hard bounds for this parameter. If a numeric value is passed in, check it is within the hard bounds. If it is larger than the high bound, return the high bound. If it's smaller, return the low bound. In either case, the returned value could be None. If a non-numeric value is passed in, set to be the default value (which could be None). In no case is an exception raised; all values are accepted. """ # Currently, values outside the bounds are silently cropped to # be inside the bounds; it may be appropriate to add a warning # in such cases. if _is_number(val): if self.bounds is None: return val vmin, vmax = self.bounds if vmin is not None: if val < vmin: return vmin if vmax is not None: if val > vmax: return vmax elif self.allow_None and val is None: return val else: # non-numeric value sent in: reverts to default value return self.default return val
[ "def", "crop_to_bounds", "(", "self", ",", "val", ")", ":", "# Currently, values outside the bounds are silently cropped to", "# be inside the bounds; it may be appropriate to add a warning", "# in such cases.", "if", "_is_number", "(", "val", ")", ":", "if", "self", ".", "bounds", "is", "None", ":", "return", "val", "vmin", ",", "vmax", "=", "self", ".", "bounds", "if", "vmin", "is", "not", "None", ":", "if", "val", "<", "vmin", ":", "return", "vmin", "if", "vmax", "is", "not", "None", ":", "if", "val", ">", "vmax", ":", "return", "vmax", "elif", "self", ".", "allow_None", "and", "val", "is", "None", ":", "return", "val", "else", ":", "# non-numeric value sent in: reverts to default value", "return", "self", ".", "default", "return", "val" ]
Return the given value cropped to be within the hard bounds for this parameter. If a numeric value is passed in, check it is within the hard bounds. If it is larger than the high bound, return the high bound. If it's smaller, return the low bound. In either case, the returned value could be None. If a non-numeric value is passed in, set to be the default value (which could be None). In no case is an exception raised; all values are accepted.
[ "Return", "the", "given", "value", "cropped", "to", "be", "within", "the", "hard", "bounds", "for", "this", "parameter", "." ]
8f0dafa78defa883247b40635f96cc6d5c1b3481
https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/__init__.py#L801-L835
train