id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
9,800
tcalmant/ipopo
pelix/ipopo/instance.py
StoredInstance.invalidate
def invalidate(self, callback=True): # type: (bool) -> bool """ Applies the component invalidation. :param callback: If True, call back the component before the invalidation :return: False if the component wasn't valid """ with self._lock: if self.state != StoredInstance.VALID: # Instance is not running... return False # Change the state self.state = StoredInstance.INVALID # Call the handlers self.__safe_handlers_callback("pre_invalidate") # Call the component if callback: # pylint: disable=W0212 self.__safe_validation_callback( constants.IPOPO_CALLBACK_INVALIDATE ) # Trigger an "Invalidated" event self._ipopo_service._fire_ipopo_event( constants.IPopoEvent.INVALIDATED, self.factory_name, self.name, ) # Call the handlers self.__safe_handlers_callback("post_invalidate") return True
python
def invalidate(self, callback=True): # type: (bool) -> bool with self._lock: if self.state != StoredInstance.VALID: # Instance is not running... return False # Change the state self.state = StoredInstance.INVALID # Call the handlers self.__safe_handlers_callback("pre_invalidate") # Call the component if callback: # pylint: disable=W0212 self.__safe_validation_callback( constants.IPOPO_CALLBACK_INVALIDATE ) # Trigger an "Invalidated" event self._ipopo_service._fire_ipopo_event( constants.IPopoEvent.INVALIDATED, self.factory_name, self.name, ) # Call the handlers self.__safe_handlers_callback("post_invalidate") return True
[ "def", "invalidate", "(", "self", ",", "callback", "=", "True", ")", ":", "# type: (bool) -> bool", "with", "self", ".", "_lock", ":", "if", "self", ".", "state", "!=", "StoredInstance", ".", "VALID", ":", "# Instance is not running...", "return", "False", "# ...
Applies the component invalidation. :param callback: If True, call back the component before the invalidation :return: False if the component wasn't valid
[ "Applies", "the", "component", "invalidation", "." ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L377-L413
9,801
tcalmant/ipopo
pelix/ipopo/instance.py
StoredInstance.validate
def validate(self, safe_callback=True): # type: (bool) -> bool """ Ends the component validation, registering services :param safe_callback: If True, calls the component validation callback :return: True if the component has been validated, else False :raise RuntimeError: You try to awake a dead component """ with self._lock: if self.state in ( StoredInstance.VALID, StoredInstance.VALIDATING, StoredInstance.ERRONEOUS, ): # No work to do (yet) return False if self.state == StoredInstance.KILLED: raise RuntimeError("{0}: Zombies !".format(self.name)) # Clear the error trace self.error_trace = None # Call the handlers self.__safe_handlers_callback("pre_validate") if safe_callback: # Safe call back needed and not yet passed self.state = StoredInstance.VALIDATING # Call @ValidateComponent first, then @Validate if not self.__safe_validation_callback( constants.IPOPO_CALLBACK_VALIDATE ): # Stop there if the callback failed self.state = StoredInstance.VALID self.invalidate(True) # Consider the component has erroneous self.state = StoredInstance.ERRONEOUS return False # All good self.state = StoredInstance.VALID # Call the handlers self.__safe_handlers_callback("post_validate") # We may have caused a framework error, so check if iPOPO is active if self._ipopo_service is not None: # pylint: disable=W0212 # Trigger the iPOPO event (after the service _registration) self._ipopo_service._fire_ipopo_event( constants.IPopoEvent.VALIDATED, self.factory_name, self.name ) return True
python
def validate(self, safe_callback=True): # type: (bool) -> bool with self._lock: if self.state in ( StoredInstance.VALID, StoredInstance.VALIDATING, StoredInstance.ERRONEOUS, ): # No work to do (yet) return False if self.state == StoredInstance.KILLED: raise RuntimeError("{0}: Zombies !".format(self.name)) # Clear the error trace self.error_trace = None # Call the handlers self.__safe_handlers_callback("pre_validate") if safe_callback: # Safe call back needed and not yet passed self.state = StoredInstance.VALIDATING # Call @ValidateComponent first, then @Validate if not self.__safe_validation_callback( constants.IPOPO_CALLBACK_VALIDATE ): # Stop there if the callback failed self.state = StoredInstance.VALID self.invalidate(True) # Consider the component has erroneous self.state = StoredInstance.ERRONEOUS return False # All good self.state = StoredInstance.VALID # Call the handlers self.__safe_handlers_callback("post_validate") # We may have caused a framework error, so check if iPOPO is active if self._ipopo_service is not None: # pylint: disable=W0212 # Trigger the iPOPO event (after the service _registration) self._ipopo_service._fire_ipopo_event( constants.IPopoEvent.VALIDATED, self.factory_name, self.name ) return True
[ "def", "validate", "(", "self", ",", "safe_callback", "=", "True", ")", ":", "# type: (bool) -> bool", "with", "self", ".", "_lock", ":", "if", "self", ".", "state", "in", "(", "StoredInstance", ".", "VALID", ",", "StoredInstance", ".", "VALIDATING", ",", ...
Ends the component validation, registering services :param safe_callback: If True, calls the component validation callback :return: True if the component has been validated, else False :raise RuntimeError: You try to awake a dead component
[ "Ends", "the", "component", "validation", "registering", "services" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L477-L533
9,802
tcalmant/ipopo
pelix/ipopo/instance.py
StoredInstance.__callback
def __callback(self, event, *args, **kwargs): # type: (str, *Any, **Any) -> Any """ Calls the registered method in the component for the given event :param event: An event (IPOPO_CALLBACK_VALIDATE, ...) :return: The callback result, or None :raise Exception: Something went wrong """ comp_callback = self.context.get_callback(event) if not comp_callback: # No registered callback return True # Call it result = comp_callback(self.instance, *args, **kwargs) if result is None: # Special case, if the call back returns nothing return True return result
python
def __callback(self, event, *args, **kwargs): # type: (str, *Any, **Any) -> Any comp_callback = self.context.get_callback(event) if not comp_callback: # No registered callback return True # Call it result = comp_callback(self.instance, *args, **kwargs) if result is None: # Special case, if the call back returns nothing return True return result
[ "def", "__callback", "(", "self", ",", "event", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# type: (str, *Any, **Any) -> Any", "comp_callback", "=", "self", ".", "context", ".", "get_callback", "(", "event", ")", "if", "not", "comp_callback", ":",...
Calls the registered method in the component for the given event :param event: An event (IPOPO_CALLBACK_VALIDATE, ...) :return: The callback result, or None :raise Exception: Something went wrong
[ "Calls", "the", "registered", "method", "in", "the", "component", "for", "the", "given", "event" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L535-L555
9,803
tcalmant/ipopo
pelix/ipopo/instance.py
StoredInstance.__field_callback
def __field_callback(self, field, event, *args, **kwargs): # type: (str, str, *Any, **Any) -> Any """ Calls the registered method in the component for the given field event :param field: A field name :param event: An event (IPOPO_CALLBACK_VALIDATE, ...) :return: The callback result, or None :raise Exception: Something went wrong """ # Get the field callback info cb_info = self.context.get_field_callback(field, event) if not cb_info: # No registered callback return True # Extract information callback, if_valid = cb_info if if_valid and self.state != StoredInstance.VALID: # Don't call the method if the component state isn't satisfying return True # Call it result = callback(self.instance, field, *args, **kwargs) if result is None: # Special case, if the call back returns nothing return True return result
python
def __field_callback(self, field, event, *args, **kwargs): # type: (str, str, *Any, **Any) -> Any # Get the field callback info cb_info = self.context.get_field_callback(field, event) if not cb_info: # No registered callback return True # Extract information callback, if_valid = cb_info if if_valid and self.state != StoredInstance.VALID: # Don't call the method if the component state isn't satisfying return True # Call it result = callback(self.instance, field, *args, **kwargs) if result is None: # Special case, if the call back returns nothing return True return result
[ "def", "__field_callback", "(", "self", ",", "field", ",", "event", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# type: (str, str, *Any, **Any) -> Any", "# Get the field callback info", "cb_info", "=", "self", ".", "context", ".", "get_field_callback", "...
Calls the registered method in the component for the given field event :param field: A field name :param event: An event (IPOPO_CALLBACK_VALIDATE, ...) :return: The callback result, or None :raise Exception: Something went wrong
[ "Calls", "the", "registered", "method", "in", "the", "component", "for", "the", "given", "field", "event" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L597-L626
9,804
tcalmant/ipopo
pelix/ipopo/instance.py
StoredInstance.safe_callback
def safe_callback(self, event, *args, **kwargs): # type: (str, *Any, **Any) -> Any """ Calls the registered method in the component for the given event, ignoring raised exceptions :param event: An event (IPOPO_CALLBACK_VALIDATE, ...) :return: The callback result, or None """ if self.state == StoredInstance.KILLED: # Invalid state return None try: return self.__callback(event, *args, **kwargs) except FrameworkException as ex: # Important error self._logger.exception( "Critical error calling back %s: %s", self.name, ex ) # Kill the component self._ipopo_service.kill(self.name) if ex.needs_stop: # Framework must be stopped... self._logger.error( "%s said that the Framework must be stopped.", self.name ) self.bundle_context.get_framework().stop() return False except: self._logger.exception( "Component '%s': error calling callback method for event %s", self.name, event, ) return False
python
def safe_callback(self, event, *args, **kwargs): # type: (str, *Any, **Any) -> Any if self.state == StoredInstance.KILLED: # Invalid state return None try: return self.__callback(event, *args, **kwargs) except FrameworkException as ex: # Important error self._logger.exception( "Critical error calling back %s: %s", self.name, ex ) # Kill the component self._ipopo_service.kill(self.name) if ex.needs_stop: # Framework must be stopped... self._logger.error( "%s said that the Framework must be stopped.", self.name ) self.bundle_context.get_framework().stop() return False except: self._logger.exception( "Component '%s': error calling callback method for event %s", self.name, event, ) return False
[ "def", "safe_callback", "(", "self", ",", "event", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# type: (str, *Any, **Any) -> Any", "if", "self", ".", "state", "==", "StoredInstance", ".", "KILLED", ":", "# Invalid state", "return", "None", "try", "...
Calls the registered method in the component for the given event, ignoring raised exceptions :param event: An event (IPOPO_CALLBACK_VALIDATE, ...) :return: The callback result, or None
[ "Calls", "the", "registered", "method", "in", "the", "component", "for", "the", "given", "event", "ignoring", "raised", "exceptions" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L628-L665
9,805
tcalmant/ipopo
pelix/ipopo/instance.py
StoredInstance.__safe_handler_callback
def __safe_handler_callback(self, handler, method_name, *args, **kwargs): # type: (Any, str, *Any, **Any) -> Any """ Calls the given method with the given arguments in the given handler. Logs exceptions, but doesn't propagate them. Special arguments can be given in kwargs: * 'none_as_true': If set to True and the method returned None or doesn't exist, the result is considered as True. If set to False, None result is kept as is. Default is False. * 'only_boolean': If True, the result can only be True or False, else the result is the value returned by the method. Default is False. :param handler: The handler to call :param method_name: The name of the method to call :param args: List of arguments for the method to call :param kwargs: Dictionary of arguments for the method to call and to control the call :return: The method result, or None on error """ if handler is None or method_name is None: return None # Behavior flags only_boolean = kwargs.pop("only_boolean", False) none_as_true = kwargs.pop("none_as_true", False) # Get the method for each handler try: method = getattr(handler, method_name) except AttributeError: # Method not found result = None else: try: # Call it result = method(*args, **kwargs) except Exception as ex: # No result result = None # Log error self._logger.exception( "Error calling handler '%s': %s", handler, ex ) if result is None and none_as_true: # Consider None (nothing returned) as True result = True if only_boolean: # Convert to a boolean result return bool(result) return result
python
def __safe_handler_callback(self, handler, method_name, *args, **kwargs): # type: (Any, str, *Any, **Any) -> Any if handler is None or method_name is None: return None # Behavior flags only_boolean = kwargs.pop("only_boolean", False) none_as_true = kwargs.pop("none_as_true", False) # Get the method for each handler try: method = getattr(handler, method_name) except AttributeError: # Method not found result = None else: try: # Call it result = method(*args, **kwargs) except Exception as ex: # No result result = None # Log error self._logger.exception( "Error calling handler '%s': %s", handler, ex ) if result is None and none_as_true: # Consider None (nothing returned) as True result = True if only_boolean: # Convert to a boolean result return bool(result) return result
[ "def", "__safe_handler_callback", "(", "self", ",", "handler", ",", "method_name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# type: (Any, str, *Any, **Any) -> Any", "if", "handler", "is", "None", "or", "method_name", "is", "None", ":", "return", "...
Calls the given method with the given arguments in the given handler. Logs exceptions, but doesn't propagate them. Special arguments can be given in kwargs: * 'none_as_true': If set to True and the method returned None or doesn't exist, the result is considered as True. If set to False, None result is kept as is. Default is False. * 'only_boolean': If True, the result can only be True or False, else the result is the value returned by the method. Default is False. :param handler: The handler to call :param method_name: The name of the method to call :param args: List of arguments for the method to call :param kwargs: Dictionary of arguments for the method to call and to control the call :return: The method result, or None on error
[ "Calls", "the", "given", "method", "with", "the", "given", "arguments", "in", "the", "given", "handler", ".", "Logs", "exceptions", "but", "doesn", "t", "propagate", "them", "." ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L753-L810
9,806
tcalmant/ipopo
pelix/ipopo/instance.py
StoredInstance.__safe_handlers_callback
def __safe_handlers_callback(self, method_name, *args, **kwargs): # type: (str, *Any, **Any) -> bool """ Calls the given method with the given arguments in all handlers. Logs exceptions, but doesn't propagate them. Methods called in handlers must return None, True or False. Special parameters can be given in kwargs: * 'exception_as_error': if it is set to True and an exception is raised by a handler, then this method will return False. By default, this flag is set to False and exceptions are ignored. * 'break_on_false': if it set to True, the loop calling the handler will stop after an handler returned False. By default, this flag is set to False, and all handlers are called. :param method_name: Name of the method to call :param args: List of arguments for the method to call :param kwargs: Dictionary of arguments for the method to call and the behavior of the call :return: True if all handlers returned True (or None), else False """ if self.state == StoredInstance.KILLED: # Nothing to do return False # Behavior flags exception_as_error = kwargs.pop("exception_as_error", False) break_on_false = kwargs.pop("break_on_false", False) result = True for handler in self.get_handlers(): # Get the method for each handler try: method = getattr(handler, method_name) except AttributeError: # Ignore missing methods pass else: try: # Call it res = method(*args, **kwargs) if res is not None and not res: # Ignore 'None' results result = False except Exception as ex: # Log errors self._logger.exception( "Error calling handler '%s': %s", handler, ex ) # We can consider exceptions as errors or ignore them result = result and not exception_as_error if not handler and break_on_false: # The loop can stop here break return result
python
def __safe_handlers_callback(self, method_name, *args, **kwargs): # type: (str, *Any, **Any) -> bool if self.state == StoredInstance.KILLED: # Nothing to do return False # Behavior flags exception_as_error = kwargs.pop("exception_as_error", False) break_on_false = kwargs.pop("break_on_false", False) result = True for handler in self.get_handlers(): # Get the method for each handler try: method = getattr(handler, method_name) except AttributeError: # Ignore missing methods pass else: try: # Call it res = method(*args, **kwargs) if res is not None and not res: # Ignore 'None' results result = False except Exception as ex: # Log errors self._logger.exception( "Error calling handler '%s': %s", handler, ex ) # We can consider exceptions as errors or ignore them result = result and not exception_as_error if not handler and break_on_false: # The loop can stop here break return result
[ "def", "__safe_handlers_callback", "(", "self", ",", "method_name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# type: (str, *Any, **Any) -> bool", "if", "self", ".", "state", "==", "StoredInstance", ".", "KILLED", ":", "# Nothing to do", "return", "F...
Calls the given method with the given arguments in all handlers. Logs exceptions, but doesn't propagate them. Methods called in handlers must return None, True or False. Special parameters can be given in kwargs: * 'exception_as_error': if it is set to True and an exception is raised by a handler, then this method will return False. By default, this flag is set to False and exceptions are ignored. * 'break_on_false': if it set to True, the loop calling the handler will stop after an handler returned False. By default, this flag is set to False, and all handlers are called. :param method_name: Name of the method to call :param args: List of arguments for the method to call :param kwargs: Dictionary of arguments for the method to call and the behavior of the call :return: True if all handlers returned True (or None), else False
[ "Calls", "the", "given", "method", "with", "the", "given", "arguments", "in", "all", "handlers", ".", "Logs", "exceptions", "but", "doesn", "t", "propagate", "them", ".", "Methods", "called", "in", "handlers", "must", "return", "None", "True", "or", "False",...
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L812-L870
9,807
tcalmant/ipopo
pelix/ipopo/instance.py
StoredInstance.__set_binding
def __set_binding(self, dependency, service, reference): # type: (Any, Any, ServiceReference) -> None """ Injects a service in the component :param dependency: The dependency handler :param service: The injected service :param reference: The reference of the injected service """ # Set the value setattr(self.instance, dependency.get_field(), dependency.get_value()) # Call the component back self.safe_callback(constants.IPOPO_CALLBACK_BIND, service, reference) self.__safe_field_callback( dependency.get_field(), constants.IPOPO_CALLBACK_BIND_FIELD, service, reference, )
python
def __set_binding(self, dependency, service, reference): # type: (Any, Any, ServiceReference) -> None # Set the value setattr(self.instance, dependency.get_field(), dependency.get_value()) # Call the component back self.safe_callback(constants.IPOPO_CALLBACK_BIND, service, reference) self.__safe_field_callback( dependency.get_field(), constants.IPOPO_CALLBACK_BIND_FIELD, service, reference, )
[ "def", "__set_binding", "(", "self", ",", "dependency", ",", "service", ",", "reference", ")", ":", "# type: (Any, Any, ServiceReference) -> None", "# Set the value", "setattr", "(", "self", ".", "instance", ",", "dependency", ".", "get_field", "(", ")", ",", "dep...
Injects a service in the component :param dependency: The dependency handler :param service: The injected service :param reference: The reference of the injected service
[ "Injects", "a", "service", "in", "the", "component" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L872-L892
9,808
tcalmant/ipopo
pelix/ipopo/instance.py
StoredInstance.__update_binding
def __update_binding( self, dependency, service, reference, old_properties, new_value ): # type: (Any, Any, ServiceReference, dict, bool) -> None """ Calls back component binding and field binding methods when the properties of an injected dependency have been updated. :param dependency: The dependency handler :param service: The injected service :param reference: The reference of the injected service :param old_properties: Previous properties of the dependency :param new_value: If True, inject the new value of the handler """ if new_value: # Set the value setattr( self.instance, dependency.get_field(), dependency.get_value() ) # Call the component back self.__safe_field_callback( dependency.get_field(), constants.IPOPO_CALLBACK_UPDATE_FIELD, service, reference, old_properties, ) self.safe_callback( constants.IPOPO_CALLBACK_UPDATE, service, reference, old_properties )
python
def __update_binding( self, dependency, service, reference, old_properties, new_value ): # type: (Any, Any, ServiceReference, dict, bool) -> None if new_value: # Set the value setattr( self.instance, dependency.get_field(), dependency.get_value() ) # Call the component back self.__safe_field_callback( dependency.get_field(), constants.IPOPO_CALLBACK_UPDATE_FIELD, service, reference, old_properties, ) self.safe_callback( constants.IPOPO_CALLBACK_UPDATE, service, reference, old_properties )
[ "def", "__update_binding", "(", "self", ",", "dependency", ",", "service", ",", "reference", ",", "old_properties", ",", "new_value", ")", ":", "# type: (Any, Any, ServiceReference, dict, bool) -> None", "if", "new_value", ":", "# Set the value", "setattr", "(", "self",...
Calls back component binding and field binding methods when the properties of an injected dependency have been updated. :param dependency: The dependency handler :param service: The injected service :param reference: The reference of the injected service :param old_properties: Previous properties of the dependency :param new_value: If True, inject the new value of the handler
[ "Calls", "back", "component", "binding", "and", "field", "binding", "methods", "when", "the", "properties", "of", "an", "injected", "dependency", "have", "been", "updated", "." ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L894-L925
9,809
tcalmant/ipopo
pelix/ipopo/instance.py
StoredInstance.__unset_binding
def __unset_binding(self, dependency, service, reference): # type: (Any, Any, ServiceReference) -> None """ Removes a service from the component :param dependency: The dependency handler :param service: The injected service :param reference: The reference of the injected service """ # Call the component back self.__safe_field_callback( dependency.get_field(), constants.IPOPO_CALLBACK_UNBIND_FIELD, service, reference, ) self.safe_callback(constants.IPOPO_CALLBACK_UNBIND, service, reference) # Update the injected field setattr(self.instance, dependency.get_field(), dependency.get_value()) # Unget the service self.bundle_context.unget_service(reference)
python
def __unset_binding(self, dependency, service, reference): # type: (Any, Any, ServiceReference) -> None # Call the component back self.__safe_field_callback( dependency.get_field(), constants.IPOPO_CALLBACK_UNBIND_FIELD, service, reference, ) self.safe_callback(constants.IPOPO_CALLBACK_UNBIND, service, reference) # Update the injected field setattr(self.instance, dependency.get_field(), dependency.get_value()) # Unget the service self.bundle_context.unget_service(reference)
[ "def", "__unset_binding", "(", "self", ",", "dependency", ",", "service", ",", "reference", ")", ":", "# type: (Any, Any, ServiceReference) -> None", "# Call the component back", "self", ".", "__safe_field_callback", "(", "dependency", ".", "get_field", "(", ")", ",", ...
Removes a service from the component :param dependency: The dependency handler :param service: The injected service :param reference: The reference of the injected service
[ "Removes", "a", "service", "from", "the", "component" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L927-L950
9,810
tcalmant/ipopo
pelix/misc/eventadmin_printer.py
_parse_boolean
def _parse_boolean(value): """ Returns a boolean value corresponding to the given value. :param value: Any value :return: Its boolean value """ if not value: return False try: # Lower string to check known "false" value value = value.lower() return value not in ("none", "0", "false", "no") except AttributeError: # Not a string, but has a value return True
python
def _parse_boolean(value): if not value: return False try: # Lower string to check known "false" value value = value.lower() return value not in ("none", "0", "false", "no") except AttributeError: # Not a string, but has a value return True
[ "def", "_parse_boolean", "(", "value", ")", ":", "if", "not", "value", ":", "return", "False", "try", ":", "# Lower string to check known \"false\" value", "value", "=", "value", ".", "lower", "(", ")", "return", "value", "not", "in", "(", "\"none\"", ",", "...
Returns a boolean value corresponding to the given value. :param value: Any value :return: Its boolean value
[ "Returns", "a", "boolean", "value", "corresponding", "to", "the", "given", "value", "." ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/eventadmin_printer.py#L58-L74
9,811
tcalmant/ipopo
pelix/ipopo/handlers/requiresvarfilter.py
_VariableFilterMixIn._find_keys
def _find_keys(self): """ Looks for the property keys in the filter string :return: A list of property keys """ formatter = string.Formatter() return [ val[1] for val in formatter.parse(self._original_filter) if val[1] ]
python
def _find_keys(self): formatter = string.Formatter() return [ val[1] for val in formatter.parse(self._original_filter) if val[1] ]
[ "def", "_find_keys", "(", "self", ")", ":", "formatter", "=", "string", ".", "Formatter", "(", ")", "return", "[", "val", "[", "1", "]", "for", "val", "in", "formatter", ".", "parse", "(", "self", ".", "_original_filter", ")", "if", "val", "[", "1", ...
Looks for the property keys in the filter string :return: A list of property keys
[ "Looks", "for", "the", "property", "keys", "in", "the", "filter", "string" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requiresvarfilter.py#L162-L171
9,812
tcalmant/ipopo
pelix/ipopo/handlers/requiresvarfilter.py
_VariableFilterMixIn.update_filter
def update_filter(self): """ Update the filter according to the new properties :return: True if the filter changed, else False :raise ValueError: The filter is invalid """ # Consider the filter invalid self.valid_filter = False try: # Format the new filter filter_str = self._original_filter.format( **self._component_context.properties ) except KeyError as ex: # An entry is missing: abandon logging.warning("Missing filter value: %s", ex) raise ValueError("Missing filter value") try: # Parse the new LDAP filter new_filter = ldapfilter.get_ldap_filter(filter_str) except (TypeError, ValueError) as ex: logging.warning("Error parsing filter: %s", ex) raise ValueError("Error parsing filter") # The filter is valid self.valid_filter = True # Compare to the "old" one if new_filter != self.requirement.filter: # Replace the requirement filter self.requirement.filter = new_filter return True # Same filter return False
python
def update_filter(self): # Consider the filter invalid self.valid_filter = False try: # Format the new filter filter_str = self._original_filter.format( **self._component_context.properties ) except KeyError as ex: # An entry is missing: abandon logging.warning("Missing filter value: %s", ex) raise ValueError("Missing filter value") try: # Parse the new LDAP filter new_filter = ldapfilter.get_ldap_filter(filter_str) except (TypeError, ValueError) as ex: logging.warning("Error parsing filter: %s", ex) raise ValueError("Error parsing filter") # The filter is valid self.valid_filter = True # Compare to the "old" one if new_filter != self.requirement.filter: # Replace the requirement filter self.requirement.filter = new_filter return True # Same filter return False
[ "def", "update_filter", "(", "self", ")", ":", "# Consider the filter invalid", "self", ".", "valid_filter", "=", "False", "try", ":", "# Format the new filter", "filter_str", "=", "self", ".", "_original_filter", ".", "format", "(", "*", "*", "self", ".", "_com...
Update the filter according to the new properties :return: True if the filter changed, else False :raise ValueError: The filter is invalid
[ "Update", "the", "filter", "according", "to", "the", "new", "properties" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requiresvarfilter.py#L173-L210
9,813
tcalmant/ipopo
pelix/ipopo/handlers/requiresvarfilter.py
_VariableFilterMixIn.on_property_change
def on_property_change(self, name, old_value, new_value): # pylint: disable=W0613 """ A component property has been updated :param name: Name of the property :param old_value: Previous value of the property :param new_value: New value of the property """ if name in self._keys: try: if self.update_filter(): # This is a key for the filter and the filter has changed # => Force the handler to update its dependency self._reset() except ValueError: # Invalid filter: clear all references, this will invalidate # the component for svc_ref in self.get_bindings(): self.on_service_departure(svc_ref)
python
def on_property_change(self, name, old_value, new_value): # pylint: disable=W0613 if name in self._keys: try: if self.update_filter(): # This is a key for the filter and the filter has changed # => Force the handler to update its dependency self._reset() except ValueError: # Invalid filter: clear all references, this will invalidate # the component for svc_ref in self.get_bindings(): self.on_service_departure(svc_ref)
[ "def", "on_property_change", "(", "self", ",", "name", ",", "old_value", ",", "new_value", ")", ":", "# pylint: disable=W0613", "if", "name", "in", "self", ".", "_keys", ":", "try", ":", "if", "self", ".", "update_filter", "(", ")", ":", "# This is a key for...
A component property has been updated :param name: Name of the property :param old_value: Previous value of the property :param new_value: New value of the property
[ "A", "component", "property", "has", "been", "updated" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requiresvarfilter.py#L212-L231
9,814
tcalmant/ipopo
pelix/ipopo/handlers/requiresvarfilter.py
_VariableFilterMixIn._reset
def _reset(self): """ Called when the filter has been changed """ with self._lock: # Start listening to services with the new filter self.stop() self.start() for svc_ref in self.get_bindings(): # Check if the current reference matches the filter if not self.requirement.filter.matches( svc_ref.get_properties() ): # Not the case: emulate a service departure # The instance life cycle will be updated as well self.on_service_departure(svc_ref)
python
def _reset(self): with self._lock: # Start listening to services with the new filter self.stop() self.start() for svc_ref in self.get_bindings(): # Check if the current reference matches the filter if not self.requirement.filter.matches( svc_ref.get_properties() ): # Not the case: emulate a service departure # The instance life cycle will be updated as well self.on_service_departure(svc_ref)
[ "def", "_reset", "(", "self", ")", ":", "with", "self", ".", "_lock", ":", "# Start listening to services with the new filter", "self", ".", "stop", "(", ")", "self", ".", "start", "(", ")", "for", "svc_ref", "in", "self", ".", "get_bindings", "(", ")", ":...
Called when the filter has been changed
[ "Called", "when", "the", "filter", "has", "been", "changed" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requiresvarfilter.py#L233-L249
9,815
tcalmant/ipopo
pelix/threadpool.py
EventData.set
def set(self, data=None): """ Sets the event """ self.__data = data self.__exception = None self.__event.set()
python
def set(self, data=None): self.__data = data self.__exception = None self.__event.set()
[ "def", "set", "(", "self", ",", "data", "=", "None", ")", ":", "self", ".", "__data", "=", "data", "self", ".", "__exception", "=", "None", "self", ".", "__event", ".", "set", "(", ")" ]
Sets the event
[ "Sets", "the", "event" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/threadpool.py#L97-L103
9,816
tcalmant/ipopo
pelix/threadpool.py
EventData.wait
def wait(self, timeout=None): """ Waits for the event or for the timeout :param timeout: Wait timeout (in seconds) :return: True if the event as been set, else False """ # The 'or' part is for Python 2.6 result = self.__event.wait(timeout) # pylint: disable=E0702 # Pylint seems to miss the "is None" check below if self.__exception is None: return result else: raise self.__exception
python
def wait(self, timeout=None): # The 'or' part is for Python 2.6 result = self.__event.wait(timeout) # pylint: disable=E0702 # Pylint seems to miss the "is None" check below if self.__exception is None: return result else: raise self.__exception
[ "def", "wait", "(", "self", ",", "timeout", "=", "None", ")", ":", "# The 'or' part is for Python 2.6", "result", "=", "self", ".", "__event", ".", "wait", "(", "timeout", ")", "# pylint: disable=E0702", "# Pylint seems to miss the \"is None\" check below", "if", "sel...
Waits for the event or for the timeout :param timeout: Wait timeout (in seconds) :return: True if the event as been set, else False
[ "Waits", "for", "the", "event", "or", "for", "the", "timeout" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/threadpool.py#L115-L129
9,817
tcalmant/ipopo
pelix/threadpool.py
FutureResult.__notify
def __notify(self): """ Notify the given callback about the result of the execution """ if self.__callback is not None: try: self.__callback( self._done_event.data, self._done_event.exception, self.__extra, ) except Exception as ex: self._logger.exception("Error calling back method: %s", ex)
python
def __notify(self): if self.__callback is not None: try: self.__callback( self._done_event.data, self._done_event.exception, self.__extra, ) except Exception as ex: self._logger.exception("Error calling back method: %s", ex)
[ "def", "__notify", "(", "self", ")", ":", "if", "self", ".", "__callback", "is", "not", "None", ":", "try", ":", "self", ".", "__callback", "(", "self", ".", "_done_event", ".", "data", ",", "self", ".", "_done_event", ".", "exception", ",", "self", ...
Notify the given callback about the result of the execution
[ "Notify", "the", "given", "callback", "about", "the", "result", "of", "the", "execution" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/threadpool.py#L153-L165
9,818
tcalmant/ipopo
pelix/threadpool.py
FutureResult.set_callback
def set_callback(self, method, extra=None): """ Sets a callback method, called once the result has been computed or in case of exception. The callback method must have the following signature: ``callback(result, exception, extra)``. :param method: The method to call back in the end of the execution :param extra: Extra parameter to be given to the callback method """ self.__callback = method self.__extra = extra if self._done_event.is_set(): # The execution has already finished self.__notify()
python
def set_callback(self, method, extra=None): self.__callback = method self.__extra = extra if self._done_event.is_set(): # The execution has already finished self.__notify()
[ "def", "set_callback", "(", "self", ",", "method", ",", "extra", "=", "None", ")", ":", "self", ".", "__callback", "=", "method", "self", ".", "__extra", "=", "extra", "if", "self", ".", "_done_event", ".", "is_set", "(", ")", ":", "# The execution has a...
Sets a callback method, called once the result has been computed or in case of exception. The callback method must have the following signature: ``callback(result, exception, extra)``. :param method: The method to call back in the end of the execution :param extra: Extra parameter to be given to the callback method
[ "Sets", "a", "callback", "method", "called", "once", "the", "result", "has", "been", "computed", "or", "in", "case", "of", "exception", "." ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/threadpool.py#L167-L182
9,819
tcalmant/ipopo
pelix/threadpool.py
ThreadPool.start
def start(self): """ Starts the thread pool. Does nothing if the pool is already started. """ if not self._done_event.is_set(): # Stop event not set: we're running return # Clear the stop event self._done_event.clear() # Compute the number of threads to start to handle pending tasks nb_pending_tasks = self._queue.qsize() if nb_pending_tasks > self._max_threads: nb_threads = self._max_threads nb_pending_tasks = self._max_threads elif nb_pending_tasks < self._min_threads: nb_threads = self._min_threads else: nb_threads = nb_pending_tasks # Create the threads for _ in range(nb_pending_tasks): self.__nb_pending_task += 1 self.__start_thread() for _ in range(nb_threads - nb_pending_tasks): self.__start_thread()
python
def start(self): if not self._done_event.is_set(): # Stop event not set: we're running return # Clear the stop event self._done_event.clear() # Compute the number of threads to start to handle pending tasks nb_pending_tasks = self._queue.qsize() if nb_pending_tasks > self._max_threads: nb_threads = self._max_threads nb_pending_tasks = self._max_threads elif nb_pending_tasks < self._min_threads: nb_threads = self._min_threads else: nb_threads = nb_pending_tasks # Create the threads for _ in range(nb_pending_tasks): self.__nb_pending_task += 1 self.__start_thread() for _ in range(nb_threads - nb_pending_tasks): self.__start_thread()
[ "def", "start", "(", "self", ")", ":", "if", "not", "self", ".", "_done_event", ".", "is_set", "(", ")", ":", "# Stop event not set: we're running", "return", "# Clear the stop event", "self", ".", "_done_event", ".", "clear", "(", ")", "# Compute the number of th...
Starts the thread pool. Does nothing if the pool is already started.
[ "Starts", "the", "thread", "pool", ".", "Does", "nothing", "if", "the", "pool", "is", "already", "started", "." ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/threadpool.py#L308-L334
9,820
tcalmant/ipopo
pelix/threadpool.py
ThreadPool.__start_thread
def __start_thread(self): """ Starts a new thread, if possible """ with self.__lock: if self.__nb_threads >= self._max_threads: # Can't create more threads return False if self._done_event.is_set(): # We're stopped: do nothing return False # Prepare thread and start it name = "{0}-{1}".format(self._logger.name, self._thread_id) self._thread_id += 1 thread = threading.Thread(target=self.__run, name=name) thread.daemon = True try: self.__nb_threads += 1 thread.start() self._threads.append(thread) return True except (RuntimeError, OSError): self.__nb_threads -= 1 return False
python
def __start_thread(self): with self.__lock: if self.__nb_threads >= self._max_threads: # Can't create more threads return False if self._done_event.is_set(): # We're stopped: do nothing return False # Prepare thread and start it name = "{0}-{1}".format(self._logger.name, self._thread_id) self._thread_id += 1 thread = threading.Thread(target=self.__run, name=name) thread.daemon = True try: self.__nb_threads += 1 thread.start() self._threads.append(thread) return True except (RuntimeError, OSError): self.__nb_threads -= 1 return False
[ "def", "__start_thread", "(", "self", ")", ":", "with", "self", ".", "__lock", ":", "if", "self", ".", "__nb_threads", ">=", "self", ".", "_max_threads", ":", "# Can't create more threads", "return", "False", "if", "self", ".", "_done_event", ".", "is_set", ...
Starts a new thread, if possible
[ "Starts", "a", "new", "thread", "if", "possible" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/threadpool.py#L336-L362
9,821
tcalmant/ipopo
pelix/threadpool.py
ThreadPool.stop
def stop(self): """ Stops the thread pool. Does nothing if the pool is already stopped. """ if self._done_event.is_set(): # Stop event set: we're stopped return # Set the stop event self._done_event.set() with self.__lock: # Add something in the queue (to unlock the join()) try: for _ in self._threads: self._queue.put(self._done_event, True, self._timeout) except queue.Full: # There is already something in the queue pass # Copy the list of threads to wait for threads = self._threads[:] # Join threads outside the lock for thread in threads: while thread.is_alive(): # Wait 3 seconds thread.join(3) if thread.is_alive(): # Thread is still alive: something might be wrong self._logger.warning( "Thread %s is still alive...", thread.name ) # Clear storage del self._threads[:] self.clear()
python
def stop(self): if self._done_event.is_set(): # Stop event set: we're stopped return # Set the stop event self._done_event.set() with self.__lock: # Add something in the queue (to unlock the join()) try: for _ in self._threads: self._queue.put(self._done_event, True, self._timeout) except queue.Full: # There is already something in the queue pass # Copy the list of threads to wait for threads = self._threads[:] # Join threads outside the lock for thread in threads: while thread.is_alive(): # Wait 3 seconds thread.join(3) if thread.is_alive(): # Thread is still alive: something might be wrong self._logger.warning( "Thread %s is still alive...", thread.name ) # Clear storage del self._threads[:] self.clear()
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "_done_event", ".", "is_set", "(", ")", ":", "# Stop event set: we're stopped", "return", "# Set the stop event", "self", ".", "_done_event", ".", "set", "(", ")", "with", "self", ".", "__lock", ":", ...
Stops the thread pool. Does nothing if the pool is already stopped.
[ "Stops", "the", "thread", "pool", ".", "Does", "nothing", "if", "the", "pool", "is", "already", "stopped", "." ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/threadpool.py#L364-L400
9,822
tcalmant/ipopo
pelix/threadpool.py
ThreadPool.enqueue
def enqueue(self, method, *args, **kwargs): """ Queues a task in the pool :param method: Method to call :return: A FutureResult object, to get the result of the task :raise ValueError: Invalid method :raise Full: The task queue is full """ if not hasattr(method, "__call__"): raise ValueError( "{0} has no __call__ member.".format(method.__name__) ) # Prepare the future result object future = FutureResult(self._logger) # Use a lock, as we might be "resetting" the queue with self.__lock: # Add the task to the queue self._queue.put((method, args, kwargs, future), True, self._timeout) self.__nb_pending_task += 1 if self.__nb_pending_task > self.__nb_threads: # All threads are taken: start a new one self.__start_thread() return future
python
def enqueue(self, method, *args, **kwargs): if not hasattr(method, "__call__"): raise ValueError( "{0} has no __call__ member.".format(method.__name__) ) # Prepare the future result object future = FutureResult(self._logger) # Use a lock, as we might be "resetting" the queue with self.__lock: # Add the task to the queue self._queue.put((method, args, kwargs, future), True, self._timeout) self.__nb_pending_task += 1 if self.__nb_pending_task > self.__nb_threads: # All threads are taken: start a new one self.__start_thread() return future
[ "def", "enqueue", "(", "self", ",", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "hasattr", "(", "method", ",", "\"__call__\"", ")", ":", "raise", "ValueError", "(", "\"{0} has no __call__ member.\"", ".", "format", "(", "m...
Queues a task in the pool :param method: Method to call :return: A FutureResult object, to get the result of the task :raise ValueError: Invalid method :raise Full: The task queue is full
[ "Queues", "a", "task", "in", "the", "pool" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/threadpool.py#L402-L429
9,823
tcalmant/ipopo
pelix/threadpool.py
ThreadPool.clear
def clear(self): """ Empties the current queue content. Returns once the queue have been emptied. """ with self.__lock: # Empty the current queue try: while True: self._queue.get_nowait() self._queue.task_done() except queue.Empty: # Queue is now empty pass # Wait for the tasks currently executed self.join()
python
def clear(self): with self.__lock: # Empty the current queue try: while True: self._queue.get_nowait() self._queue.task_done() except queue.Empty: # Queue is now empty pass # Wait for the tasks currently executed self.join()
[ "def", "clear", "(", "self", ")", ":", "with", "self", ".", "__lock", ":", "# Empty the current queue", "try", ":", "while", "True", ":", "self", ".", "_queue", ".", "get_nowait", "(", ")", "self", ".", "_queue", ".", "task_done", "(", ")", "except", "...
Empties the current queue content. Returns once the queue have been emptied.
[ "Empties", "the", "current", "queue", "content", ".", "Returns", "once", "the", "queue", "have", "been", "emptied", "." ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/threadpool.py#L431-L447
9,824
tcalmant/ipopo
pelix/threadpool.py
ThreadPool.join
def join(self, timeout=None): """ Waits for all the tasks to be executed :param timeout: Maximum time to wait (in seconds) :return: True if the queue has been emptied, else False """ if self._queue.empty(): # Nothing to wait for... return True elif timeout is None: # Use the original join self._queue.join() return True else: # Wait for the condition with self._queue.all_tasks_done: self._queue.all_tasks_done.wait(timeout) return not bool(self._queue.unfinished_tasks)
python
def join(self, timeout=None): if self._queue.empty(): # Nothing to wait for... return True elif timeout is None: # Use the original join self._queue.join() return True else: # Wait for the condition with self._queue.all_tasks_done: self._queue.all_tasks_done.wait(timeout) return not bool(self._queue.unfinished_tasks)
[ "def", "join", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "self", ".", "_queue", ".", "empty", "(", ")", ":", "# Nothing to wait for...", "return", "True", "elif", "timeout", "is", "None", ":", "# Use the original join", "self", ".", "_queue...
Waits for all the tasks to be executed :param timeout: Maximum time to wait (in seconds) :return: True if the queue has been emptied, else False
[ "Waits", "for", "all", "the", "tasks", "to", "be", "executed" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/threadpool.py#L449-L467
9,825
tcalmant/ipopo
pelix/threadpool.py
ThreadPool.__run
def __run(self): """ The main loop """ already_cleaned = False try: while not self._done_event.is_set(): try: # Wait for an action (blocking) task = self._queue.get(True, self._timeout) if task is self._done_event: # Stop event in the queue: get out self._queue.task_done() return except queue.Empty: # Nothing to do yet pass else: with self.__lock: self.__nb_active_threads += 1 # Extract elements method, args, kwargs, future = task try: # Call the method future.execute(method, args, kwargs) except Exception as ex: self._logger.exception( "Error executing %s: %s", method.__name__, ex ) finally: # Mark the action as executed self._queue.task_done() # Thread is not active anymore with self.__lock: self.__nb_pending_task -= 1 self.__nb_active_threads -= 1 # Clean up thread if necessary with self.__lock: extra_threads = self.__nb_threads - self.__nb_active_threads if ( self.__nb_threads > self._min_threads and extra_threads > self._queue.qsize() ): # No more work for this thread # if there are more non active_thread than task # and we're above the minimum number of threads: # stop this one self.__nb_threads -= 1 # To avoid a race condition: decrease the number of # threads here and mark it as already accounted for already_cleaned = True return finally: # Always clean up with self.__lock: # Thread stops: clean up references try: self._threads.remove(threading.current_thread()) except ValueError: pass if not already_cleaned: self.__nb_threads -= 1
python
def __run(self): already_cleaned = False try: while not self._done_event.is_set(): try: # Wait for an action (blocking) task = self._queue.get(True, self._timeout) if task is self._done_event: # Stop event in the queue: get out self._queue.task_done() return except queue.Empty: # Nothing to do yet pass else: with self.__lock: self.__nb_active_threads += 1 # Extract elements method, args, kwargs, future = task try: # Call the method future.execute(method, args, kwargs) except Exception as ex: self._logger.exception( "Error executing %s: %s", method.__name__, ex ) finally: # Mark the action as executed self._queue.task_done() # Thread is not active anymore with self.__lock: self.__nb_pending_task -= 1 self.__nb_active_threads -= 1 # Clean up thread if necessary with self.__lock: extra_threads = self.__nb_threads - self.__nb_active_threads if ( self.__nb_threads > self._min_threads and extra_threads > self._queue.qsize() ): # No more work for this thread # if there are more non active_thread than task # and we're above the minimum number of threads: # stop this one self.__nb_threads -= 1 # To avoid a race condition: decrease the number of # threads here and mark it as already accounted for already_cleaned = True return finally: # Always clean up with self.__lock: # Thread stops: clean up references try: self._threads.remove(threading.current_thread()) except ValueError: pass if not already_cleaned: self.__nb_threads -= 1
[ "def", "__run", "(", "self", ")", ":", "already_cleaned", "=", "False", "try", ":", "while", "not", "self", ".", "_done_event", ".", "is_set", "(", ")", ":", "try", ":", "# Wait for an action (blocking)", "task", "=", "self", ".", "_queue", ".", "get", "...
The main loop
[ "The", "main", "loop" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/threadpool.py#L469-L534
9,826
cfhamlet/os-docid
src/os_docid/x.py
docid
def docid(url, encoding='ascii'): """Get DocID from URL. DocID generation depends on bytes of the URL string. So, if non-ascii charactors in the URL, encoding should be considered properly. Args: url (str or bytes): Pre-encoded bytes or string will be encoded with the 'encoding' argument. encoding (str, optional): Defaults to 'ascii'. Used to encode url argument if it is not pre-encoded into bytes. Returns: DocID: The DocID object. Examples: >>> from os_docid import docid >>> docid('http://www.google.com/') 1d5920f4b44b27a8-ed646a3334ca891f-ff90821feeb2b02a33a6f9fc8e5f3fcd >>> docid('1d5920f4b44b27a8-ed646a3334ca891f-ff90821feeb2b02a33a6f9fc8e5f3fcd') 1d5920f4b44b27a8-ed646a3334ca891f-ff90821feeb2b02a33a6f9fc8e5f3fcd >>> docid('1d5920f4b44b27a8ed646a3334ca891fff90821feeb2b02a33a6f9fc8e5f3fcd') 1d5920f4b44b27a8-ed646a3334ca891f-ff90821feeb2b02a33a6f9fc8e5f3fcd >>> docid('abc') NotImplementedError: Not supported data format """ if not isinstance(url, bytes): url = url.encode(encoding) parser = _URL_PARSER idx = 0 for _c in url: if _c not in _HEX: if not (_c == _SYM_MINUS and (idx == _DOMAINID_LENGTH or idx == _HOSTID_LENGTH + 1)): return parser.parse(url, idx) idx += 1 if idx > 4: break _l = len(url) if _l == _DOCID_LENGTH: parser = _DOCID_PARSER elif _l == _READABLE_DOCID_LENGTH \ and url[_DOMAINID_LENGTH] == _SYM_MINUS \ and url[_HOSTID_LENGTH + 1] == _SYM_MINUS: parser = _R_DOCID_PARSER else: parser = _PARSER return parser.parse(url, idx)
python
def docid(url, encoding='ascii'): if not isinstance(url, bytes): url = url.encode(encoding) parser = _URL_PARSER idx = 0 for _c in url: if _c not in _HEX: if not (_c == _SYM_MINUS and (idx == _DOMAINID_LENGTH or idx == _HOSTID_LENGTH + 1)): return parser.parse(url, idx) idx += 1 if idx > 4: break _l = len(url) if _l == _DOCID_LENGTH: parser = _DOCID_PARSER elif _l == _READABLE_DOCID_LENGTH \ and url[_DOMAINID_LENGTH] == _SYM_MINUS \ and url[_HOSTID_LENGTH + 1] == _SYM_MINUS: parser = _R_DOCID_PARSER else: parser = _PARSER return parser.parse(url, idx)
[ "def", "docid", "(", "url", ",", "encoding", "=", "'ascii'", ")", ":", "if", "not", "isinstance", "(", "url", ",", "bytes", ")", ":", "url", "=", "url", ".", "encode", "(", "encoding", ")", "parser", "=", "_URL_PARSER", "idx", "=", "0", "for", "_c"...
Get DocID from URL. DocID generation depends on bytes of the URL string. So, if non-ascii charactors in the URL, encoding should be considered properly. Args: url (str or bytes): Pre-encoded bytes or string will be encoded with the 'encoding' argument. encoding (str, optional): Defaults to 'ascii'. Used to encode url argument if it is not pre-encoded into bytes. Returns: DocID: The DocID object. Examples: >>> from os_docid import docid >>> docid('http://www.google.com/') 1d5920f4b44b27a8-ed646a3334ca891f-ff90821feeb2b02a33a6f9fc8e5f3fcd >>> docid('1d5920f4b44b27a8-ed646a3334ca891f-ff90821feeb2b02a33a6f9fc8e5f3fcd') 1d5920f4b44b27a8-ed646a3334ca891f-ff90821feeb2b02a33a6f9fc8e5f3fcd >>> docid('1d5920f4b44b27a8ed646a3334ca891fff90821feeb2b02a33a6f9fc8e5f3fcd') 1d5920f4b44b27a8-ed646a3334ca891f-ff90821feeb2b02a33a6f9fc8e5f3fcd >>> docid('abc') NotImplementedError: Not supported data format
[ "Get", "DocID", "from", "URL", "." ]
d3730aa118182f903b540ea738cd47c83f6b5e89
https://github.com/cfhamlet/os-docid/blob/d3730aa118182f903b540ea738cd47c83f6b5e89/src/os_docid/x.py#L172-L229
9,827
hasgeek/coaster
coaster/utils/text.py
sanitize_html
def sanitize_html(value, valid_tags=VALID_TAGS, strip=True): """ Strips unwanted markup out of HTML. """ return bleach.clean(value, tags=list(VALID_TAGS.keys()), attributes=VALID_TAGS, strip=strip)
python
def sanitize_html(value, valid_tags=VALID_TAGS, strip=True): return bleach.clean(value, tags=list(VALID_TAGS.keys()), attributes=VALID_TAGS, strip=strip)
[ "def", "sanitize_html", "(", "value", ",", "valid_tags", "=", "VALID_TAGS", ",", "strip", "=", "True", ")", ":", "return", "bleach", ".", "clean", "(", "value", ",", "tags", "=", "list", "(", "VALID_TAGS", ".", "keys", "(", ")", ")", ",", "attributes",...
Strips unwanted markup out of HTML.
[ "Strips", "unwanted", "markup", "out", "of", "HTML", "." ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/text.py#L61-L65
9,828
hasgeek/coaster
coaster/utils/text.py
deobfuscate_email
def deobfuscate_email(text): """ Deobfuscate email addresses in provided text """ text = unescape(text) # Find the "dot" text = _deobfuscate_dot1_re.sub('.', text) text = _deobfuscate_dot2_re.sub(r'\1.\2', text) text = _deobfuscate_dot3_re.sub(r'\1.\2', text) # Find the "at" text = _deobfuscate_at1_re.sub('@', text) text = _deobfuscate_at2_re.sub(r'\1@\2', text) text = _deobfuscate_at3_re.sub(r'\1@\2', text) return text
python
def deobfuscate_email(text): text = unescape(text) # Find the "dot" text = _deobfuscate_dot1_re.sub('.', text) text = _deobfuscate_dot2_re.sub(r'\1.\2', text) text = _deobfuscate_dot3_re.sub(r'\1.\2', text) # Find the "at" text = _deobfuscate_at1_re.sub('@', text) text = _deobfuscate_at2_re.sub(r'\1@\2', text) text = _deobfuscate_at3_re.sub(r'\1@\2', text) return text
[ "def", "deobfuscate_email", "(", "text", ")", ":", "text", "=", "unescape", "(", "text", ")", "# Find the \"dot\"", "text", "=", "_deobfuscate_dot1_re", ".", "sub", "(", "'.'", ",", "text", ")", "text", "=", "_deobfuscate_dot2_re", ".", "sub", "(", "r'\\1.\\...
Deobfuscate email addresses in provided text
[ "Deobfuscate", "email", "addresses", "in", "provided", "text" ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/text.py#L161-L175
9,829
hasgeek/coaster
coaster/utils/text.py
simplify_text
def simplify_text(text): """ Simplify text to allow comparison. >>> simplify_text("Awesome Coder wanted at Awesome Company") 'awesome coder wanted at awesome company' >>> simplify_text("Awesome Coder, wanted at Awesome Company! ") 'awesome coder wanted at awesome company' >>> simplify_text(u"Awesome Coder, wanted at Awesome Company! ") == 'awesome coder wanted at awesome company' True """ if isinstance(text, six.text_type): if six.PY3: # pragma: no cover text = text.translate(text.maketrans("", "", string.punctuation)).lower() else: # pragma: no cover text = six.text_type(text.encode('utf-8').translate(string.maketrans("", ""), string.punctuation).lower(), 'utf-8') else: text = text.translate(string.maketrans("", ""), string.punctuation).lower() return " ".join(text.split())
python
def simplify_text(text): if isinstance(text, six.text_type): if six.PY3: # pragma: no cover text = text.translate(text.maketrans("", "", string.punctuation)).lower() else: # pragma: no cover text = six.text_type(text.encode('utf-8').translate(string.maketrans("", ""), string.punctuation).lower(), 'utf-8') else: text = text.translate(string.maketrans("", ""), string.punctuation).lower() return " ".join(text.split())
[ "def", "simplify_text", "(", "text", ")", ":", "if", "isinstance", "(", "text", ",", "six", ".", "text_type", ")", ":", "if", "six", ".", "PY3", ":", "# pragma: no cover", "text", "=", "text", ".", "translate", "(", "text", ".", "maketrans", "(", "\"\"...
Simplify text to allow comparison. >>> simplify_text("Awesome Coder wanted at Awesome Company") 'awesome coder wanted at awesome company' >>> simplify_text("Awesome Coder, wanted at Awesome Company! ") 'awesome coder wanted at awesome company' >>> simplify_text(u"Awesome Coder, wanted at Awesome Company! ") == 'awesome coder wanted at awesome company' True
[ "Simplify", "text", "to", "allow", "comparison", "." ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/text.py#L178-L196
9,830
hasgeek/coaster
coaster/manage.py
dropdb
def dropdb(): """Drop database tables""" manager.db.engine.echo = True if prompt_bool("Are you sure you want to lose all your data"): manager.db.drop_all() metadata, alembic_version = alembic_table_metadata() alembic_version.drop() manager.db.session.commit()
python
def dropdb(): manager.db.engine.echo = True if prompt_bool("Are you sure you want to lose all your data"): manager.db.drop_all() metadata, alembic_version = alembic_table_metadata() alembic_version.drop() manager.db.session.commit()
[ "def", "dropdb", "(", ")", ":", "manager", ".", "db", ".", "engine", ".", "echo", "=", "True", "if", "prompt_bool", "(", "\"Are you sure you want to lose all your data\"", ")", ":", "manager", ".", "db", ".", "drop_all", "(", ")", "metadata", ",", "alembic_v...
Drop database tables
[ "Drop", "database", "tables" ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/manage.py#L79-L86
9,831
hasgeek/coaster
coaster/manage.py
createdb
def createdb(): """Create database tables from sqlalchemy models""" manager.db.engine.echo = True manager.db.create_all() set_alembic_revision()
python
def createdb(): manager.db.engine.echo = True manager.db.create_all() set_alembic_revision()
[ "def", "createdb", "(", ")", ":", "manager", ".", "db", ".", "engine", ".", "echo", "=", "True", "manager", ".", "db", ".", "create_all", "(", ")", "set_alembic_revision", "(", ")" ]
Create database tables from sqlalchemy models
[ "Create", "database", "tables", "from", "sqlalchemy", "models" ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/manage.py#L90-L94
9,832
hasgeek/coaster
coaster/manage.py
sync_resources
def sync_resources(): """Sync the client's resources with the Lastuser server""" print("Syncing resources with Lastuser...") resources = manager.app.lastuser.sync_resources()['results'] for rname, resource in six.iteritems(resources): if resource['status'] == 'error': print("Error for %s: %s" % (rname, resource['error'])) else: print("Resource %s %s..." % (rname, resource['status'])) for aname, action in six.iteritems(resource['actions']): if action['status'] == 'error': print("\tError for %s/%s: %s" % (rname, aname, action['error'])) else: print("\tAction %s/%s %s..." % (rname, aname, resource['status'])) print("Resources synced...")
python
def sync_resources(): print("Syncing resources with Lastuser...") resources = manager.app.lastuser.sync_resources()['results'] for rname, resource in six.iteritems(resources): if resource['status'] == 'error': print("Error for %s: %s" % (rname, resource['error'])) else: print("Resource %s %s..." % (rname, resource['status'])) for aname, action in six.iteritems(resource['actions']): if action['status'] == 'error': print("\tError for %s/%s: %s" % (rname, aname, action['error'])) else: print("\tAction %s/%s %s..." % (rname, aname, resource['status'])) print("Resources synced...")
[ "def", "sync_resources", "(", ")", ":", "print", "(", "\"Syncing resources with Lastuser...\"", ")", "resources", "=", "manager", ".", "app", ".", "lastuser", ".", "sync_resources", "(", ")", "[", "'results'", "]", "for", "rname", ",", "resource", "in", "six",...
Sync the client's resources with the Lastuser server
[ "Sync", "the", "client", "s", "resources", "with", "the", "Lastuser", "server" ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/manage.py#L98-L113
9,833
hasgeek/coaster
coaster/app.py
load_config_from_file
def load_config_from_file(app, filepath): """Helper function to load config from a specified file""" try: app.config.from_pyfile(filepath) return True except IOError: # TODO: Can we print to sys.stderr in production? Should this go to # logs instead? print("Did not find settings file %s for additional settings, skipping it" % filepath, file=sys.stderr) return False
python
def load_config_from_file(app, filepath): try: app.config.from_pyfile(filepath) return True except IOError: # TODO: Can we print to sys.stderr in production? Should this go to # logs instead? print("Did not find settings file %s for additional settings, skipping it" % filepath, file=sys.stderr) return False
[ "def", "load_config_from_file", "(", "app", ",", "filepath", ")", ":", "try", ":", "app", ".", "config", ".", "from_pyfile", "(", "filepath", ")", "return", "True", "except", "IOError", ":", "# TODO: Can we print to sys.stderr in production? Should this go to", "# log...
Helper function to load config from a specified file
[ "Helper", "function", "to", "load", "config", "from", "a", "specified", "file" ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/app.py#L124-L133
9,834
hasgeek/coaster
coaster/sqlalchemy/mixins.py
IdMixin.id
def id(cls): """ Database identity for this model, used for foreign key references from other models """ if cls.__uuid_primary_key__: return immutable(Column(UUIDType(binary=False), default=uuid_.uuid4, primary_key=True, nullable=False)) else: return immutable(Column(Integer, primary_key=True, nullable=False))
python
def id(cls): if cls.__uuid_primary_key__: return immutable(Column(UUIDType(binary=False), default=uuid_.uuid4, primary_key=True, nullable=False)) else: return immutable(Column(Integer, primary_key=True, nullable=False))
[ "def", "id", "(", "cls", ")", ":", "if", "cls", ".", "__uuid_primary_key__", ":", "return", "immutable", "(", "Column", "(", "UUIDType", "(", "binary", "=", "False", ")", ",", "default", "=", "uuid_", ".", "uuid4", ",", "primary_key", "=", "True", ",",...
Database identity for this model, used for foreign key references from other models
[ "Database", "identity", "for", "this", "model", "used", "for", "foreign", "key", "references", "from", "other", "models" ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L61-L68
9,835
hasgeek/coaster
coaster/sqlalchemy/mixins.py
IdMixin.url_id
def url_id(cls): """The URL id""" if cls.__uuid_primary_key__: def url_id_func(self): """The URL id, UUID primary key rendered as a hex string""" return self.id.hex def url_id_is(cls): return SqlHexUuidComparator(cls.id) url_id_func.__name__ = 'url_id' url_id_property = hybrid_property(url_id_func) url_id_property = url_id_property.comparator(url_id_is) return url_id_property else: def url_id_func(self): """The URL id, integer primary key rendered as a string""" return six.text_type(self.id) def url_id_expression(cls): """The URL id, integer primary key""" return cls.id url_id_func.__name__ = 'url_id' url_id_property = hybrid_property(url_id_func) url_id_property = url_id_property.expression(url_id_expression) return url_id_property
python
def url_id(cls): if cls.__uuid_primary_key__: def url_id_func(self): """The URL id, UUID primary key rendered as a hex string""" return self.id.hex def url_id_is(cls): return SqlHexUuidComparator(cls.id) url_id_func.__name__ = 'url_id' url_id_property = hybrid_property(url_id_func) url_id_property = url_id_property.comparator(url_id_is) return url_id_property else: def url_id_func(self): """The URL id, integer primary key rendered as a string""" return six.text_type(self.id) def url_id_expression(cls): """The URL id, integer primary key""" return cls.id url_id_func.__name__ = 'url_id' url_id_property = hybrid_property(url_id_func) url_id_property = url_id_property.expression(url_id_expression) return url_id_property
[ "def", "url_id", "(", "cls", ")", ":", "if", "cls", ".", "__uuid_primary_key__", ":", "def", "url_id_func", "(", "self", ")", ":", "\"\"\"The URL id, UUID primary key rendered as a hex string\"\"\"", "return", "self", ".", "id", ".", "hex", "def", "url_id_is", "("...
The URL id
[ "The", "URL", "id" ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L71-L97
9,836
hasgeek/coaster
coaster/sqlalchemy/mixins.py
UrlForMixin.register_view_for
def register_view_for(cls, app, action, classview, attr): """ Register a classview and viewhandler for a given app and action """ if 'view_for_endpoints' not in cls.__dict__: cls.view_for_endpoints = {} cls.view_for_endpoints.setdefault(app, {})[action] = (classview, attr)
python
def register_view_for(cls, app, action, classview, attr): if 'view_for_endpoints' not in cls.__dict__: cls.view_for_endpoints = {} cls.view_for_endpoints.setdefault(app, {})[action] = (classview, attr)
[ "def", "register_view_for", "(", "cls", ",", "app", ",", "action", ",", "classview", ",", "attr", ")", ":", "if", "'view_for_endpoints'", "not", "in", "cls", ".", "__dict__", ":", "cls", ".", "view_for_endpoints", "=", "{", "}", "cls", ".", "view_for_endpo...
Register a classview and viewhandler for a given app and action
[ "Register", "a", "classview", "and", "viewhandler", "for", "a", "given", "app", "and", "action" ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L275-L281
9,837
hasgeek/coaster
coaster/sqlalchemy/mixins.py
UrlForMixin.view_for
def view_for(self, action='view'): """ Return the classview viewhandler that handles the specified action """ app = current_app._get_current_object() view, attr = self.view_for_endpoints[app][action] return getattr(view(self), attr)
python
def view_for(self, action='view'): app = current_app._get_current_object() view, attr = self.view_for_endpoints[app][action] return getattr(view(self), attr)
[ "def", "view_for", "(", "self", ",", "action", "=", "'view'", ")", ":", "app", "=", "current_app", ".", "_get_current_object", "(", ")", "view", ",", "attr", "=", "self", ".", "view_for_endpoints", "[", "app", "]", "[", "action", "]", "return", "getattr"...
Return the classview viewhandler that handles the specified action
[ "Return", "the", "classview", "viewhandler", "that", "handles", "the", "specified", "action" ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L283-L289
9,838
hasgeek/coaster
coaster/sqlalchemy/mixins.py
UrlForMixin.classview_for
def classview_for(self, action='view'): """ Return the classview that contains the viewhandler for the specified action """ app = current_app._get_current_object() return self.view_for_endpoints[app][action][0](self)
python
def classview_for(self, action='view'): app = current_app._get_current_object() return self.view_for_endpoints[app][action][0](self)
[ "def", "classview_for", "(", "self", ",", "action", "=", "'view'", ")", ":", "app", "=", "current_app", ".", "_get_current_object", "(", ")", "return", "self", ".", "view_for_endpoints", "[", "app", "]", "[", "action", "]", "[", "0", "]", "(", "self", ...
Return the classview that contains the viewhandler for the specified action
[ "Return", "the", "classview", "that", "contains", "the", "viewhandler", "for", "the", "specified", "action" ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L291-L296
9,839
hasgeek/coaster
coaster/sqlalchemy/mixins.py
BaseNameMixin.name
def name(cls): """The URL name of this object, unique across all instances of this model""" if cls.__name_length__ is None: column_type = UnicodeText() else: column_type = Unicode(cls.__name_length__) if cls.__name_blank_allowed__: return Column(column_type, nullable=False, unique=True) else: return Column(column_type, CheckConstraint("name <> ''"), nullable=False, unique=True)
python
def name(cls): if cls.__name_length__ is None: column_type = UnicodeText() else: column_type = Unicode(cls.__name_length__) if cls.__name_blank_allowed__: return Column(column_type, nullable=False, unique=True) else: return Column(column_type, CheckConstraint("name <> ''"), nullable=False, unique=True)
[ "def", "name", "(", "cls", ")", ":", "if", "cls", ".", "__name_length__", "is", "None", ":", "column_type", "=", "UnicodeText", "(", ")", "else", ":", "column_type", "=", "Unicode", "(", "cls", ".", "__name_length__", ")", "if", "cls", ".", "__name_blank...
The URL name of this object, unique across all instances of this model
[ "The", "URL", "name", "of", "this", "object", "unique", "across", "all", "instances", "of", "this", "model" ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L347-L356
9,840
hasgeek/coaster
coaster/sqlalchemy/mixins.py
BaseNameMixin.title
def title(cls): """The title of this object""" if cls.__title_length__ is None: column_type = UnicodeText() else: column_type = Unicode(cls.__title_length__) return Column(column_type, nullable=False)
python
def title(cls): if cls.__title_length__ is None: column_type = UnicodeText() else: column_type = Unicode(cls.__title_length__) return Column(column_type, nullable=False)
[ "def", "title", "(", "cls", ")", ":", "if", "cls", ".", "__title_length__", "is", "None", ":", "column_type", "=", "UnicodeText", "(", ")", "else", ":", "column_type", "=", "Unicode", "(", "cls", ".", "__title_length__", ")", "return", "Column", "(", "co...
The title of this object
[ "The", "title", "of", "this", "object" ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L359-L365
9,841
hasgeek/coaster
coaster/sqlalchemy/mixins.py
BaseNameMixin.upsert
def upsert(cls, name, **fields): """Insert or update an instance""" instance = cls.get(name) if instance: instance._set_fields(fields) else: instance = cls(name=name, **fields) instance = failsafe_add(cls.query.session, instance, name=name) return instance
python
def upsert(cls, name, **fields): instance = cls.get(name) if instance: instance._set_fields(fields) else: instance = cls(name=name, **fields) instance = failsafe_add(cls.query.session, instance, name=name) return instance
[ "def", "upsert", "(", "cls", ",", "name", ",", "*", "*", "fields", ")", ":", "instance", "=", "cls", ".", "get", "(", "name", ")", "if", "instance", ":", "instance", ".", "_set_fields", "(", "fields", ")", "else", ":", "instance", "=", "cls", "(", ...
Insert or update an instance
[ "Insert", "or", "update", "an", "instance" ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L386-L394
9,842
hasgeek/coaster
coaster/sqlalchemy/mixins.py
BaseScopedNameMixin.get
def get(cls, parent, name): """Get an instance matching the parent and name""" return cls.query.filter_by(parent=parent, name=name).one_or_none()
python
def get(cls, parent, name): return cls.query.filter_by(parent=parent, name=name).one_or_none()
[ "def", "get", "(", "cls", ",", "parent", ",", "name", ")", ":", "return", "cls", ".", "query", ".", "filter_by", "(", "parent", "=", "parent", ",", "name", "=", "name", ")", ".", "one_or_none", "(", ")" ]
Get an instance matching the parent and name
[ "Get", "an", "instance", "matching", "the", "parent", "and", "name" ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L483-L485
9,843
hasgeek/coaster
coaster/sqlalchemy/mixins.py
BaseScopedNameMixin.short_title
def short_title(self): """ Generates an abbreviated title by subtracting the parent's title from this instance's title. """ if self.title and self.parent is not None and hasattr(self.parent, 'title') and self.parent.title: if self.title.startswith(self.parent.title): short = self.title[len(self.parent.title):].strip() match = _punctuation_re.match(short) if match: short = short[match.end():].strip() if short: return short return self.title
python
def short_title(self): if self.title and self.parent is not None and hasattr(self.parent, 'title') and self.parent.title: if self.title.startswith(self.parent.title): short = self.title[len(self.parent.title):].strip() match = _punctuation_re.match(short) if match: short = short[match.end():].strip() if short: return short return self.title
[ "def", "short_title", "(", "self", ")", ":", "if", "self", ".", "title", "and", "self", ".", "parent", "is", "not", "None", "and", "hasattr", "(", "self", ".", "parent", ",", "'title'", ")", "and", "self", ".", "parent", ".", "title", ":", "if", "s...
Generates an abbreviated title by subtracting the parent's title from this instance's title.
[ "Generates", "an", "abbreviated", "title", "by", "subtracting", "the", "parent", "s", "title", "from", "this", "instance", "s", "title", "." ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L517-L529
9,844
hasgeek/coaster
coaster/sqlalchemy/mixins.py
BaseScopedNameMixin.permissions
def permissions(self, actor, inherited=None): """ Permissions for this model, plus permissions inherited from the parent. """ if inherited is not None: return inherited | super(BaseScopedNameMixin, self).permissions(actor) elif self.parent is not None and isinstance(self.parent, PermissionMixin): return self.parent.permissions(actor) | super(BaseScopedNameMixin, self).permissions(actor) else: return super(BaseScopedNameMixin, self).permissions(actor)
python
def permissions(self, actor, inherited=None): if inherited is not None: return inherited | super(BaseScopedNameMixin, self).permissions(actor) elif self.parent is not None and isinstance(self.parent, PermissionMixin): return self.parent.permissions(actor) | super(BaseScopedNameMixin, self).permissions(actor) else: return super(BaseScopedNameMixin, self).permissions(actor)
[ "def", "permissions", "(", "self", ",", "actor", ",", "inherited", "=", "None", ")", ":", "if", "inherited", "is", "not", "None", ":", "return", "inherited", "|", "super", "(", "BaseScopedNameMixin", ",", "self", ")", ".", "permissions", "(", "actor", ")...
Permissions for this model, plus permissions inherited from the parent.
[ "Permissions", "for", "this", "model", "plus", "permissions", "inherited", "from", "the", "parent", "." ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L536-L545
9,845
hasgeek/coaster
coaster/sqlalchemy/mixins.py
BaseScopedIdMixin.get
def get(cls, parent, url_id): """Get an instance matching the parent and url_id""" return cls.query.filter_by(parent=parent, url_id=url_id).one_or_none()
python
def get(cls, parent, url_id): return cls.query.filter_by(parent=parent, url_id=url_id).one_or_none()
[ "def", "get", "(", "cls", ",", "parent", ",", "url_id", ")", ":", "return", "cls", ".", "query", ".", "filter_by", "(", "parent", "=", "parent", ",", "url_id", "=", "url_id", ")", ".", "one_or_none", "(", ")" ]
Get an instance matching the parent and url_id
[ "Get", "an", "instance", "matching", "the", "parent", "and", "url_id" ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L673-L675
9,846
hasgeek/coaster
coaster/sqlalchemy/mixins.py
BaseScopedIdMixin.make_id
def make_id(self): """Create a new URL id that is unique to the parent container""" if self.url_id is None: # Set id only if empty self.url_id = select([func.coalesce(func.max(self.__class__.url_id + 1), 1)], self.__class__.parent == self.parent)
python
def make_id(self): if self.url_id is None: # Set id only if empty self.url_id = select([func.coalesce(func.max(self.__class__.url_id + 1), 1)], self.__class__.parent == self.parent)
[ "def", "make_id", "(", "self", ")", ":", "if", "self", ".", "url_id", "is", "None", ":", "# Set id only if empty", "self", ".", "url_id", "=", "select", "(", "[", "func", ".", "coalesce", "(", "func", ".", "max", "(", "self", ".", "__class__", ".", "...
Create a new URL id that is unique to the parent container
[ "Create", "a", "new", "URL", "id", "that", "is", "unique", "to", "the", "parent", "container" ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L677-L681
9,847
hasgeek/coaster
coaster/sqlalchemy/functions.py
make_timestamp_columns
def make_timestamp_columns(): """Return two columns, created_at and updated_at, with appropriate defaults""" return ( Column('created_at', DateTime, default=func.utcnow(), nullable=False), Column('updated_at', DateTime, default=func.utcnow(), onupdate=func.utcnow(), nullable=False), )
python
def make_timestamp_columns(): return ( Column('created_at', DateTime, default=func.utcnow(), nullable=False), Column('updated_at', DateTime, default=func.utcnow(), onupdate=func.utcnow(), nullable=False), )
[ "def", "make_timestamp_columns", "(", ")", ":", "return", "(", "Column", "(", "'created_at'", ",", "DateTime", ",", "default", "=", "func", ".", "utcnow", "(", ")", ",", "nullable", "=", "False", ")", ",", "Column", "(", "'updated_at'", ",", "DateTime", ...
Return two columns, created_at and updated_at, with appropriate defaults
[ "Return", "two", "columns", "created_at", "and", "updated_at", "with", "appropriate", "defaults" ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/functions.py#L49-L54
9,848
hasgeek/coaster
coaster/sqlalchemy/functions.py
auto_init_default
def auto_init_default(column): """ Set the default value for a column when it's first accessed rather than first committed to the database. """ if isinstance(column, ColumnProperty): default = column.columns[0].default else: default = column.default @event.listens_for(column, 'init_scalar', retval=True, propagate=True) def init_scalar(target, value, dict_): # A subclass may override the column and not provide a default. Watch out for that. if default: if default.is_callable: value = default.arg(None) elif default.is_scalar: value = default.arg else: raise NotImplementedError("Can't invoke pre-default for a SQL-level column default") dict_[column.key] = value return value
python
def auto_init_default(column): if isinstance(column, ColumnProperty): default = column.columns[0].default else: default = column.default @event.listens_for(column, 'init_scalar', retval=True, propagate=True) def init_scalar(target, value, dict_): # A subclass may override the column and not provide a default. Watch out for that. if default: if default.is_callable: value = default.arg(None) elif default.is_scalar: value = default.arg else: raise NotImplementedError("Can't invoke pre-default for a SQL-level column default") dict_[column.key] = value return value
[ "def", "auto_init_default", "(", "column", ")", ":", "if", "isinstance", "(", "column", ",", "ColumnProperty", ")", ":", "default", "=", "column", ".", "columns", "[", "0", "]", ".", "default", "else", ":", "default", "=", "column", ".", "default", "@", ...
Set the default value for a column when it's first accessed rather than first committed to the database.
[ "Set", "the", "default", "value", "for", "a", "column", "when", "it", "s", "first", "accessed", "rather", "than", "first", "committed", "to", "the", "database", "." ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/functions.py#L213-L234
9,849
hasgeek/coaster
coaster/views/decorators.py
load_model
def load_model(model, attributes=None, parameter=None, kwargs=False, permission=None, addlperms=None, urlcheck=[]): """ Decorator to load a model given a query parameter. Typical usage:: @app.route('/<profile>') @load_model(Profile, {'name': 'profile'}, 'profileob') def profile_view(profileob): # 'profileob' is now a Profile model instance. The load_model decorator replaced this: # profileob = Profile.query.filter_by(name=profile).first_or_404() return "Hello, %s" % profileob.name Using the same name for request and parameter makes code easier to understand:: @app.route('/<profile>') @load_model(Profile, {'name': 'profile'}, 'profile') def profile_view(profile): return "Hello, %s" % profile.name ``load_model`` aborts with a 404 if no instance is found. :param model: The SQLAlchemy model to query. Must contain a ``query`` object (which is the default with Flask-SQLAlchemy) :param attributes: A dict of attributes (from the URL request) that will be used to query for the object. For each key:value pair, the key is the name of the column on the model and the value is the name of the request parameter that contains the data :param parameter: The name of the parameter to the decorated function via which the result is passed. Usually the same as the attribute. If the parameter name is prefixed with 'g.', the parameter is also made available as g.<parameter> :param kwargs: If True, the original request parameters are passed to the decorated function as a ``kwargs`` parameter :param permission: If present, ``load_model`` calls the :meth:`~coaster.sqlalchemy.PermissionMixin.permissions` method of the retrieved object with ``current_auth.actor`` as a parameter. If ``permission`` is not present in the result, ``load_model`` aborts with a 403. The permission may be a string or a list of strings, in which case access is allowed if any of the listed permissions are available :param addlperms: Iterable or callable that returns an iterable containing additional permissions available to the user, apart from those granted by the models. In an app that uses Lastuser for authentication, passing ``lastuser.permissions`` will pass through permissions granted via Lastuser :param list urlcheck: If an attribute in this list has been used to load an object, but the value of the attribute in the loaded object does not match the request argument, issue a redirect to the corrected URL. This is useful for attributes like ``url_id_name`` and ``url_name_suuid`` where the ``name`` component may change """ return load_models((model, attributes, parameter), kwargs=kwargs, permission=permission, addlperms=addlperms, urlcheck=urlcheck)
python
def load_model(model, attributes=None, parameter=None, kwargs=False, permission=None, addlperms=None, urlcheck=[]): return load_models((model, attributes, parameter), kwargs=kwargs, permission=permission, addlperms=addlperms, urlcheck=urlcheck)
[ "def", "load_model", "(", "model", ",", "attributes", "=", "None", ",", "parameter", "=", "None", ",", "kwargs", "=", "False", ",", "permission", "=", "None", ",", "addlperms", "=", "None", ",", "urlcheck", "=", "[", "]", ")", ":", "return", "load_mode...
Decorator to load a model given a query parameter. Typical usage:: @app.route('/<profile>') @load_model(Profile, {'name': 'profile'}, 'profileob') def profile_view(profileob): # 'profileob' is now a Profile model instance. The load_model decorator replaced this: # profileob = Profile.query.filter_by(name=profile).first_or_404() return "Hello, %s" % profileob.name Using the same name for request and parameter makes code easier to understand:: @app.route('/<profile>') @load_model(Profile, {'name': 'profile'}, 'profile') def profile_view(profile): return "Hello, %s" % profile.name ``load_model`` aborts with a 404 if no instance is found. :param model: The SQLAlchemy model to query. Must contain a ``query`` object (which is the default with Flask-SQLAlchemy) :param attributes: A dict of attributes (from the URL request) that will be used to query for the object. For each key:value pair, the key is the name of the column on the model and the value is the name of the request parameter that contains the data :param parameter: The name of the parameter to the decorated function via which the result is passed. Usually the same as the attribute. If the parameter name is prefixed with 'g.', the parameter is also made available as g.<parameter> :param kwargs: If True, the original request parameters are passed to the decorated function as a ``kwargs`` parameter :param permission: If present, ``load_model`` calls the :meth:`~coaster.sqlalchemy.PermissionMixin.permissions` method of the retrieved object with ``current_auth.actor`` as a parameter. If ``permission`` is not present in the result, ``load_model`` aborts with a 403. The permission may be a string or a list of strings, in which case access is allowed if any of the listed permissions are available :param addlperms: Iterable or callable that returns an iterable containing additional permissions available to the user, apart from those granted by the models. In an app that uses Lastuser for authentication, passing ``lastuser.permissions`` will pass through permissions granted via Lastuser :param list urlcheck: If an attribute in this list has been used to load an object, but the value of the attribute in the loaded object does not match the request argument, issue a redirect to the corrected URL. This is useful for attributes like ``url_id_name`` and ``url_name_suuid`` where the ``name`` component may change
[ "Decorator", "to", "load", "a", "model", "given", "a", "query", "parameter", "." ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/decorators.py#L147-L203
9,850
hasgeek/coaster
coaster/views/decorators.py
dict_jsonify
def dict_jsonify(param): """Convert the parameter into a dictionary before calling jsonify, if it's not already one""" if not isinstance(param, dict): param = dict(param) return jsonify(param)
python
def dict_jsonify(param): if not isinstance(param, dict): param = dict(param) return jsonify(param)
[ "def", "dict_jsonify", "(", "param", ")", ":", "if", "not", "isinstance", "(", "param", ",", "dict", ")", ":", "param", "=", "dict", "(", "param", ")", "return", "jsonify", "(", "param", ")" ]
Convert the parameter into a dictionary before calling jsonify, if it's not already one
[ "Convert", "the", "parameter", "into", "a", "dictionary", "before", "calling", "jsonify", "if", "it", "s", "not", "already", "one" ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/decorators.py#L334-L338
9,851
hasgeek/coaster
coaster/views/decorators.py
dict_jsonp
def dict_jsonp(param): """Convert the parameter into a dictionary before calling jsonp, if it's not already one""" if not isinstance(param, dict): param = dict(param) return jsonp(param)
python
def dict_jsonp(param): if not isinstance(param, dict): param = dict(param) return jsonp(param)
[ "def", "dict_jsonp", "(", "param", ")", ":", "if", "not", "isinstance", "(", "param", ",", "dict", ")", ":", "param", "=", "dict", "(", "param", ")", "return", "jsonp", "(", "param", ")" ]
Convert the parameter into a dictionary before calling jsonp, if it's not already one
[ "Convert", "the", "parameter", "into", "a", "dictionary", "before", "calling", "jsonp", "if", "it", "s", "not", "already", "one" ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/decorators.py#L341-L345
9,852
hasgeek/coaster
coaster/views/decorators.py
cors
def cors(origins, methods=['HEAD', 'OPTIONS', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE'], headers=['Accept', 'Accept-Language', 'Content-Language', 'Content-Type', 'X-Requested-With'], max_age=None): """ Adds CORS headers to the decorated view function. :param origins: Allowed origins (see below) :param methods: A list of allowed HTTP methods :param headers: A list of allowed HTTP headers :param max_age: Duration in seconds for which the CORS response may be cached The :obj:`origins` parameter may be one of: 1. A callable that receives the origin as a parameter. 2. A list of origins. 3. ``*``, indicating that this resource is accessible by any origin. Example use:: from flask import Flask, Response from coaster.views import cors app = Flask(__name__) @app.route('/any') @cors('*') def any_origin(): return Response() @app.route('/static', methods=['GET', 'POST']) @cors(['https://hasgeek.com'], methods=['GET'], headers=['Content-Type', 'X-Requested-With'], max_age=3600) def static_list(): return Response() def check_origin(origin): # check if origin should be allowed return True @app.route('/callable') @cors(check_origin) def callable_function(): return Response() """ def inner(f): @wraps(f) def wrapper(*args, **kwargs): origin = request.headers.get('Origin') if request.method not in methods: abort(405) if origins == '*': pass elif is_collection(origins) and origin in origins: pass elif callable(origins) and origins(origin): pass else: abort(403) if request.method == 'OPTIONS': # pre-flight request resp = Response() else: result = f(*args, **kwargs) resp = make_response(result) if not isinstance(result, (Response, WerkzeugResponse, current_app.response_class)) else result resp.headers['Access-Control-Allow-Origin'] = origin if origin else '' resp.headers['Access-Control-Allow-Methods'] = ', '.join(methods) resp.headers['Access-Control-Allow-Headers'] = ', '.join(headers) if max_age: resp.headers['Access-Control-Max-Age'] = str(max_age) # Add 'Origin' to the Vary header since response will vary by origin if 'Vary' in resp.headers: vary_values = [item.strip() for item in resp.headers['Vary'].split(',')] if 'Origin' not in vary_values: vary_values.append('Origin') resp.headers['Vary'] = ', '.join(vary_values) else: resp.headers['Vary'] = 'Origin' return resp return wrapper return inner
python
def cors(origins, methods=['HEAD', 'OPTIONS', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE'], headers=['Accept', 'Accept-Language', 'Content-Language', 'Content-Type', 'X-Requested-With'], max_age=None): def inner(f): @wraps(f) def wrapper(*args, **kwargs): origin = request.headers.get('Origin') if request.method not in methods: abort(405) if origins == '*': pass elif is_collection(origins) and origin in origins: pass elif callable(origins) and origins(origin): pass else: abort(403) if request.method == 'OPTIONS': # pre-flight request resp = Response() else: result = f(*args, **kwargs) resp = make_response(result) if not isinstance(result, (Response, WerkzeugResponse, current_app.response_class)) else result resp.headers['Access-Control-Allow-Origin'] = origin if origin else '' resp.headers['Access-Control-Allow-Methods'] = ', '.join(methods) resp.headers['Access-Control-Allow-Headers'] = ', '.join(headers) if max_age: resp.headers['Access-Control-Max-Age'] = str(max_age) # Add 'Origin' to the Vary header since response will vary by origin if 'Vary' in resp.headers: vary_values = [item.strip() for item in resp.headers['Vary'].split(',')] if 'Origin' not in vary_values: vary_values.append('Origin') resp.headers['Vary'] = ', '.join(vary_values) else: resp.headers['Vary'] = 'Origin' return resp return wrapper return inner
[ "def", "cors", "(", "origins", ",", "methods", "=", "[", "'HEAD'", ",", "'OPTIONS'", ",", "'GET'", ",", "'POST'", ",", "'PUT'", ",", "'PATCH'", ",", "'DELETE'", "]", ",", "headers", "=", "[", "'Accept'", ",", "'Accept-Language'", ",", "'Content-Language'",...
Adds CORS headers to the decorated view function. :param origins: Allowed origins (see below) :param methods: A list of allowed HTTP methods :param headers: A list of allowed HTTP headers :param max_age: Duration in seconds for which the CORS response may be cached The :obj:`origins` parameter may be one of: 1. A callable that receives the origin as a parameter. 2. A list of origins. 3. ``*``, indicating that this resource is accessible by any origin. Example use:: from flask import Flask, Response from coaster.views import cors app = Flask(__name__) @app.route('/any') @cors('*') def any_origin(): return Response() @app.route('/static', methods=['GET', 'POST']) @cors(['https://hasgeek.com'], methods=['GET'], headers=['Content-Type', 'X-Requested-With'], max_age=3600) def static_list(): return Response() def check_origin(origin): # check if origin should be allowed return True @app.route('/callable') @cors(check_origin) def callable_function(): return Response()
[ "Adds", "CORS", "headers", "to", "the", "decorated", "view", "function", "." ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/decorators.py#L513-L598
9,853
hasgeek/coaster
coaster/views/decorators.py
requires_permission
def requires_permission(permission): """ View decorator that requires a certain permission to be present in ``current_auth.permissions`` before the view is allowed to proceed. Aborts with ``403 Forbidden`` if the permission is not present. The decorated view will have an ``is_available`` method that can be called to perform the same test. :param permission: Permission that is required. If a collection type is provided, any one permission must be available """ def inner(f): def is_available_here(): if not hasattr(current_auth, 'permissions'): return False elif is_collection(permission): return bool(current_auth.permissions.intersection(permission)) else: return permission in current_auth.permissions def is_available(context=None): result = is_available_here() if result and hasattr(f, 'is_available'): # We passed, but we're wrapping another test, so ask there as well return f.is_available(context) return result @wraps(f) def wrapper(*args, **kwargs): add_auth_attribute('login_required', True) if not is_available_here(): abort(403) return f(*args, **kwargs) wrapper.requires_permission = permission wrapper.is_available = is_available return wrapper return inner
python
def requires_permission(permission): def inner(f): def is_available_here(): if not hasattr(current_auth, 'permissions'): return False elif is_collection(permission): return bool(current_auth.permissions.intersection(permission)) else: return permission in current_auth.permissions def is_available(context=None): result = is_available_here() if result and hasattr(f, 'is_available'): # We passed, but we're wrapping another test, so ask there as well return f.is_available(context) return result @wraps(f) def wrapper(*args, **kwargs): add_auth_attribute('login_required', True) if not is_available_here(): abort(403) return f(*args, **kwargs) wrapper.requires_permission = permission wrapper.is_available = is_available return wrapper return inner
[ "def", "requires_permission", "(", "permission", ")", ":", "def", "inner", "(", "f", ")", ":", "def", "is_available_here", "(", ")", ":", "if", "not", "hasattr", "(", "current_auth", ",", "'permissions'", ")", ":", "return", "False", "elif", "is_collection",...
View decorator that requires a certain permission to be present in ``current_auth.permissions`` before the view is allowed to proceed. Aborts with ``403 Forbidden`` if the permission is not present. The decorated view will have an ``is_available`` method that can be called to perform the same test. :param permission: Permission that is required. If a collection type is provided, any one permission must be available
[ "View", "decorator", "that", "requires", "a", "certain", "permission", "to", "be", "present", "in", "current_auth", ".", "permissions", "before", "the", "view", "is", "allowed", "to", "proceed", ".", "Aborts", "with", "403", "Forbidden", "if", "the", "permissi...
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/decorators.py#L601-L639
9,854
hasgeek/coaster
coaster/utils/misc.py
uuid1mc_from_datetime
def uuid1mc_from_datetime(dt): """ Return a UUID1 with a random multicast MAC id and with a timestamp matching the given datetime object or timestamp value. .. warning:: This function does not consider the timezone, and is not guaranteed to return a unique UUID. Use under controlled conditions only. >>> dt = datetime.now() >>> u1 = uuid1mc() >>> u2 = uuid1mc_from_datetime(dt) >>> # Both timestamps should be very close to each other but not an exact match >>> u1.time > u2.time True >>> u1.time - u2.time < 5000 True >>> d2 = datetime.fromtimestamp((u2.time - 0x01b21dd213814000) * 100 / 1e9) >>> d2 == dt True """ fields = list(uuid1mc().fields) if isinstance(dt, datetime): timeval = time.mktime(dt.timetuple()) + dt.microsecond / 1e6 else: # Assume we got an actual timestamp timeval = dt # The following code is borrowed from the UUID module source: nanoseconds = int(timeval * 1e9) # 0x01b21dd213814000 is the number of 100-ns intervals between the # UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00. timestamp = int(nanoseconds // 100) + 0x01b21dd213814000 time_low = timestamp & 0xffffffff time_mid = (timestamp >> 32) & 0xffff time_hi_version = (timestamp >> 48) & 0x0fff fields[0] = time_low fields[1] = time_mid fields[2] = time_hi_version return uuid.UUID(fields=tuple(fields))
python
def uuid1mc_from_datetime(dt): fields = list(uuid1mc().fields) if isinstance(dt, datetime): timeval = time.mktime(dt.timetuple()) + dt.microsecond / 1e6 else: # Assume we got an actual timestamp timeval = dt # The following code is borrowed from the UUID module source: nanoseconds = int(timeval * 1e9) # 0x01b21dd213814000 is the number of 100-ns intervals between the # UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00. timestamp = int(nanoseconds // 100) + 0x01b21dd213814000 time_low = timestamp & 0xffffffff time_mid = (timestamp >> 32) & 0xffff time_hi_version = (timestamp >> 48) & 0x0fff fields[0] = time_low fields[1] = time_mid fields[2] = time_hi_version return uuid.UUID(fields=tuple(fields))
[ "def", "uuid1mc_from_datetime", "(", "dt", ")", ":", "fields", "=", "list", "(", "uuid1mc", "(", ")", ".", "fields", ")", "if", "isinstance", "(", "dt", ",", "datetime", ")", ":", "timeval", "=", "time", ".", "mktime", "(", "dt", ".", "timetuple", "(...
Return a UUID1 with a random multicast MAC id and with a timestamp matching the given datetime object or timestamp value. .. warning:: This function does not consider the timezone, and is not guaranteed to return a unique UUID. Use under controlled conditions only. >>> dt = datetime.now() >>> u1 = uuid1mc() >>> u2 = uuid1mc_from_datetime(dt) >>> # Both timestamps should be very close to each other but not an exact match >>> u1.time > u2.time True >>> u1.time - u2.time < 5000 True >>> d2 = datetime.fromtimestamp((u2.time - 0x01b21dd213814000) * 100 / 1e9) >>> d2 == dt True
[ "Return", "a", "UUID1", "with", "a", "random", "multicast", "MAC", "id", "and", "with", "a", "timestamp", "matching", "the", "given", "datetime", "object", "or", "timestamp", "value", "." ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L104-L145
9,855
hasgeek/coaster
coaster/utils/misc.py
uuid2buid
def uuid2buid(value): """ Convert a UUID object to a 22-char BUID string >>> u = uuid.UUID('33203dd2-f2ef-422f-aeb0-058d6f5f7089') >>> uuid2buid(u) 'MyA90vLvQi-usAWNb19wiQ' """ if six.PY3: # pragma: no cover return urlsafe_b64encode(value.bytes).decode('utf-8').rstrip('=') else: return six.text_type(urlsafe_b64encode(value.bytes).rstrip('='))
python
def uuid2buid(value): if six.PY3: # pragma: no cover return urlsafe_b64encode(value.bytes).decode('utf-8').rstrip('=') else: return six.text_type(urlsafe_b64encode(value.bytes).rstrip('='))
[ "def", "uuid2buid", "(", "value", ")", ":", "if", "six", ".", "PY3", ":", "# pragma: no cover", "return", "urlsafe_b64encode", "(", "value", ".", "bytes", ")", ".", "decode", "(", "'utf-8'", ")", ".", "rstrip", "(", "'='", ")", "else", ":", "return", "...
Convert a UUID object to a 22-char BUID string >>> u = uuid.UUID('33203dd2-f2ef-422f-aeb0-058d6f5f7089') >>> uuid2buid(u) 'MyA90vLvQi-usAWNb19wiQ'
[ "Convert", "a", "UUID", "object", "to", "a", "22", "-", "char", "BUID", "string" ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L148-L159
9,856
hasgeek/coaster
coaster/utils/misc.py
newpin
def newpin(digits=4): """ Return a random numeric string with the specified number of digits, default 4. >>> len(newpin()) 4 >>> len(newpin(5)) 5 >>> newpin().isdigit() True """ randnum = randint(0, 10 ** digits) while len(str(randnum)) > digits: randnum = randint(0, 10 ** digits) return (u'%%0%dd' % digits) % randnum
python
def newpin(digits=4): randnum = randint(0, 10 ** digits) while len(str(randnum)) > digits: randnum = randint(0, 10 ** digits) return (u'%%0%dd' % digits) % randnum
[ "def", "newpin", "(", "digits", "=", "4", ")", ":", "randnum", "=", "randint", "(", "0", ",", "10", "**", "digits", ")", "while", "len", "(", "str", "(", "randnum", ")", ")", ">", "digits", ":", "randnum", "=", "randint", "(", "0", ",", "10", "...
Return a random numeric string with the specified number of digits, default 4. >>> len(newpin()) 4 >>> len(newpin(5)) 5 >>> newpin().isdigit() True
[ "Return", "a", "random", "numeric", "string", "with", "the", "specified", "number", "of", "digits", "default", "4", "." ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L186-L201
9,857
hasgeek/coaster
coaster/utils/misc.py
make_name
def make_name(text, delim=u'-', maxlength=50, checkused=None, counter=2): u""" Generate an ASCII name slug. If a checkused filter is provided, it will be called with the candidate. If it returns True, make_name will add counter numbers starting from 2 until a suitable candidate is found. :param string delim: Delimiter between words, default '-' :param int maxlength: Maximum length of name, default 50 :param checkused: Function to check if a generated name is available for use :param int counter: Starting position for name counter >>> make_name('This is a title') 'this-is-a-title' >>> make_name('Invalid URL/slug here') 'invalid-url-slug-here' >>> make_name('this.that') 'this-that' >>> make_name('this:that') 'this-that' >>> make_name("How 'bout this?") 'how-bout-this' >>> make_name(u"How’s that?") 'hows-that' >>> make_name(u'K & D') 'k-d' >>> make_name('billion+ pageviews') 'billion-pageviews' >>> make_name(u'हिन्दी slug!') 'hindii-slug' >>> make_name(u'Your webapps should talk not just in English, but in español, Kiswahili, 廣州話 and অসমীয়া too.', maxlength=250) u'your-webapps-should-talk-not-just-in-english-but-in-espanol-kiswahili-guang-zhou-hua-and-asmiiyaa-too' >>> make_name(u'__name__', delim=u'_') 'name' >>> make_name(u'how_about_this', delim=u'_') 'how_about_this' >>> make_name(u'and-that', delim=u'_') 'and_that' >>> make_name(u'Umlauts in Mötörhead') 'umlauts-in-motorhead' >>> make_name('Candidate', checkused=lambda c: c in ['candidate']) 'candidate2' >>> make_name('Candidate', checkused=lambda c: c in ['candidate'], counter=1) 'candidate1' >>> make_name('Candidate', checkused=lambda c: c in ['candidate', 'candidate1', 'candidate2'], counter=1) 'candidate3' >>> make_name('Long title, but snipped', maxlength=20) 'long-title-but-snipp' >>> len(make_name('Long title, but snipped', maxlength=20)) 20 >>> make_name('Long candidate', maxlength=10, checkused=lambda c: c in ['long-candi', 'long-cand1']) 'long-cand2' >>> make_name(u'Lǝnkǝran') 'lankaran' >>> make_name(u'example@example.com') 'example-example-com' >>> make_name('trailing-delimiter', maxlength=10) 'trailing-d' >>> make_name('trailing-delimiter', maxlength=9) 'trailing' >>> make_name('''test this ... newline''') 'test-this-newline' >>> make_name(u"testing an emoji😁") u'testing-an-emoji' >>> make_name('''testing\\t\\nmore\\r\\nslashes''') 'testing-more-slashes' >>> make_name('What if a HTML <tag/>') 'what-if-a-html-tag' >>> make_name('These are equivalent to \\x01 through \\x1A') 'these-are-equivalent-to-through' """ name = text.replace('@', delim) name = unidecode(name).replace('@', 'a') # We don't know why unidecode uses '@' for 'a'-like chars name = six.text_type(delim.join([_strip_re.sub('', x) for x in _punctuation_re.split(name.lower()) if x != ''])) if isinstance(text, six.text_type): # Unidecode returns str. Restore to a unicode string if original was unicode name = six.text_type(name) candidate = name[:maxlength] if candidate.endswith(delim): candidate = candidate[:-1] if checkused is None: return candidate existing = checkused(candidate) while existing: candidate = name[:maxlength - len(str(counter))] + str(counter) counter += 1 existing = checkused(candidate) return candidate
python
def make_name(text, delim=u'-', maxlength=50, checkused=None, counter=2): u""" Generate an ASCII name slug. If a checkused filter is provided, it will be called with the candidate. If it returns True, make_name will add counter numbers starting from 2 until a suitable candidate is found. :param string delim: Delimiter between words, default '-' :param int maxlength: Maximum length of name, default 50 :param checkused: Function to check if a generated name is available for use :param int counter: Starting position for name counter >>> make_name('This is a title') 'this-is-a-title' >>> make_name('Invalid URL/slug here') 'invalid-url-slug-here' >>> make_name('this.that') 'this-that' >>> make_name('this:that') 'this-that' >>> make_name("How 'bout this?") 'how-bout-this' >>> make_name(u"How’s that?") 'hows-that' >>> make_name(u'K & D') 'k-d' >>> make_name('billion+ pageviews') 'billion-pageviews' >>> make_name(u'हिन्दी slug!') 'hindii-slug' >>> make_name(u'Your webapps should talk not just in English, but in español, Kiswahili, 廣州話 and অসমীয়া too.', maxlength=250) u'your-webapps-should-talk-not-just-in-english-but-in-espanol-kiswahili-guang-zhou-hua-and-asmiiyaa-too' >>> make_name(u'__name__', delim=u'_') 'name' >>> make_name(u'how_about_this', delim=u'_') 'how_about_this' >>> make_name(u'and-that', delim=u'_') 'and_that' >>> make_name(u'Umlauts in Mötörhead') 'umlauts-in-motorhead' >>> make_name('Candidate', checkused=lambda c: c in ['candidate']) 'candidate2' >>> make_name('Candidate', checkused=lambda c: c in ['candidate'], counter=1) 'candidate1' >>> make_name('Candidate', checkused=lambda c: c in ['candidate', 'candidate1', 'candidate2'], counter=1) 'candidate3' >>> make_name('Long title, but snipped', maxlength=20) 'long-title-but-snipp' >>> len(make_name('Long title, but snipped', maxlength=20)) 20 >>> make_name('Long candidate', maxlength=10, checkused=lambda c: c in ['long-candi', 'long-cand1']) 'long-cand2' >>> make_name(u'Lǝnkǝran') 'lankaran' >>> make_name(u'example@example.com') 'example-example-com' >>> make_name('trailing-delimiter', maxlength=10) 'trailing-d' >>> make_name('trailing-delimiter', maxlength=9) 'trailing' >>> make_name('''test this ... newline''') 'test-this-newline' >>> make_name(u"testing an emoji😁") u'testing-an-emoji' >>> make_name('''testing\\t\\nmore\\r\\nslashes''') 'testing-more-slashes' >>> make_name('What if a HTML <tag/>') 'what-if-a-html-tag' >>> make_name('These are equivalent to \\x01 through \\x1A') 'these-are-equivalent-to-through' """ name = text.replace('@', delim) name = unidecode(name).replace('@', 'a') # We don't know why unidecode uses '@' for 'a'-like chars name = six.text_type(delim.join([_strip_re.sub('', x) for x in _punctuation_re.split(name.lower()) if x != ''])) if isinstance(text, six.text_type): # Unidecode returns str. Restore to a unicode string if original was unicode name = six.text_type(name) candidate = name[:maxlength] if candidate.endswith(delim): candidate = candidate[:-1] if checkused is None: return candidate existing = checkused(candidate) while existing: candidate = name[:maxlength - len(str(counter))] + str(counter) counter += 1 existing = checkused(candidate) return candidate
[ "def", "make_name", "(", "text", ",", "delim", "=", "u'-'", ",", "maxlength", "=", "50", ",", "checkused", "=", "None", ",", "counter", "=", "2", ")", ":", "name", "=", "text", ".", "replace", "(", "'@'", ",", "delim", ")", "name", "=", "unidecode"...
u""" Generate an ASCII name slug. If a checkused filter is provided, it will be called with the candidate. If it returns True, make_name will add counter numbers starting from 2 until a suitable candidate is found. :param string delim: Delimiter between words, default '-' :param int maxlength: Maximum length of name, default 50 :param checkused: Function to check if a generated name is available for use :param int counter: Starting position for name counter >>> make_name('This is a title') 'this-is-a-title' >>> make_name('Invalid URL/slug here') 'invalid-url-slug-here' >>> make_name('this.that') 'this-that' >>> make_name('this:that') 'this-that' >>> make_name("How 'bout this?") 'how-bout-this' >>> make_name(u"How’s that?") 'hows-that' >>> make_name(u'K & D') 'k-d' >>> make_name('billion+ pageviews') 'billion-pageviews' >>> make_name(u'हिन्दी slug!') 'hindii-slug' >>> make_name(u'Your webapps should talk not just in English, but in español, Kiswahili, 廣州話 and অসমীয়া too.', maxlength=250) u'your-webapps-should-talk-not-just-in-english-but-in-espanol-kiswahili-guang-zhou-hua-and-asmiiyaa-too' >>> make_name(u'__name__', delim=u'_') 'name' >>> make_name(u'how_about_this', delim=u'_') 'how_about_this' >>> make_name(u'and-that', delim=u'_') 'and_that' >>> make_name(u'Umlauts in Mötörhead') 'umlauts-in-motorhead' >>> make_name('Candidate', checkused=lambda c: c in ['candidate']) 'candidate2' >>> make_name('Candidate', checkused=lambda c: c in ['candidate'], counter=1) 'candidate1' >>> make_name('Candidate', checkused=lambda c: c in ['candidate', 'candidate1', 'candidate2'], counter=1) 'candidate3' >>> make_name('Long title, but snipped', maxlength=20) 'long-title-but-snipp' >>> len(make_name('Long title, but snipped', maxlength=20)) 20 >>> make_name('Long candidate', maxlength=10, checkused=lambda c: c in ['long-candi', 'long-cand1']) 'long-cand2' >>> make_name(u'Lǝnkǝran') 'lankaran' >>> make_name(u'example@example.com') 'example-example-com' >>> make_name('trailing-delimiter', maxlength=10) 'trailing-d' >>> make_name('trailing-delimiter', maxlength=9) 'trailing' >>> make_name('''test this ... newline''') 'test-this-newline' >>> make_name(u"testing an emoji😁") u'testing-an-emoji' >>> make_name('''testing\\t\\nmore\\r\\nslashes''') 'testing-more-slashes' >>> make_name('What if a HTML <tag/>') 'what-if-a-html-tag' >>> make_name('These are equivalent to \\x01 through \\x1A') 'these-are-equivalent-to-through'
[ "u", "Generate", "an", "ASCII", "name", "slug", ".", "If", "a", "checkused", "filter", "is", "provided", "it", "will", "be", "called", "with", "the", "candidate", ".", "If", "it", "returns", "True", "make_name", "will", "add", "counter", "numbers", "starti...
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L204-L291
9,858
hasgeek/coaster
coaster/utils/misc.py
check_password
def check_password(reference, attempt): """ Compare a reference password with the user attempt. >>> check_password('{PLAIN}foo', 'foo') True >>> check_password(u'{PLAIN}bar', 'bar') True >>> check_password(u'{UNKNOWN}baz', 'baz') False >>> check_password(u'no-encoding', u'no-encoding') False >>> check_password(u'{SSHA}q/uVU8r15k/9QhRi92CWUwMJu2DM6TUSpp25', u're-foo') True >>> check_password(u'{BCRYPT}$2b$12$NfKivgz7njR3/rWZ56EsDe7..PPum.fcmFLbdkbP.chtMTcS1s01C', 'foo') True """ if reference.startswith(u'{PLAIN}'): if reference[7:] == attempt: return True elif reference.startswith(u'{SSHA}'): # In python3 b64decode takes inputtype as bytes as opposed to str in python 2, and returns # binascii.Error as opposed to TypeError if six.PY3: # pragma: no cover try: if isinstance(reference, six.text_type): ref = b64decode(reference[6:].encode('utf-8')) else: ref = b64decode(reference[6:]) except binascii.Error: return False # Not Base64 else: # pragma: no cover try: ref = b64decode(reference[6:]) except TypeError: return False # Not Base64 if isinstance(attempt, six.text_type): attempt = attempt.encode('utf-8') salt = ref[20:] b64_encoded = b64encode(hashlib.sha1(attempt + salt).digest() + salt) if six.PY3: # pragma: no cover # type(b64_encoded) is bytes and can't be compared with type(reference) which is str compare = six.text_type('{SSHA}%s' % b64_encoded.decode('utf-8') if type(b64_encoded) is bytes else b64_encoded) else: # pragma: no cover compare = six.text_type('{SSHA}%s' % b64_encoded) return compare == reference elif reference.startswith(u'{BCRYPT}'): # bcrypt.hashpw() accepts either a unicode encoded string or the basic string (python 2) if isinstance(attempt, six.text_type) or isinstance(reference, six.text_type): attempt = attempt.encode('utf-8') reference = reference.encode('utf-8') if six.PY3: # pragma: no cover return bcrypt.hashpw(attempt, reference[8:]) == reference[8:] else: # pragma: no cover return bcrypt.hashpw( attempt.encode('utf-8') if isinstance(attempt, six.text_type) else attempt, str(reference[8:])) == reference[8:] return False
python
def check_password(reference, attempt): if reference.startswith(u'{PLAIN}'): if reference[7:] == attempt: return True elif reference.startswith(u'{SSHA}'): # In python3 b64decode takes inputtype as bytes as opposed to str in python 2, and returns # binascii.Error as opposed to TypeError if six.PY3: # pragma: no cover try: if isinstance(reference, six.text_type): ref = b64decode(reference[6:].encode('utf-8')) else: ref = b64decode(reference[6:]) except binascii.Error: return False # Not Base64 else: # pragma: no cover try: ref = b64decode(reference[6:]) except TypeError: return False # Not Base64 if isinstance(attempt, six.text_type): attempt = attempt.encode('utf-8') salt = ref[20:] b64_encoded = b64encode(hashlib.sha1(attempt + salt).digest() + salt) if six.PY3: # pragma: no cover # type(b64_encoded) is bytes and can't be compared with type(reference) which is str compare = six.text_type('{SSHA}%s' % b64_encoded.decode('utf-8') if type(b64_encoded) is bytes else b64_encoded) else: # pragma: no cover compare = six.text_type('{SSHA}%s' % b64_encoded) return compare == reference elif reference.startswith(u'{BCRYPT}'): # bcrypt.hashpw() accepts either a unicode encoded string or the basic string (python 2) if isinstance(attempt, six.text_type) or isinstance(reference, six.text_type): attempt = attempt.encode('utf-8') reference = reference.encode('utf-8') if six.PY3: # pragma: no cover return bcrypt.hashpw(attempt, reference[8:]) == reference[8:] else: # pragma: no cover return bcrypt.hashpw( attempt.encode('utf-8') if isinstance(attempt, six.text_type) else attempt, str(reference[8:])) == reference[8:] return False
[ "def", "check_password", "(", "reference", ",", "attempt", ")", ":", "if", "reference", ".", "startswith", "(", "u'{PLAIN}'", ")", ":", "if", "reference", "[", "7", ":", "]", "==", "attempt", ":", "return", "True", "elif", "reference", ".", "startswith", ...
Compare a reference password with the user attempt. >>> check_password('{PLAIN}foo', 'foo') True >>> check_password(u'{PLAIN}bar', 'bar') True >>> check_password(u'{UNKNOWN}baz', 'baz') False >>> check_password(u'no-encoding', u'no-encoding') False >>> check_password(u'{SSHA}q/uVU8r15k/9QhRi92CWUwMJu2DM6TUSpp25', u're-foo') True >>> check_password(u'{BCRYPT}$2b$12$NfKivgz7njR3/rWZ56EsDe7..PPum.fcmFLbdkbP.chtMTcS1s01C', 'foo') True
[ "Compare", "a", "reference", "password", "with", "the", "user", "attempt", "." ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L341-L398
9,859
hasgeek/coaster
coaster/utils/misc.py
format_currency
def format_currency(value, decimals=2): """ Return a number suitably formatted for display as currency, with thousands separated by commas and up to two decimal points. >>> format_currency(1000) '1,000' >>> format_currency(100) '100' >>> format_currency(999.95) '999.95' >>> format_currency(99.95) '99.95' >>> format_currency(100000) '100,000' >>> format_currency(1000.00) '1,000' >>> format_currency(1000.41) '1,000.41' >>> format_currency(23.21, decimals=3) '23.210' >>> format_currency(1000, decimals=3) '1,000' >>> format_currency(123456789.123456789) '123,456,789.12' """ number, decimal = ((u'%%.%df' % decimals) % value).split(u'.') parts = [] while len(number) > 3: part, number = number[-3:], number[:-3] parts.append(part) parts.append(number) parts.reverse() if int(decimal) == 0: return u','.join(parts) else: return u','.join(parts) + u'.' + decimal
python
def format_currency(value, decimals=2): number, decimal = ((u'%%.%df' % decimals) % value).split(u'.') parts = [] while len(number) > 3: part, number = number[-3:], number[:-3] parts.append(part) parts.append(number) parts.reverse() if int(decimal) == 0: return u','.join(parts) else: return u','.join(parts) + u'.' + decimal
[ "def", "format_currency", "(", "value", ",", "decimals", "=", "2", ")", ":", "number", ",", "decimal", "=", "(", "(", "u'%%.%df'", "%", "decimals", ")", "%", "value", ")", ".", "split", "(", "u'.'", ")", "parts", "=", "[", "]", "while", "len", "(",...
Return a number suitably formatted for display as currency, with thousands separated by commas and up to two decimal points. >>> format_currency(1000) '1,000' >>> format_currency(100) '100' >>> format_currency(999.95) '999.95' >>> format_currency(99.95) '99.95' >>> format_currency(100000) '100,000' >>> format_currency(1000.00) '1,000' >>> format_currency(1000.41) '1,000.41' >>> format_currency(23.21, decimals=3) '23.210' >>> format_currency(1000, decimals=3) '1,000' >>> format_currency(123456789.123456789) '123,456,789.12'
[ "Return", "a", "number", "suitably", "formatted", "for", "display", "as", "currency", "with", "thousands", "separated", "by", "commas", "and", "up", "to", "two", "decimal", "points", "." ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L401-L437
9,860
hasgeek/coaster
coaster/utils/misc.py
md5sum
def md5sum(data): """ Return md5sum of data as a 32-character string. >>> md5sum('random text') 'd9b9bec3f4cc5482e7c5ef43143e563a' >>> md5sum(u'random text') 'd9b9bec3f4cc5482e7c5ef43143e563a' >>> len(md5sum('random text')) 32 """ if six.PY3: # pragma: no cover return hashlib.md5(data.encode('utf-8')).hexdigest() else: # pragma: no cover return hashlib.md5(data).hexdigest()
python
def md5sum(data): if six.PY3: # pragma: no cover return hashlib.md5(data.encode('utf-8')).hexdigest() else: # pragma: no cover return hashlib.md5(data).hexdigest()
[ "def", "md5sum", "(", "data", ")", ":", "if", "six", ".", "PY3", ":", "# pragma: no cover", "return", "hashlib", ".", "md5", "(", "data", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdigest", "(", ")", "else", ":", "# pragma: no cover", "return", ...
Return md5sum of data as a 32-character string. >>> md5sum('random text') 'd9b9bec3f4cc5482e7c5ef43143e563a' >>> md5sum(u'random text') 'd9b9bec3f4cc5482e7c5ef43143e563a' >>> len(md5sum('random text')) 32
[ "Return", "md5sum", "of", "data", "as", "a", "32", "-", "character", "string", "." ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L440-L454
9,861
hasgeek/coaster
coaster/utils/misc.py
midnight_to_utc
def midnight_to_utc(dt, timezone=None, naive=False): """ Returns a UTC datetime matching the midnight for the given date or datetime. >>> from datetime import date >>> midnight_to_utc(datetime(2017, 1, 1)) datetime.datetime(2017, 1, 1, 0, 0, tzinfo=<UTC>) >>> midnight_to_utc(pytz.timezone('Asia/Kolkata').localize(datetime(2017, 1, 1))) datetime.datetime(2016, 12, 31, 18, 30, tzinfo=<UTC>) >>> midnight_to_utc(datetime(2017, 1, 1), naive=True) datetime.datetime(2017, 1, 1, 0, 0) >>> midnight_to_utc(pytz.timezone('Asia/Kolkata').localize(datetime(2017, 1, 1)), naive=True) datetime.datetime(2016, 12, 31, 18, 30) >>> midnight_to_utc(date(2017, 1, 1)) datetime.datetime(2017, 1, 1, 0, 0, tzinfo=<UTC>) >>> midnight_to_utc(date(2017, 1, 1), naive=True) datetime.datetime(2017, 1, 1, 0, 0) >>> midnight_to_utc(date(2017, 1, 1), timezone='Asia/Kolkata') datetime.datetime(2016, 12, 31, 18, 30, tzinfo=<UTC>) >>> midnight_to_utc(datetime(2017, 1, 1), timezone='Asia/Kolkata') datetime.datetime(2016, 12, 31, 18, 30, tzinfo=<UTC>) >>> midnight_to_utc(pytz.timezone('Asia/Kolkata').localize(datetime(2017, 1, 1)), timezone='UTC') datetime.datetime(2017, 1, 1, 0, 0, tzinfo=<UTC>) """ if timezone: if isinstance(timezone, six.string_types): tz = pytz.timezone(timezone) else: tz = timezone elif isinstance(dt, datetime) and dt.tzinfo: tz = dt.tzinfo else: tz = pytz.UTC utc_dt = tz.localize(datetime.combine(dt, datetime.min.time())).astimezone(pytz.UTC) if naive: return utc_dt.replace(tzinfo=None) return utc_dt
python
def midnight_to_utc(dt, timezone=None, naive=False): if timezone: if isinstance(timezone, six.string_types): tz = pytz.timezone(timezone) else: tz = timezone elif isinstance(dt, datetime) and dt.tzinfo: tz = dt.tzinfo else: tz = pytz.UTC utc_dt = tz.localize(datetime.combine(dt, datetime.min.time())).astimezone(pytz.UTC) if naive: return utc_dt.replace(tzinfo=None) return utc_dt
[ "def", "midnight_to_utc", "(", "dt", ",", "timezone", "=", "None", ",", "naive", "=", "False", ")", ":", "if", "timezone", ":", "if", "isinstance", "(", "timezone", ",", "six", ".", "string_types", ")", ":", "tz", "=", "pytz", ".", "timezone", "(", "...
Returns a UTC datetime matching the midnight for the given date or datetime. >>> from datetime import date >>> midnight_to_utc(datetime(2017, 1, 1)) datetime.datetime(2017, 1, 1, 0, 0, tzinfo=<UTC>) >>> midnight_to_utc(pytz.timezone('Asia/Kolkata').localize(datetime(2017, 1, 1))) datetime.datetime(2016, 12, 31, 18, 30, tzinfo=<UTC>) >>> midnight_to_utc(datetime(2017, 1, 1), naive=True) datetime.datetime(2017, 1, 1, 0, 0) >>> midnight_to_utc(pytz.timezone('Asia/Kolkata').localize(datetime(2017, 1, 1)), naive=True) datetime.datetime(2016, 12, 31, 18, 30) >>> midnight_to_utc(date(2017, 1, 1)) datetime.datetime(2017, 1, 1, 0, 0, tzinfo=<UTC>) >>> midnight_to_utc(date(2017, 1, 1), naive=True) datetime.datetime(2017, 1, 1, 0, 0) >>> midnight_to_utc(date(2017, 1, 1), timezone='Asia/Kolkata') datetime.datetime(2016, 12, 31, 18, 30, tzinfo=<UTC>) >>> midnight_to_utc(datetime(2017, 1, 1), timezone='Asia/Kolkata') datetime.datetime(2016, 12, 31, 18, 30, tzinfo=<UTC>) >>> midnight_to_utc(pytz.timezone('Asia/Kolkata').localize(datetime(2017, 1, 1)), timezone='UTC') datetime.datetime(2017, 1, 1, 0, 0, tzinfo=<UTC>)
[ "Returns", "a", "UTC", "datetime", "matching", "the", "midnight", "for", "the", "given", "date", "or", "datetime", "." ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L491-L528
9,862
hasgeek/coaster
coaster/utils/misc.py
getbool
def getbool(value): """ Returns a boolean from any of a range of values. Returns None for unrecognized values. Numbers other than 0 and 1 are considered unrecognized. >>> getbool(True) True >>> getbool(1) True >>> getbool('1') True >>> getbool('t') True >>> getbool(2) >>> getbool(0) False >>> getbool(False) False >>> getbool('n') False """ value = str(value).lower() if value in ['1', 't', 'true', 'y', 'yes']: return True elif value in ['0', 'f', 'false', 'n', 'no']: return False return None
python
def getbool(value): value = str(value).lower() if value in ['1', 't', 'true', 'y', 'yes']: return True elif value in ['0', 'f', 'false', 'n', 'no']: return False return None
[ "def", "getbool", "(", "value", ")", ":", "value", "=", "str", "(", "value", ")", ".", "lower", "(", ")", "if", "value", "in", "[", "'1'", ",", "'t'", ",", "'true'", ",", "'y'", ",", "'yes'", "]", ":", "return", "True", "elif", "value", "in", "...
Returns a boolean from any of a range of values. Returns None for unrecognized values. Numbers other than 0 and 1 are considered unrecognized. >>> getbool(True) True >>> getbool(1) True >>> getbool('1') True >>> getbool('t') True >>> getbool(2) >>> getbool(0) False >>> getbool(False) False >>> getbool('n') False
[ "Returns", "a", "boolean", "from", "any", "of", "a", "range", "of", "values", ".", "Returns", "None", "for", "unrecognized", "values", ".", "Numbers", "other", "than", "0", "and", "1", "are", "considered", "unrecognized", "." ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L531-L558
9,863
hasgeek/coaster
coaster/utils/misc.py
unicode_http_header
def unicode_http_header(value): r""" Convert an ASCII HTTP header string into a unicode string with the appropriate encoding applied. Expects headers to be RFC 2047 compliant. >>> unicode_http_header('=?iso-8859-1?q?p=F6stal?=') == u'p\xf6stal' True >>> unicode_http_header(b'=?iso-8859-1?q?p=F6stal?=') == u'p\xf6stal' True >>> unicode_http_header('p\xf6stal') == u'p\xf6stal' True """ if six.PY3: # pragma: no cover # email.header.decode_header expects strings, not bytes. Your input data may be in bytes. # Since these bytes are almost always ASCII, calling `.decode()` on it without specifying # a charset should work fine. if isinstance(value, six.binary_type): value = value.decode() return u''.join([six.text_type(s, e or 'iso-8859-1') if not isinstance(s, six.text_type) else s for s, e in decode_header(value)])
python
def unicode_http_header(value): r""" Convert an ASCII HTTP header string into a unicode string with the appropriate encoding applied. Expects headers to be RFC 2047 compliant. >>> unicode_http_header('=?iso-8859-1?q?p=F6stal?=') == u'p\xf6stal' True >>> unicode_http_header(b'=?iso-8859-1?q?p=F6stal?=') == u'p\xf6stal' True >>> unicode_http_header('p\xf6stal') == u'p\xf6stal' True """ if six.PY3: # pragma: no cover # email.header.decode_header expects strings, not bytes. Your input data may be in bytes. # Since these bytes are almost always ASCII, calling `.decode()` on it without specifying # a charset should work fine. if isinstance(value, six.binary_type): value = value.decode() return u''.join([six.text_type(s, e or 'iso-8859-1') if not isinstance(s, six.text_type) else s for s, e in decode_header(value)])
[ "def", "unicode_http_header", "(", "value", ")", ":", "if", "six", ".", "PY3", ":", "# pragma: no cover", "# email.header.decode_header expects strings, not bytes. Your input data may be in bytes.", "# Since these bytes are almost always ASCII, calling `.decode()` on it without specifying"...
r""" Convert an ASCII HTTP header string into a unicode string with the appropriate encoding applied. Expects headers to be RFC 2047 compliant. >>> unicode_http_header('=?iso-8859-1?q?p=F6stal?=') == u'p\xf6stal' True >>> unicode_http_header(b'=?iso-8859-1?q?p=F6stal?=') == u'p\xf6stal' True >>> unicode_http_header('p\xf6stal') == u'p\xf6stal' True
[ "r", "Convert", "an", "ASCII", "HTTP", "header", "string", "into", "a", "unicode", "string", "with", "the", "appropriate", "encoding", "applied", ".", "Expects", "headers", "to", "be", "RFC", "2047", "compliant", "." ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L645-L664
9,864
hasgeek/coaster
coaster/utils/misc.py
get_email_domain
def get_email_domain(emailaddr): """ Return the domain component of an email address. Returns None if the provided string cannot be parsed as an email address. >>> get_email_domain('test@example.com') 'example.com' >>> get_email_domain('test+trailing@example.com') 'example.com' >>> get_email_domain('Example Address <test@example.com>') 'example.com' >>> get_email_domain('foobar') >>> get_email_domain('foo@bar@baz') 'bar' >>> get_email_domain('foobar@') >>> get_email_domain('@foobar') """ realname, address = email.utils.parseaddr(emailaddr) try: username, domain = address.split('@') if not username: return None return domain or None except ValueError: return None
python
def get_email_domain(emailaddr): realname, address = email.utils.parseaddr(emailaddr) try: username, domain = address.split('@') if not username: return None return domain or None except ValueError: return None
[ "def", "get_email_domain", "(", "emailaddr", ")", ":", "realname", ",", "address", "=", "email", ".", "utils", ".", "parseaddr", "(", "emailaddr", ")", "try", ":", "username", ",", "domain", "=", "address", ".", "split", "(", "'@'", ")", "if", "not", "...
Return the domain component of an email address. Returns None if the provided string cannot be parsed as an email address. >>> get_email_domain('test@example.com') 'example.com' >>> get_email_domain('test+trailing@example.com') 'example.com' >>> get_email_domain('Example Address <test@example.com>') 'example.com' >>> get_email_domain('foobar') >>> get_email_domain('foo@bar@baz') 'bar' >>> get_email_domain('foobar@') >>> get_email_domain('@foobar')
[ "Return", "the", "domain", "component", "of", "an", "email", "address", ".", "Returns", "None", "if", "the", "provided", "string", "cannot", "be", "parsed", "as", "an", "email", "address", "." ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L667-L691
9,865
hasgeek/coaster
coaster/utils/misc.py
sorted_timezones
def sorted_timezones(): """ Return a list of timezones sorted by offset from UTC. """ def hourmin(delta): if delta.days < 0: hours, remaining = divmod(86400 - delta.seconds, 3600) else: hours, remaining = divmod(delta.seconds, 3600) minutes, remaining = divmod(remaining, 60) return hours, minutes now = datetime.utcnow() # Make a list of country code mappings timezone_country = {} for countrycode in pytz.country_timezones: for timezone in pytz.country_timezones[countrycode]: timezone_country[timezone] = countrycode # Make a list of timezones, discarding the US/* and Canada/* zones since they aren't reliable for # DST, and discarding UTC and GMT since timezones in that zone have their own names timezones = [(pytz.timezone(tzname).utcoffset(now, is_dst=False), tzname) for tzname in pytz.common_timezones if not tzname.startswith('US/') and not tzname.startswith('Canada/') and tzname not in ('GMT', 'UTC')] # Sort timezones by offset from UTC and their human-readable name presorted = [(delta, '%s%s - %s%s (%s)' % ( (delta.days < 0 and '-') or (delta.days == 0 and delta.seconds == 0 and ' ') or '+', '%02d:%02d' % hourmin(delta), (pytz.country_names[timezone_country[name]] + ': ') if name in timezone_country else '', name.replace('_', ' '), pytz.timezone(name).tzname(now, is_dst=False)), name) for delta, name in timezones] presorted.sort() # Return a list of (timezone, label) with the timezone offset included in the label. return [(name, label) for (delta, label, name) in presorted]
python
def sorted_timezones(): def hourmin(delta): if delta.days < 0: hours, remaining = divmod(86400 - delta.seconds, 3600) else: hours, remaining = divmod(delta.seconds, 3600) minutes, remaining = divmod(remaining, 60) return hours, minutes now = datetime.utcnow() # Make a list of country code mappings timezone_country = {} for countrycode in pytz.country_timezones: for timezone in pytz.country_timezones[countrycode]: timezone_country[timezone] = countrycode # Make a list of timezones, discarding the US/* and Canada/* zones since they aren't reliable for # DST, and discarding UTC and GMT since timezones in that zone have their own names timezones = [(pytz.timezone(tzname).utcoffset(now, is_dst=False), tzname) for tzname in pytz.common_timezones if not tzname.startswith('US/') and not tzname.startswith('Canada/') and tzname not in ('GMT', 'UTC')] # Sort timezones by offset from UTC and their human-readable name presorted = [(delta, '%s%s - %s%s (%s)' % ( (delta.days < 0 and '-') or (delta.days == 0 and delta.seconds == 0 and ' ') or '+', '%02d:%02d' % hourmin(delta), (pytz.country_names[timezone_country[name]] + ': ') if name in timezone_country else '', name.replace('_', ' '), pytz.timezone(name).tzname(now, is_dst=False)), name) for delta, name in timezones] presorted.sort() # Return a list of (timezone, label) with the timezone offset included in the label. return [(name, label) for (delta, label, name) in presorted]
[ "def", "sorted_timezones", "(", ")", ":", "def", "hourmin", "(", "delta", ")", ":", "if", "delta", ".", "days", "<", "0", ":", "hours", ",", "remaining", "=", "divmod", "(", "86400", "-", "delta", ".", "seconds", ",", "3600", ")", "else", ":", "hou...
Return a list of timezones sorted by offset from UTC.
[ "Return", "a", "list", "of", "timezones", "sorted", "by", "offset", "from", "UTC", "." ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L714-L746
9,866
hasgeek/coaster
coaster/utils/misc.py
namespace_from_url
def namespace_from_url(url): """ Construct a dotted namespace string from a URL. """ parsed = urlparse(url) if parsed.hostname is None or parsed.hostname in ['localhost', 'localhost.localdomain'] or ( _ipv4_re.search(parsed.hostname)): return None namespace = parsed.hostname.split('.') namespace.reverse() if namespace and not namespace[0]: namespace.pop(0) if namespace and namespace[-1] == 'www': namespace.pop(-1) return type(url)('.'.join(namespace))
python
def namespace_from_url(url): parsed = urlparse(url) if parsed.hostname is None or parsed.hostname in ['localhost', 'localhost.localdomain'] or ( _ipv4_re.search(parsed.hostname)): return None namespace = parsed.hostname.split('.') namespace.reverse() if namespace and not namespace[0]: namespace.pop(0) if namespace and namespace[-1] == 'www': namespace.pop(-1) return type(url)('.'.join(namespace))
[ "def", "namespace_from_url", "(", "url", ")", ":", "parsed", "=", "urlparse", "(", "url", ")", "if", "parsed", ".", "hostname", "is", "None", "or", "parsed", ".", "hostname", "in", "[", "'localhost'", ",", "'localhost.localdomain'", "]", "or", "(", "_ipv4_...
Construct a dotted namespace string from a URL.
[ "Construct", "a", "dotted", "namespace", "string", "from", "a", "URL", "." ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L749-L764
9,867
hasgeek/coaster
coaster/utils/misc.py
base_domain_matches
def base_domain_matches(d1, d2): """ Check if two domains have the same base domain, using the Public Suffix List. >>> base_domain_matches('https://hasjob.co', 'hasjob.co') True >>> base_domain_matches('hasgeek.hasjob.co', 'hasjob.co') True >>> base_domain_matches('hasgeek.com', 'hasjob.co') False >>> base_domain_matches('static.hasgeek.co.in', 'hasgeek.com') False >>> base_domain_matches('static.hasgeek.co.in', 'hasgeek.co.in') True >>> base_domain_matches('example@example.com', 'example.com') True """ r1 = tldextract.extract(d1) r2 = tldextract.extract(d2) # r1 and r2 contain subdomain, domain and suffix. # We want to confirm that domain and suffix match. return r1.domain == r2.domain and r1.suffix == r2.suffix
python
def base_domain_matches(d1, d2): r1 = tldextract.extract(d1) r2 = tldextract.extract(d2) # r1 and r2 contain subdomain, domain and suffix. # We want to confirm that domain and suffix match. return r1.domain == r2.domain and r1.suffix == r2.suffix
[ "def", "base_domain_matches", "(", "d1", ",", "d2", ")", ":", "r1", "=", "tldextract", ".", "extract", "(", "d1", ")", "r2", "=", "tldextract", ".", "extract", "(", "d2", ")", "# r1 and r2 contain subdomain, domain and suffix.", "# We want to confirm that domain and...
Check if two domains have the same base domain, using the Public Suffix List. >>> base_domain_matches('https://hasjob.co', 'hasjob.co') True >>> base_domain_matches('hasgeek.hasjob.co', 'hasjob.co') True >>> base_domain_matches('hasgeek.com', 'hasjob.co') False >>> base_domain_matches('static.hasgeek.co.in', 'hasgeek.com') False >>> base_domain_matches('static.hasgeek.co.in', 'hasgeek.co.in') True >>> base_domain_matches('example@example.com', 'example.com') True
[ "Check", "if", "two", "domains", "have", "the", "same", "base", "domain", "using", "the", "Public", "Suffix", "List", "." ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L767-L788
9,868
hasgeek/coaster
coaster/sqlalchemy/columns.py
MarkdownColumn
def MarkdownColumn(name, deferred=False, group=None, **kwargs): """ Create a composite column that autogenerates HTML from Markdown text, storing data in db columns named with ``_html`` and ``_text`` prefixes. """ return composite(MarkdownComposite, Column(name + '_text', UnicodeText, **kwargs), Column(name + '_html', UnicodeText, **kwargs), deferred=deferred, group=group or name )
python
def MarkdownColumn(name, deferred=False, group=None, **kwargs): return composite(MarkdownComposite, Column(name + '_text', UnicodeText, **kwargs), Column(name + '_html', UnicodeText, **kwargs), deferred=deferred, group=group or name )
[ "def", "MarkdownColumn", "(", "name", ",", "deferred", "=", "False", ",", "group", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "composite", "(", "MarkdownComposite", ",", "Column", "(", "name", "+", "'_text'", ",", "UnicodeText", ",", "*", ...
Create a composite column that autogenerates HTML from Markdown text, storing data in db columns named with ``_html`` and ``_text`` prefixes.
[ "Create", "a", "composite", "column", "that", "autogenerates", "HTML", "from", "Markdown", "text", "storing", "data", "in", "db", "columns", "named", "with", "_html", "and", "_text", "prefixes", "." ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/columns.py#L177-L186
9,869
hasgeek/coaster
coaster/assets.py
VersionedAssets.require
def require(self, *namespecs): """Return a bundle of the requested assets and their dependencies.""" blacklist = set([n[1:] for n in namespecs if n.startswith('!')]) not_blacklist = [n for n in namespecs if not n.startswith('!')] return Bundle(*[bundle for name, version, bundle in self._require_recursive(*not_blacklist) if name not in blacklist])
python
def require(self, *namespecs): blacklist = set([n[1:] for n in namespecs if n.startswith('!')]) not_blacklist = [n for n in namespecs if not n.startswith('!')] return Bundle(*[bundle for name, version, bundle in self._require_recursive(*not_blacklist) if name not in blacklist])
[ "def", "require", "(", "self", ",", "*", "namespecs", ")", ":", "blacklist", "=", "set", "(", "[", "n", "[", "1", ":", "]", "for", "n", "in", "namespecs", "if", "n", ".", "startswith", "(", "'!'", ")", "]", ")", "not_blacklist", "=", "[", "n", ...
Return a bundle of the requested assets and their dependencies.
[ "Return", "a", "bundle", "of", "the", "requested", "assets", "and", "their", "dependencies", "." ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/assets.py#L165-L170
9,870
hasgeek/coaster
coaster/sqlalchemy/statemanager.py
StateTransitionWrapper._state_invalid
def _state_invalid(self): """ If the state is invalid for the transition, return details on what didn't match :return: Tuple of (state manager, current state, label for current state) """ for statemanager, conditions in self.statetransition.transitions.items(): current_state = getattr(self.obj, statemanager.propname) if conditions['from'] is None: state_valid = True else: mstate = conditions['from'].get(current_state) state_valid = mstate and mstate(self.obj) if state_valid and conditions['if']: state_valid = all(v(self.obj) for v in conditions['if']) if not state_valid: return statemanager, current_state, statemanager.lenum.get(current_state)
python
def _state_invalid(self): for statemanager, conditions in self.statetransition.transitions.items(): current_state = getattr(self.obj, statemanager.propname) if conditions['from'] is None: state_valid = True else: mstate = conditions['from'].get(current_state) state_valid = mstate and mstate(self.obj) if state_valid and conditions['if']: state_valid = all(v(self.obj) for v in conditions['if']) if not state_valid: return statemanager, current_state, statemanager.lenum.get(current_state)
[ "def", "_state_invalid", "(", "self", ")", ":", "for", "statemanager", ",", "conditions", "in", "self", ".", "statetransition", ".", "transitions", ".", "items", "(", ")", ":", "current_state", "=", "getattr", "(", "self", ".", "obj", ",", "statemanager", ...
If the state is invalid for the transition, return details on what didn't match :return: Tuple of (state manager, current state, label for current state)
[ "If", "the", "state", "is", "invalid", "for", "the", "transition", "return", "details", "on", "what", "didn", "t", "match" ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/statemanager.py#L538-L554
9,871
hasgeek/coaster
coaster/sqlalchemy/statemanager.py
StateManager.add_conditional_state
def add_conditional_state(self, name, state, validator, class_validator=None, cache_for=None, label=None): """ Add a conditional state that combines an existing state with a validator that must also pass. The validator receives the object on which the property is present as a parameter. :param str name: Name of the new state :param ManagedState state: Existing state that this is based on :param validator: Function that will be called with the host object as a parameter :param class_validator: Function that will be called when the state is queried on the class instead of the instance. Falls back to ``validator`` if not specified. Receives the class as the parameter :param cache_for: Integer or function that indicates how long ``validator``'s result can be cached (not applicable to ``class_validator``). ``None`` implies no cache, ``0`` implies indefinite cache (until invalidated by a transition) and any other integer is the number of seconds for which to cache the assertion :param label: Label for this state (string or 2-tuple) TODO: `cache_for`'s implementation is currently pending a test case demonstrating how it will be used. """ # We'll accept a ManagedState with grouped values, but not a ManagedStateGroup if not isinstance(state, ManagedState): raise TypeError("Not a managed state: %s" % repr(state)) elif state.statemanager != self: raise ValueError("State %s is not associated with this state manager" % repr(state)) if isinstance(label, tuple) and len(label) == 2: label = NameTitle(*label) self._add_state_internal(name, state.value, label=label, validator=validator, class_validator=class_validator, cache_for=cache_for)
python
def add_conditional_state(self, name, state, validator, class_validator=None, cache_for=None, label=None): # We'll accept a ManagedState with grouped values, but not a ManagedStateGroup if not isinstance(state, ManagedState): raise TypeError("Not a managed state: %s" % repr(state)) elif state.statemanager != self: raise ValueError("State %s is not associated with this state manager" % repr(state)) if isinstance(label, tuple) and len(label) == 2: label = NameTitle(*label) self._add_state_internal(name, state.value, label=label, validator=validator, class_validator=class_validator, cache_for=cache_for)
[ "def", "add_conditional_state", "(", "self", ",", "name", ",", "state", ",", "validator", ",", "class_validator", "=", "None", ",", "cache_for", "=", "None", ",", "label", "=", "None", ")", ":", "# We'll accept a ManagedState with grouped values, but not a ManagedStat...
Add a conditional state that combines an existing state with a validator that must also pass. The validator receives the object on which the property is present as a parameter. :param str name: Name of the new state :param ManagedState state: Existing state that this is based on :param validator: Function that will be called with the host object as a parameter :param class_validator: Function that will be called when the state is queried on the class instead of the instance. Falls back to ``validator`` if not specified. Receives the class as the parameter :param cache_for: Integer or function that indicates how long ``validator``'s result can be cached (not applicable to ``class_validator``). ``None`` implies no cache, ``0`` implies indefinite cache (until invalidated by a transition) and any other integer is the number of seconds for which to cache the assertion :param label: Label for this state (string or 2-tuple) TODO: `cache_for`'s implementation is currently pending a test case demonstrating how it will be used.
[ "Add", "a", "conditional", "state", "that", "combines", "an", "existing", "state", "with", "a", "validator", "that", "must", "also", "pass", ".", "The", "validator", "receives", "the", "object", "on", "which", "the", "property", "is", "present", "as", "a", ...
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/statemanager.py#L709-L738
9,872
hasgeek/coaster
coaster/sqlalchemy/statemanager.py
StateManager.requires
def requires(self, from_, if_=None, **data): """ Decorates a method that may be called if the given state is currently active. Registers a transition internally, but does not change the state. :param from_: Required state to allow this call (can be a state group) :param if_: Validator(s) that, given the object, must all return True for the call to proceed :param data: Additional metadata, stored on the `StateTransition` object as a :attr:`data` attribute """ return self.transition(from_, None, if_, **data)
python
def requires(self, from_, if_=None, **data): return self.transition(from_, None, if_, **data)
[ "def", "requires", "(", "self", ",", "from_", ",", "if_", "=", "None", ",", "*", "*", "data", ")", ":", "return", "self", ".", "transition", "(", "from_", ",", "None", ",", "if_", ",", "*", "*", "data", ")" ]
Decorates a method that may be called if the given state is currently active. Registers a transition internally, but does not change the state. :param from_: Required state to allow this call (can be a state group) :param if_: Validator(s) that, given the object, must all return True for the call to proceed :param data: Additional metadata, stored on the `StateTransition` object as a :attr:`data` attribute
[ "Decorates", "a", "method", "that", "may", "be", "called", "if", "the", "given", "state", "is", "currently", "active", ".", "Registers", "a", "transition", "internally", "but", "does", "not", "change", "the", "state", "." ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/statemanager.py#L765-L774
9,873
hasgeek/coaster
coaster/sqlalchemy/statemanager.py
StateManagerWrapper.current
def current(self): """ All states and state groups that are currently active. """ if self.obj is not None: return {name: mstate(self.obj, self.cls) for name, mstate in self.statemanager.states.items() if mstate(self.obj, self.cls)}
python
def current(self): if self.obj is not None: return {name: mstate(self.obj, self.cls) for name, mstate in self.statemanager.states.items() if mstate(self.obj, self.cls)}
[ "def", "current", "(", "self", ")", ":", "if", "self", ".", "obj", "is", "not", "None", ":", "return", "{", "name", ":", "mstate", "(", "self", ".", "obj", ",", "self", ".", "cls", ")", "for", "name", ",", "mstate", "in", "self", ".", "statemanag...
All states and state groups that are currently active.
[ "All", "states", "and", "state", "groups", "that", "are", "currently", "active", "." ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/statemanager.py#L843-L850
9,874
hasgeek/coaster
coaster/gfm.py
gfm
def gfm(text): """ Prepare text for rendering by a regular Markdown processor. """ def indent_code(matchobj): syntax = matchobj.group(1) code = matchobj.group(2) if syntax: result = ' :::' + syntax + '\n' else: result = '' # The last line will be blank since it had the closing "```". Discard it # when indenting the lines. return result + '\n'.join([' ' + line for line in code.split('\n')[:-1]]) use_crlf = text.find('\r') != -1 if use_crlf: text = text.replace('\r\n', '\n') # Render GitHub-style ```code blocks``` into Markdown-style 4-space indented blocks text = CODEPATTERN_RE.sub(indent_code, text) text, code_blocks = remove_pre_blocks(text) text, inline_blocks = remove_inline_code_blocks(text) # Prevent foo_bar_baz from ending up with an italic word in the middle. def italic_callback(matchobj): s = matchobj.group(0) # don't mess with URLs: if 'http:' in s or 'https:' in s: return s return s.replace('_', r'\_') # fix italics for code blocks text = ITALICSPATTERN_RE.sub(italic_callback, text) # linkify naked URLs # wrap the URL in brackets: http://foo -> [http://foo](http://foo) text = NAKEDURL_RE.sub(r'\1[\2](\2)\3', text) # In very clear cases, let newlines become <br /> tags. def newline_callback(matchobj): if len(matchobj.group(1)) == 1: return matchobj.group(0).rstrip() + ' \n' else: return matchobj.group(0) text = NEWLINE_RE.sub(newline_callback, text) # now restore removed code blocks removed_blocks = code_blocks + inline_blocks for removed_block in removed_blocks: text = text.replace('{placeholder}', removed_block, 1) if use_crlf: text = text.replace('\n', '\r\n') return text
python
def gfm(text): def indent_code(matchobj): syntax = matchobj.group(1) code = matchobj.group(2) if syntax: result = ' :::' + syntax + '\n' else: result = '' # The last line will be blank since it had the closing "```". Discard it # when indenting the lines. return result + '\n'.join([' ' + line for line in code.split('\n')[:-1]]) use_crlf = text.find('\r') != -1 if use_crlf: text = text.replace('\r\n', '\n') # Render GitHub-style ```code blocks``` into Markdown-style 4-space indented blocks text = CODEPATTERN_RE.sub(indent_code, text) text, code_blocks = remove_pre_blocks(text) text, inline_blocks = remove_inline_code_blocks(text) # Prevent foo_bar_baz from ending up with an italic word in the middle. def italic_callback(matchobj): s = matchobj.group(0) # don't mess with URLs: if 'http:' in s or 'https:' in s: return s return s.replace('_', r'\_') # fix italics for code blocks text = ITALICSPATTERN_RE.sub(italic_callback, text) # linkify naked URLs # wrap the URL in brackets: http://foo -> [http://foo](http://foo) text = NAKEDURL_RE.sub(r'\1[\2](\2)\3', text) # In very clear cases, let newlines become <br /> tags. def newline_callback(matchobj): if len(matchobj.group(1)) == 1: return matchobj.group(0).rstrip() + ' \n' else: return matchobj.group(0) text = NEWLINE_RE.sub(newline_callback, text) # now restore removed code blocks removed_blocks = code_blocks + inline_blocks for removed_block in removed_blocks: text = text.replace('{placeholder}', removed_block, 1) if use_crlf: text = text.replace('\n', '\r\n') return text
[ "def", "gfm", "(", "text", ")", ":", "def", "indent_code", "(", "matchobj", ")", ":", "syntax", "=", "matchobj", ".", "group", "(", "1", ")", "code", "=", "matchobj", ".", "group", "(", "2", ")", "if", "syntax", ":", "result", "=", "' :::'", "+"...
Prepare text for rendering by a regular Markdown processor.
[ "Prepare", "text", "for", "rendering", "by", "a", "regular", "Markdown", "processor", "." ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/gfm.py#L111-L169
9,875
hasgeek/coaster
coaster/gfm.py
markdown
def markdown(text, html=False, valid_tags=GFM_TAGS): """ Return Markdown rendered text using GitHub Flavoured Markdown, with HTML escaped and syntax-highlighting enabled. """ if text is None: return None if html: return Markup(sanitize_html(markdown_convert_html(gfm(text)), valid_tags=valid_tags)) else: return Markup(markdown_convert_text(gfm(text)))
python
def markdown(text, html=False, valid_tags=GFM_TAGS): if text is None: return None if html: return Markup(sanitize_html(markdown_convert_html(gfm(text)), valid_tags=valid_tags)) else: return Markup(markdown_convert_text(gfm(text)))
[ "def", "markdown", "(", "text", ",", "html", "=", "False", ",", "valid_tags", "=", "GFM_TAGS", ")", ":", "if", "text", "is", "None", ":", "return", "None", "if", "html", ":", "return", "Markup", "(", "sanitize_html", "(", "markdown_convert_html", "(", "g...
Return Markdown rendered text using GitHub Flavoured Markdown, with HTML escaped and syntax-highlighting enabled.
[ "Return", "Markdown", "rendered", "text", "using", "GitHub", "Flavoured", "Markdown", "with", "HTML", "escaped", "and", "syntax", "-", "highlighting", "enabled", "." ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/gfm.py#L172-L182
9,876
hasgeek/coaster
coaster/views/classview.py
ViewHandlerWrapper.is_available
def is_available(self): """Indicates whether this view is available in the current context""" if hasattr(self._viewh.wrapped_func, 'is_available'): return self._viewh.wrapped_func.is_available(self._obj) return True
python
def is_available(self): if hasattr(self._viewh.wrapped_func, 'is_available'): return self._viewh.wrapped_func.is_available(self._obj) return True
[ "def", "is_available", "(", "self", ")", ":", "if", "hasattr", "(", "self", ".", "_viewh", ".", "wrapped_func", ",", "'is_available'", ")", ":", "return", "self", ".", "_viewh", ".", "wrapped_func", ".", "is_available", "(", "self", ".", "_obj", ")", "re...
Indicates whether this view is available in the current context
[ "Indicates", "whether", "this", "view", "is", "available", "in", "the", "current", "context" ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/classview.py#L254-L258
9,877
hasgeek/coaster
coaster/views/misc.py
get_current_url
def get_current_url(): """ Return the current URL including the query string as a relative path. If the app uses subdomains, return an absolute path """ if current_app.config.get('SERVER_NAME') and ( # Check current hostname against server name, ignoring port numbers, if any (split on ':') request.environ['HTTP_HOST'].split(':', 1)[0] != current_app.config['SERVER_NAME'].split(':', 1)[0]): return request.url url = url_for(request.endpoint, **request.view_args) query = request.query_string if query: return url + '?' + query.decode() else: return url
python
def get_current_url(): if current_app.config.get('SERVER_NAME') and ( # Check current hostname against server name, ignoring port numbers, if any (split on ':') request.environ['HTTP_HOST'].split(':', 1)[0] != current_app.config['SERVER_NAME'].split(':', 1)[0]): return request.url url = url_for(request.endpoint, **request.view_args) query = request.query_string if query: return url + '?' + query.decode() else: return url
[ "def", "get_current_url", "(", ")", ":", "if", "current_app", ".", "config", ".", "get", "(", "'SERVER_NAME'", ")", "and", "(", "# Check current hostname against server name, ignoring port numbers, if any (split on ':')", "request", ".", "environ", "[", "'HTTP_HOST'", "]"...
Return the current URL including the query string as a relative path. If the app uses subdomains, return an absolute path
[ "Return", "the", "current", "URL", "including", "the", "query", "string", "as", "a", "relative", "path", ".", "If", "the", "app", "uses", "subdomains", "return", "an", "absolute", "path" ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/misc.py#L43-L58
9,878
hasgeek/coaster
coaster/views/misc.py
get_next_url
def get_next_url(referrer=False, external=False, session=False, default=__marker): """ Get the next URL to redirect to. Don't return external URLs unless explicitly asked for. This is to protect the site from being an unwitting redirector to external URLs. Subdomains are okay, however. This function looks for a ``next`` parameter in the request or in the session (depending on whether parameter ``session`` is True). If no ``next`` is present, it checks the referrer (if enabled), and finally returns either the provided default (which can be any value including ``None``) or the script root (typically ``/``). """ if session: next_url = request_session.pop('next', None) or request.args.get('next', '') else: next_url = request.args.get('next', '') if next_url and not external: next_url = __clean_external_url(next_url) if next_url: return next_url if default is __marker: usedefault = False else: usedefault = True if referrer and request.referrer: if external: return request.referrer else: return __clean_external_url(request.referrer) or (default if usedefault else __index_url()) else: return default if usedefault else __index_url()
python
def get_next_url(referrer=False, external=False, session=False, default=__marker): if session: next_url = request_session.pop('next', None) or request.args.get('next', '') else: next_url = request.args.get('next', '') if next_url and not external: next_url = __clean_external_url(next_url) if next_url: return next_url if default is __marker: usedefault = False else: usedefault = True if referrer and request.referrer: if external: return request.referrer else: return __clean_external_url(request.referrer) or (default if usedefault else __index_url()) else: return default if usedefault else __index_url()
[ "def", "get_next_url", "(", "referrer", "=", "False", ",", "external", "=", "False", ",", "session", "=", "False", ",", "default", "=", "__marker", ")", ":", "if", "session", ":", "next_url", "=", "request_session", ".", "pop", "(", "'next'", ",", "None"...
Get the next URL to redirect to. Don't return external URLs unless explicitly asked for. This is to protect the site from being an unwitting redirector to external URLs. Subdomains are okay, however. This function looks for a ``next`` parameter in the request or in the session (depending on whether parameter ``session`` is True). If no ``next`` is present, it checks the referrer (if enabled), and finally returns either the provided default (which can be any value including ``None``) or the script root (typically ``/``).
[ "Get", "the", "next", "URL", "to", "redirect", "to", ".", "Don", "t", "return", "external", "URLs", "unless", "explicitly", "asked", "for", ".", "This", "is", "to", "protect", "the", "site", "from", "being", "an", "unwitting", "redirector", "to", "external...
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/misc.py#L64-L96
9,879
hasgeek/coaster
coaster/sqlalchemy/annotations.py
annotation_wrapper
def annotation_wrapper(annotation, doc=None): """ Defines an annotation, which can be applied to attributes in a database model. """ def decorator(attr): __cache__.setdefault(attr, []).append(annotation) # Also mark the annotation on the object itself. This will # fail if the object has a restrictive __slots__, but it's # required for some objects like Column because SQLAlchemy copies # them in subclasses, changing their hash and making them # undiscoverable via the cache. try: if not hasattr(attr, '_coaster_annotations'): setattr(attr, '_coaster_annotations', []) attr._coaster_annotations.append(annotation) except AttributeError: pass return attr decorator.__name__ = decorator.name = annotation decorator.__doc__ = doc return decorator
python
def annotation_wrapper(annotation, doc=None): def decorator(attr): __cache__.setdefault(attr, []).append(annotation) # Also mark the annotation on the object itself. This will # fail if the object has a restrictive __slots__, but it's # required for some objects like Column because SQLAlchemy copies # them in subclasses, changing their hash and making them # undiscoverable via the cache. try: if not hasattr(attr, '_coaster_annotations'): setattr(attr, '_coaster_annotations', []) attr._coaster_annotations.append(annotation) except AttributeError: pass return attr decorator.__name__ = decorator.name = annotation decorator.__doc__ = doc return decorator
[ "def", "annotation_wrapper", "(", "annotation", ",", "doc", "=", "None", ")", ":", "def", "decorator", "(", "attr", ")", ":", "__cache__", ".", "setdefault", "(", "attr", ",", "[", "]", ")", ".", "append", "(", "annotation", ")", "# Also mark the annotatio...
Defines an annotation, which can be applied to attributes in a database model.
[ "Defines", "an", "annotation", "which", "can", "be", "applied", "to", "attributes", "in", "a", "database", "model", "." ]
07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/annotations.py#L114-L135
9,880
dnephin/PyStaticConfiguration
staticconf/schema.py
SchemaMeta.build_attributes
def build_attributes(cls, attributes, namespace): """Return an attributes dictionary with ValueTokens replaced by a property which returns the config value. """ config_path = attributes.get('config_path') tokens = {} def build_config_key(value_def, config_key): key = value_def.config_key or config_key return '%s.%s' % (config_path, key) if config_path else key def build_token(name, value_def): config_key = build_config_key(value_def, name) value_token = ValueToken.from_definition( value_def, namespace, config_key) getters.register_value_proxy(namespace, value_token, value_def.help) tokens[name] = value_token return name, build_property(value_token) def build_attr(name, attribute): if not isinstance(attribute, ValueTypeDefinition): return name, attribute return build_token(name, attribute) attributes = dict(build_attr(*item) for item in six.iteritems(attributes)) attributes['_tokens'] = tokens return attributes
python
def build_attributes(cls, attributes, namespace): config_path = attributes.get('config_path') tokens = {} def build_config_key(value_def, config_key): key = value_def.config_key or config_key return '%s.%s' % (config_path, key) if config_path else key def build_token(name, value_def): config_key = build_config_key(value_def, name) value_token = ValueToken.from_definition( value_def, namespace, config_key) getters.register_value_proxy(namespace, value_token, value_def.help) tokens[name] = value_token return name, build_property(value_token) def build_attr(name, attribute): if not isinstance(attribute, ValueTypeDefinition): return name, attribute return build_token(name, attribute) attributes = dict(build_attr(*item) for item in six.iteritems(attributes)) attributes['_tokens'] = tokens return attributes
[ "def", "build_attributes", "(", "cls", ",", "attributes", ",", "namespace", ")", ":", "config_path", "=", "attributes", ".", "get", "(", "'config_path'", ")", "tokens", "=", "{", "}", "def", "build_config_key", "(", "value_def", ",", "config_key", ")", ":", ...
Return an attributes dictionary with ValueTokens replaced by a property which returns the config value.
[ "Return", "an", "attributes", "dictionary", "with", "ValueTokens", "replaced", "by", "a", "property", "which", "returns", "the", "config", "value", "." ]
229733270bc0dc0d9690ba850dbfb470e535c212
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/schema.py#L166-L193
9,881
dnephin/PyStaticConfiguration
staticconf/proxy.py
cache_as_field
def cache_as_field(cache_name): """Cache a functions return value as the field 'cache_name'.""" def cache_wrapper(func): @functools.wraps(func) def inner_wrapper(self, *args, **kwargs): value = getattr(self, cache_name, UndefToken) if value != UndefToken: return value ret = func(self, *args, **kwargs) setattr(self, cache_name, ret) return ret return inner_wrapper return cache_wrapper
python
def cache_as_field(cache_name): def cache_wrapper(func): @functools.wraps(func) def inner_wrapper(self, *args, **kwargs): value = getattr(self, cache_name, UndefToken) if value != UndefToken: return value ret = func(self, *args, **kwargs) setattr(self, cache_name, ret) return ret return inner_wrapper return cache_wrapper
[ "def", "cache_as_field", "(", "cache_name", ")", ":", "def", "cache_wrapper", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "inner_wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "value", ...
Cache a functions return value as the field 'cache_name'.
[ "Cache", "a", "functions", "return", "value", "as", "the", "field", "cache_name", "." ]
229733270bc0dc0d9690ba850dbfb470e535c212
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/proxy.py#L74-L87
9,882
dnephin/PyStaticConfiguration
staticconf/proxy.py
extract_value
def extract_value(proxy): """Given a value proxy type, Retrieve a value from a namespace, raising exception if no value is found, or the value does not validate. """ value = proxy.namespace.get(proxy.config_key, proxy.default) if value is UndefToken: raise errors.ConfigurationError("%s is missing value for: %s" % (proxy.namespace, proxy.config_key)) try: return proxy.validator(value) except errors.ValidationError as e: raise errors.ConfigurationError("%s failed to validate %s: %s" % (proxy.namespace, proxy.config_key, e))
python
def extract_value(proxy): value = proxy.namespace.get(proxy.config_key, proxy.default) if value is UndefToken: raise errors.ConfigurationError("%s is missing value for: %s" % (proxy.namespace, proxy.config_key)) try: return proxy.validator(value) except errors.ValidationError as e: raise errors.ConfigurationError("%s failed to validate %s: %s" % (proxy.namespace, proxy.config_key, e))
[ "def", "extract_value", "(", "proxy", ")", ":", "value", "=", "proxy", ".", "namespace", ".", "get", "(", "proxy", ".", "config_key", ",", "proxy", ".", "default", ")", "if", "value", "is", "UndefToken", ":", "raise", "errors", ".", "ConfigurationError", ...
Given a value proxy type, Retrieve a value from a namespace, raising exception if no value is found, or the value does not validate.
[ "Given", "a", "value", "proxy", "type", "Retrieve", "a", "value", "from", "a", "namespace", "raising", "exception", "if", "no", "value", "is", "found", "or", "the", "value", "does", "not", "validate", "." ]
229733270bc0dc0d9690ba850dbfb470e535c212
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/proxy.py#L90-L103
9,883
dnephin/PyStaticConfiguration
staticconf/readers.py
build_reader
def build_reader(validator, reader_namespace=config.DEFAULT): """A factory method for creating a custom config reader from a validation function. :param validator: a validation function which acceptance one argument (the configuration value), and returns that value casted to the appropriate type. :param reader_namespace: the default namespace to use. Defaults to `DEFAULT`. """ def reader(config_key, default=UndefToken, namespace=None): config_namespace = config.get_namespace(namespace or reader_namespace) return validator(_read_config(config_key, config_namespace, default)) return reader
python
def build_reader(validator, reader_namespace=config.DEFAULT): def reader(config_key, default=UndefToken, namespace=None): config_namespace = config.get_namespace(namespace or reader_namespace) return validator(_read_config(config_key, config_namespace, default)) return reader
[ "def", "build_reader", "(", "validator", ",", "reader_namespace", "=", "config", ".", "DEFAULT", ")", ":", "def", "reader", "(", "config_key", ",", "default", "=", "UndefToken", ",", "namespace", "=", "None", ")", ":", "config_namespace", "=", "config", ".",...
A factory method for creating a custom config reader from a validation function. :param validator: a validation function which acceptance one argument (the configuration value), and returns that value casted to the appropriate type. :param reader_namespace: the default namespace to use. Defaults to `DEFAULT`.
[ "A", "factory", "method", "for", "creating", "a", "custom", "config", "reader", "from", "a", "validation", "function", "." ]
229733270bc0dc0d9690ba850dbfb470e535c212
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/readers.py#L103-L116
9,884
dnephin/PyStaticConfiguration
staticconf/config.py
get_namespaces_from_names
def get_namespaces_from_names(name, all_names): """Return a generator which yields namespace objects.""" names = configuration_namespaces.keys() if all_names else [name] for name in names: yield get_namespace(name)
python
def get_namespaces_from_names(name, all_names): names = configuration_namespaces.keys() if all_names else [name] for name in names: yield get_namespace(name)
[ "def", "get_namespaces_from_names", "(", "name", ",", "all_names", ")", ":", "names", "=", "configuration_namespaces", ".", "keys", "(", ")", "if", "all_names", "else", "[", "name", "]", "for", "name", "in", "names", ":", "yield", "get_namespace", "(", "name...
Return a generator which yields namespace objects.
[ "Return", "a", "generator", "which", "yields", "namespace", "objects", "." ]
229733270bc0dc0d9690ba850dbfb470e535c212
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/config.py#L181-L185
9,885
dnephin/PyStaticConfiguration
staticconf/config.py
validate
def validate(name=DEFAULT, all_names=False): """Validate all registered keys after loading configuration. Missing values or values which do not pass validation raise :class:`staticconf.errors.ConfigurationError`. By default only validates the `DEFAULT` namespace. :param name: the namespace to validate :type name: string :param all_names: if True validates all namespaces and ignores `name` :type all_names: boolean """ for namespace in get_namespaces_from_names(name, all_names): all(value_proxy.get_value() for value_proxy in namespace.get_value_proxies())
python
def validate(name=DEFAULT, all_names=False): for namespace in get_namespaces_from_names(name, all_names): all(value_proxy.get_value() for value_proxy in namespace.get_value_proxies())
[ "def", "validate", "(", "name", "=", "DEFAULT", ",", "all_names", "=", "False", ")", ":", "for", "namespace", "in", "get_namespaces_from_names", "(", "name", ",", "all_names", ")", ":", "all", "(", "value_proxy", ".", "get_value", "(", ")", "for", "value_p...
Validate all registered keys after loading configuration. Missing values or values which do not pass validation raise :class:`staticconf.errors.ConfigurationError`. By default only validates the `DEFAULT` namespace. :param name: the namespace to validate :type name: string :param all_names: if True validates all namespaces and ignores `name` :type all_names: boolean
[ "Validate", "all", "registered", "keys", "after", "loading", "configuration", "." ]
229733270bc0dc0d9690ba850dbfb470e535c212
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/config.py#L212-L225
9,886
dnephin/PyStaticConfiguration
staticconf/config.py
has_duplicate_keys
def has_duplicate_keys(config_data, base_conf, raise_error): """Compare two dictionaries for duplicate keys. if raise_error is True then raise on exception, otherwise log return True.""" duplicate_keys = set(base_conf) & set(config_data) if not duplicate_keys: return msg = "Duplicate keys in config: %s" % duplicate_keys if raise_error: raise errors.ConfigurationError(msg) log.info(msg) return True
python
def has_duplicate_keys(config_data, base_conf, raise_error): duplicate_keys = set(base_conf) & set(config_data) if not duplicate_keys: return msg = "Duplicate keys in config: %s" % duplicate_keys if raise_error: raise errors.ConfigurationError(msg) log.info(msg) return True
[ "def", "has_duplicate_keys", "(", "config_data", ",", "base_conf", ",", "raise_error", ")", ":", "duplicate_keys", "=", "set", "(", "base_conf", ")", "&", "set", "(", "config_data", ")", "if", "not", "duplicate_keys", ":", "return", "msg", "=", "\"Duplicate ke...
Compare two dictionaries for duplicate keys. if raise_error is True then raise on exception, otherwise log return True.
[ "Compare", "two", "dictionaries", "for", "duplicate", "keys", ".", "if", "raise_error", "is", "True", "then", "raise", "on", "exception", "otherwise", "log", "return", "True", "." ]
229733270bc0dc0d9690ba850dbfb470e535c212
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/config.py#L276-L286
9,887
dnephin/PyStaticConfiguration
staticconf/config.py
build_compare_func
def build_compare_func(err_logger=None): """Returns a compare_func that can be passed to MTimeComparator. The returned compare_func first tries os.path.getmtime(filename), then calls err_logger(filename) if that fails. If err_logger is None, then it does nothing. err_logger is always called within the context of an OSError raised by os.path.getmtime(filename). Information on this error can be retrieved by calling sys.exc_info inside of err_logger.""" def compare_func(filename): try: return os.path.getmtime(filename) except OSError: if err_logger is not None: err_logger(filename) return -1 return compare_func
python
def build_compare_func(err_logger=None): def compare_func(filename): try: return os.path.getmtime(filename) except OSError: if err_logger is not None: err_logger(filename) return -1 return compare_func
[ "def", "build_compare_func", "(", "err_logger", "=", "None", ")", ":", "def", "compare_func", "(", "filename", ")", ":", "try", ":", "return", "os", ".", "path", ".", "getmtime", "(", "filename", ")", "except", "OSError", ":", "if", "err_logger", "is", "...
Returns a compare_func that can be passed to MTimeComparator. The returned compare_func first tries os.path.getmtime(filename), then calls err_logger(filename) if that fails. If err_logger is None, then it does nothing. err_logger is always called within the context of an OSError raised by os.path.getmtime(filename). Information on this error can be retrieved by calling sys.exc_info inside of err_logger.
[ "Returns", "a", "compare_func", "that", "can", "be", "passed", "to", "MTimeComparator", "." ]
229733270bc0dc0d9690ba850dbfb470e535c212
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/config.py#L436-L451
9,888
dnephin/PyStaticConfiguration
staticconf/config.py
ConfigNamespace.get_config_dict
def get_config_dict(self): """Reconstruct the nested structure of this object's configuration and return it as a dict. """ config_dict = {} for dotted_key, value in self.get_config_values().items(): subkeys = dotted_key.split('.') d = config_dict for key in subkeys: d = d.setdefault(key, value if key == subkeys[-1] else {}) return config_dict
python
def get_config_dict(self): config_dict = {} for dotted_key, value in self.get_config_values().items(): subkeys = dotted_key.split('.') d = config_dict for key in subkeys: d = d.setdefault(key, value if key == subkeys[-1] else {}) return config_dict
[ "def", "get_config_dict", "(", "self", ")", ":", "config_dict", "=", "{", "}", "for", "dotted_key", ",", "value", "in", "self", ".", "get_config_values", "(", ")", ".", "items", "(", ")", ":", "subkeys", "=", "dotted_key", ".", "split", "(", "'.'", ")"...
Reconstruct the nested structure of this object's configuration and return it as a dict.
[ "Reconstruct", "the", "nested", "structure", "of", "this", "object", "s", "configuration", "and", "return", "it", "as", "a", "dict", "." ]
229733270bc0dc0d9690ba850dbfb470e535c212
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/config.py#L114-L124
9,889
dnephin/PyStaticConfiguration
staticconf/config.py
ConfigHelp.view_help
def view_help(self): """Return a help message describing all the statically configured keys. """ def format_desc(desc): return "%s (Type: %s, Default: %s)\n%s" % ( desc.name, desc.validator.__name__.replace('validate_', ''), desc.default, desc.help or '') def format_namespace(key, desc_list): return "\nNamespace: %s\n%s" % ( key, '\n'.join(sorted(format_desc(desc) for desc in desc_list))) def namespace_cmp(item): name, _ = item return chr(0) if name == DEFAULT else name return '\n'.join(format_namespace(*desc) for desc in sorted(six.iteritems(self.descriptions), key=namespace_cmp))
python
def view_help(self): def format_desc(desc): return "%s (Type: %s, Default: %s)\n%s" % ( desc.name, desc.validator.__name__.replace('validate_', ''), desc.default, desc.help or '') def format_namespace(key, desc_list): return "\nNamespace: %s\n%s" % ( key, '\n'.join(sorted(format_desc(desc) for desc in desc_list))) def namespace_cmp(item): name, _ = item return chr(0) if name == DEFAULT else name return '\n'.join(format_namespace(*desc) for desc in sorted(six.iteritems(self.descriptions), key=namespace_cmp))
[ "def", "view_help", "(", "self", ")", ":", "def", "format_desc", "(", "desc", ")", ":", "return", "\"%s (Type: %s, Default: %s)\\n%s\"", "%", "(", "desc", ".", "name", ",", "desc", ".", "validator", ".", "__name__", ".", "replace", "(", "'validate_'", ",", ...
Return a help message describing all the statically configured keys.
[ "Return", "a", "help", "message", "describing", "all", "the", "statically", "configured", "keys", "." ]
229733270bc0dc0d9690ba850dbfb470e535c212
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/config.py#L238-L259
9,890
dnephin/PyStaticConfiguration
staticconf/validation.py
_validate_iterable
def _validate_iterable(iterable_type, value): """Convert the iterable to iterable_type, or raise a Configuration exception. """ if isinstance(value, six.string_types): msg = "Invalid iterable of type(%s): %s" raise ValidationError(msg % (type(value), value)) try: return iterable_type(value) except TypeError: raise ValidationError("Invalid iterable: %s" % (value))
python
def _validate_iterable(iterable_type, value): if isinstance(value, six.string_types): msg = "Invalid iterable of type(%s): %s" raise ValidationError(msg % (type(value), value)) try: return iterable_type(value) except TypeError: raise ValidationError("Invalid iterable: %s" % (value))
[ "def", "_validate_iterable", "(", "iterable_type", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "msg", "=", "\"Invalid iterable of type(%s): %s\"", "raise", "ValidationError", "(", "msg", "%", "(", "type", ...
Convert the iterable to iterable_type, or raise a Configuration exception.
[ "Convert", "the", "iterable", "to", "iterable_type", "or", "raise", "a", "Configuration", "exception", "." ]
229733270bc0dc0d9690ba850dbfb470e535c212
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/validation.py#L90-L101
9,891
dnephin/PyStaticConfiguration
staticconf/validation.py
build_list_type_validator
def build_list_type_validator(item_validator): """Return a function which validates that the value is a list of items which are validated using item_validator. """ def validate_list_of_type(value): return [item_validator(item) for item in validate_list(value)] return validate_list_of_type
python
def build_list_type_validator(item_validator): def validate_list_of_type(value): return [item_validator(item) for item in validate_list(value)] return validate_list_of_type
[ "def", "build_list_type_validator", "(", "item_validator", ")", ":", "def", "validate_list_of_type", "(", "value", ")", ":", "return", "[", "item_validator", "(", "item", ")", "for", "item", "in", "validate_list", "(", "value", ")", "]", "return", "validate_list...
Return a function which validates that the value is a list of items which are validated using item_validator.
[ "Return", "a", "function", "which", "validates", "that", "the", "value", "is", "a", "list", "of", "items", "which", "are", "validated", "using", "item_validator", "." ]
229733270bc0dc0d9690ba850dbfb470e535c212
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/validation.py#L123-L129
9,892
dnephin/PyStaticConfiguration
staticconf/validation.py
build_map_type_validator
def build_map_type_validator(item_validator): """Return a function which validates that the value is a mapping of items. The function should return pairs of items that will be passed to the `dict` constructor. """ def validate_mapping(value): return dict(item_validator(item) for item in validate_list(value)) return validate_mapping
python
def build_map_type_validator(item_validator): def validate_mapping(value): return dict(item_validator(item) for item in validate_list(value)) return validate_mapping
[ "def", "build_map_type_validator", "(", "item_validator", ")", ":", "def", "validate_mapping", "(", "value", ")", ":", "return", "dict", "(", "item_validator", "(", "item", ")", "for", "item", "in", "validate_list", "(", "value", ")", ")", "return", "validate_...
Return a function which validates that the value is a mapping of items. The function should return pairs of items that will be passed to the `dict` constructor.
[ "Return", "a", "function", "which", "validates", "that", "the", "value", "is", "a", "mapping", "of", "items", ".", "The", "function", "should", "return", "pairs", "of", "items", "that", "will", "be", "passed", "to", "the", "dict", "constructor", "." ]
229733270bc0dc0d9690ba850dbfb470e535c212
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/validation.py#L132-L139
9,893
dnephin/PyStaticConfiguration
staticconf/getters.py
register_value_proxy
def register_value_proxy(namespace, value_proxy, help_text): """Register a value proxy with the namespace, and add the help_text.""" namespace.register_proxy(value_proxy) config.config_help.add( value_proxy.config_key, value_proxy.validator, value_proxy.default, namespace.get_name(), help_text)
python
def register_value_proxy(namespace, value_proxy, help_text): namespace.register_proxy(value_proxy) config.config_help.add( value_proxy.config_key, value_proxy.validator, value_proxy.default, namespace.get_name(), help_text)
[ "def", "register_value_proxy", "(", "namespace", ",", "value_proxy", ",", "help_text", ")", ":", "namespace", ".", "register_proxy", "(", "value_proxy", ")", "config", ".", "config_help", ".", "add", "(", "value_proxy", ".", "config_key", ",", "value_proxy", "."...
Register a value proxy with the namespace, and add the help_text.
[ "Register", "a", "value", "proxy", "with", "the", "namespace", "and", "add", "the", "help_text", "." ]
229733270bc0dc0d9690ba850dbfb470e535c212
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/getters.py#L68-L73
9,894
dnephin/PyStaticConfiguration
staticconf/getters.py
build_getter
def build_getter(validator, getter_namespace=None): """Create a getter function for retrieving values from the config cache. Getters will default to the DEFAULT namespace. """ def proxy_register(key_name, default=UndefToken, help=None, namespace=None): name = namespace or getter_namespace or config.DEFAULT namespace = config.get_namespace(name) return proxy_factory.build(validator, namespace, key_name, default, help) return proxy_register
python
def build_getter(validator, getter_namespace=None): def proxy_register(key_name, default=UndefToken, help=None, namespace=None): name = namespace or getter_namespace or config.DEFAULT namespace = config.get_namespace(name) return proxy_factory.build(validator, namespace, key_name, default, help) return proxy_register
[ "def", "build_getter", "(", "validator", ",", "getter_namespace", "=", "None", ")", ":", "def", "proxy_register", "(", "key_name", ",", "default", "=", "UndefToken", ",", "help", "=", "None", ",", "namespace", "=", "None", ")", ":", "name", "=", "namespace...
Create a getter function for retrieving values from the config cache. Getters will default to the DEFAULT namespace.
[ "Create", "a", "getter", "function", "for", "retrieving", "values", "from", "the", "config", "cache", ".", "Getters", "will", "default", "to", "the", "DEFAULT", "namespace", "." ]
229733270bc0dc0d9690ba850dbfb470e535c212
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/getters.py#L101-L110
9,895
dnephin/PyStaticConfiguration
staticconf/getters.py
ProxyFactory.build
def build(self, validator, namespace, config_key, default, help): """Build or retrieve a ValueProxy from the attributes. Proxies are keyed using a repr because default values can be mutable types. """ proxy_attrs = validator, namespace, config_key, default proxy_key = repr(proxy_attrs) if proxy_key in self.proxies: return self.proxies[proxy_key] value_proxy = proxy.ValueProxy(*proxy_attrs) register_value_proxy(namespace, value_proxy, help) return self.proxies.setdefault(proxy_key, value_proxy)
python
def build(self, validator, namespace, config_key, default, help): proxy_attrs = validator, namespace, config_key, default proxy_key = repr(proxy_attrs) if proxy_key in self.proxies: return self.proxies[proxy_key] value_proxy = proxy.ValueProxy(*proxy_attrs) register_value_proxy(namespace, value_proxy, help) return self.proxies.setdefault(proxy_key, value_proxy)
[ "def", "build", "(", "self", ",", "validator", ",", "namespace", ",", "config_key", ",", "default", ",", "help", ")", ":", "proxy_attrs", "=", "validator", ",", "namespace", ",", "config_key", ",", "default", "proxy_key", "=", "repr", "(", "proxy_attrs", "...
Build or retrieve a ValueProxy from the attributes. Proxies are keyed using a repr because default values can be mutable types.
[ "Build", "or", "retrieve", "a", "ValueProxy", "from", "the", "attributes", ".", "Proxies", "are", "keyed", "using", "a", "repr", "because", "default", "values", "can", "be", "mutable", "types", "." ]
229733270bc0dc0d9690ba850dbfb470e535c212
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/getters.py#L84-L95
9,896
andim/noisyopt
noisyopt/main.py
minimizeSPSA
def minimizeSPSA(func, x0, args=(), bounds=None, niter=100, paired=True, a=1.0, alpha=0.602, c=1.0, gamma=0.101, disp=False, callback=None): """ Minimization of an objective function by a simultaneous perturbation stochastic approximation algorithm. This algorithm approximates the gradient of the function by finite differences along stochastic directions Deltak. The elements of Deltak are drawn from +- 1 with probability one half. The gradient is approximated from the symmetric difference f(xk + ck*Deltak) - f(xk - ck*Deltak), where the evaluation step size ck is scaled according ck = c/(k+1)**gamma. The algorithm takes a step of size ak = a/(0.01*niter+k+1)**alpha along the negative gradient. See Spall, IEEE, 1998, 34, 817-823 for guidelines about how to choose the algorithm's parameters (a, alpha, c, gamma). Parameters ---------- func: callable objective function to be minimized: called as `func(x, *args)`, if `paired=True`, then called with keyword argument `seed` additionally x0: array-like initial guess for parameters args: tuple extra arguments to be supplied to func bounds: array-like bounds on the variables niter: int number of iterations after which to terminate the algorithm paired: boolean calculate gradient for same random seeds a: float scaling parameter for step size alpha: float scaling exponent for step size c: float scaling parameter for evaluation step size gamma: float scaling exponent for evaluation step size disp: boolean whether to output status updates during the optimization callback: callable called after each iteration, as callback(xk), where xk are the current parameters Returns ------- `scipy.optimize.OptimizeResult` object """ A = 0.01 * niter if bounds is not None: bounds = np.asarray(bounds) project = lambda x: np.clip(x, bounds[:, 0], bounds[:, 1]) if args is not None: # freeze function arguments def funcf(x, **kwargs): return func(x, *args, **kwargs) N = len(x0) x = x0 for k in range(niter): ak = a/(k+1.0+A)**alpha ck = c/(k+1.0)**gamma Deltak = np.random.choice([-1, 1], size=N) fkwargs = dict() if paired: fkwargs['seed'] = np.random.randint(0, np.iinfo(np.uint32).max) if bounds is None: grad = (funcf(x + ck*Deltak, **fkwargs) - funcf(x - ck*Deltak, **fkwargs)) / (2*ck*Deltak) x -= ak*grad else: # ensure evaluation points are feasible xplus = project(x + ck*Deltak) xminus = project(x - ck*Deltak) grad = (funcf(xplus, **fkwargs) - funcf(xminus, **fkwargs)) / (xplus-xminus) x = project(x - ak*grad) # print 100 status updates if disp=True if disp and (k % (niter//100)) == 0: print(x) if callback is not None: callback(x) message = 'terminated after reaching max number of iterations' return OptimizeResult(fun=funcf(x), x=x, nit=niter, nfev=2*niter, message=message, success=True)
python
def minimizeSPSA(func, x0, args=(), bounds=None, niter=100, paired=True, a=1.0, alpha=0.602, c=1.0, gamma=0.101, disp=False, callback=None): A = 0.01 * niter if bounds is not None: bounds = np.asarray(bounds) project = lambda x: np.clip(x, bounds[:, 0], bounds[:, 1]) if args is not None: # freeze function arguments def funcf(x, **kwargs): return func(x, *args, **kwargs) N = len(x0) x = x0 for k in range(niter): ak = a/(k+1.0+A)**alpha ck = c/(k+1.0)**gamma Deltak = np.random.choice([-1, 1], size=N) fkwargs = dict() if paired: fkwargs['seed'] = np.random.randint(0, np.iinfo(np.uint32).max) if bounds is None: grad = (funcf(x + ck*Deltak, **fkwargs) - funcf(x - ck*Deltak, **fkwargs)) / (2*ck*Deltak) x -= ak*grad else: # ensure evaluation points are feasible xplus = project(x + ck*Deltak) xminus = project(x - ck*Deltak) grad = (funcf(xplus, **fkwargs) - funcf(xminus, **fkwargs)) / (xplus-xminus) x = project(x - ak*grad) # print 100 status updates if disp=True if disp and (k % (niter//100)) == 0: print(x) if callback is not None: callback(x) message = 'terminated after reaching max number of iterations' return OptimizeResult(fun=funcf(x), x=x, nit=niter, nfev=2*niter, message=message, success=True)
[ "def", "minimizeSPSA", "(", "func", ",", "x0", ",", "args", "=", "(", ")", ",", "bounds", "=", "None", ",", "niter", "=", "100", ",", "paired", "=", "True", ",", "a", "=", "1.0", ",", "alpha", "=", "0.602", ",", "c", "=", "1.0", ",", "gamma", ...
Minimization of an objective function by a simultaneous perturbation stochastic approximation algorithm. This algorithm approximates the gradient of the function by finite differences along stochastic directions Deltak. The elements of Deltak are drawn from +- 1 with probability one half. The gradient is approximated from the symmetric difference f(xk + ck*Deltak) - f(xk - ck*Deltak), where the evaluation step size ck is scaled according ck = c/(k+1)**gamma. The algorithm takes a step of size ak = a/(0.01*niter+k+1)**alpha along the negative gradient. See Spall, IEEE, 1998, 34, 817-823 for guidelines about how to choose the algorithm's parameters (a, alpha, c, gamma). Parameters ---------- func: callable objective function to be minimized: called as `func(x, *args)`, if `paired=True`, then called with keyword argument `seed` additionally x0: array-like initial guess for parameters args: tuple extra arguments to be supplied to func bounds: array-like bounds on the variables niter: int number of iterations after which to terminate the algorithm paired: boolean calculate gradient for same random seeds a: float scaling parameter for step size alpha: float scaling exponent for step size c: float scaling parameter for evaluation step size gamma: float scaling exponent for evaluation step size disp: boolean whether to output status updates during the optimization callback: callable called after each iteration, as callback(xk), where xk are the current parameters Returns ------- `scipy.optimize.OptimizeResult` object
[ "Minimization", "of", "an", "objective", "function", "by", "a", "simultaneous", "perturbation", "stochastic", "approximation", "algorithm", "." ]
91a748f59acc357622eb4feb58057f8414de7b90
https://github.com/andim/noisyopt/blob/91a748f59acc357622eb4feb58057f8414de7b90/noisyopt/main.py#L264-L351
9,897
andim/noisyopt
noisyopt/main.py
bisect
def bisect(func, a, b, xtol=1e-6, errorcontrol=True, testkwargs=dict(), outside='extrapolate', ascending=None, disp=False): """Find root by bysection search. If the function evaluation is noisy then use `errorcontrol=True` for adaptive sampling of the function during the bisection search. Parameters ---------- func: callable Function of which the root should be found. If `errorcontrol=True` then the function should be derived from `AverageBase`. a, b: float initial interval xtol: float target tolerance for interval size errorcontrol: boolean if true, assume that function is derived from `AverageBase`. testkwargs: only for `errorcontrol=True` see `AverageBase.test0` outside: ['extrapolate', 'raise'] How to handle the case where f(a) and f(b) have same sign, i.e. where the root lies outside of the interval. If 'raise' throws a `BisectException`. ascending: allow passing in directly whether function is ascending or not if ascending=True then it is assumed without check that f(a) < 0 and f(b) > 0 if ascending=False then it is assumed without check that f(a) > 0 and f(b) < 0 Returns ------- float, root of function """ search = True # check whether function is ascending or not if ascending is None: if errorcontrol: testkwargs.update(dict(type_='smaller', force=True)) fa = func.test0(a, **testkwargs) fb = func.test0(b, **testkwargs) else: fa = func(a) < 0 fb = func(b) < 0 if fa and not fb: ascending = True elif fb and not fa: ascending = False else: if disp: print('Warning: func(a) and func(b) do not have opposing signs -> no search done') if outside == 'raise': raise BisectException() search = False # refine interval until it has reached size xtol, except if root outside while (b-a > xtol) and search: mid = (a+b)/2.0 if ascending: if ((not errorcontrol) and (func(mid) < 0)) or \ (errorcontrol and func.test0(mid, **testkwargs)): a = mid else: b = mid else: if ((not errorcontrol) and (func(mid) < 0)) or \ (errorcontrol and func.test0(mid, **testkwargs)): b = mid else: a = mid if disp: print('bisect bounds', a, b) # interpolate linearly to get zero if errorcontrol: ya, yb = func(a)[0], func(b)[0] else: ya, yb = func(a), func(b) m = (yb-ya) / (b-a) res = a-ya/m if disp: print('bisect final value', res) return res
python
def bisect(func, a, b, xtol=1e-6, errorcontrol=True, testkwargs=dict(), outside='extrapolate', ascending=None, disp=False): search = True # check whether function is ascending or not if ascending is None: if errorcontrol: testkwargs.update(dict(type_='smaller', force=True)) fa = func.test0(a, **testkwargs) fb = func.test0(b, **testkwargs) else: fa = func(a) < 0 fb = func(b) < 0 if fa and not fb: ascending = True elif fb and not fa: ascending = False else: if disp: print('Warning: func(a) and func(b) do not have opposing signs -> no search done') if outside == 'raise': raise BisectException() search = False # refine interval until it has reached size xtol, except if root outside while (b-a > xtol) and search: mid = (a+b)/2.0 if ascending: if ((not errorcontrol) and (func(mid) < 0)) or \ (errorcontrol and func.test0(mid, **testkwargs)): a = mid else: b = mid else: if ((not errorcontrol) and (func(mid) < 0)) or \ (errorcontrol and func.test0(mid, **testkwargs)): b = mid else: a = mid if disp: print('bisect bounds', a, b) # interpolate linearly to get zero if errorcontrol: ya, yb = func(a)[0], func(b)[0] else: ya, yb = func(a), func(b) m = (yb-ya) / (b-a) res = a-ya/m if disp: print('bisect final value', res) return res
[ "def", "bisect", "(", "func", ",", "a", ",", "b", ",", "xtol", "=", "1e-6", ",", "errorcontrol", "=", "True", ",", "testkwargs", "=", "dict", "(", ")", ",", "outside", "=", "'extrapolate'", ",", "ascending", "=", "None", ",", "disp", "=", "False", ...
Find root by bysection search. If the function evaluation is noisy then use `errorcontrol=True` for adaptive sampling of the function during the bisection search. Parameters ---------- func: callable Function of which the root should be found. If `errorcontrol=True` then the function should be derived from `AverageBase`. a, b: float initial interval xtol: float target tolerance for interval size errorcontrol: boolean if true, assume that function is derived from `AverageBase`. testkwargs: only for `errorcontrol=True` see `AverageBase.test0` outside: ['extrapolate', 'raise'] How to handle the case where f(a) and f(b) have same sign, i.e. where the root lies outside of the interval. If 'raise' throws a `BisectException`. ascending: allow passing in directly whether function is ascending or not if ascending=True then it is assumed without check that f(a) < 0 and f(b) > 0 if ascending=False then it is assumed without check that f(a) > 0 and f(b) < 0 Returns ------- float, root of function
[ "Find", "root", "by", "bysection", "search", "." ]
91a748f59acc357622eb4feb58057f8414de7b90
https://github.com/andim/noisyopt/blob/91a748f59acc357622eb4feb58057f8414de7b90/noisyopt/main.py#L576-L657
9,898
andim/noisyopt
noisyopt/main.py
AveragedFunction.diffse
def diffse(self, x1, x2): """Standard error of the difference between the function values at x1 and x2""" f1, f1se = self(x1) f2, f2se = self(x2) if self.paired: fx1 = np.array(self.cache[tuple(x1)]) fx2 = np.array(self.cache[tuple(x2)]) diffse = np.std(fx1-fx2, ddof=1)/self.N**.5 return diffse else: return (f1se**2 + f2se**2)**.5
python
def diffse(self, x1, x2): f1, f1se = self(x1) f2, f2se = self(x2) if self.paired: fx1 = np.array(self.cache[tuple(x1)]) fx2 = np.array(self.cache[tuple(x2)]) diffse = np.std(fx1-fx2, ddof=1)/self.N**.5 return diffse else: return (f1se**2 + f2se**2)**.5
[ "def", "diffse", "(", "self", ",", "x1", ",", "x2", ")", ":", "f1", ",", "f1se", "=", "self", "(", "x1", ")", "f2", ",", "f2se", "=", "self", "(", "x2", ")", "if", "self", ".", "paired", ":", "fx1", "=", "np", ".", "array", "(", "self", "."...
Standard error of the difference between the function values at x1 and x2
[ "Standard", "error", "of", "the", "difference", "between", "the", "function", "values", "at", "x1", "and", "x2" ]
91a748f59acc357622eb4feb58057f8414de7b90
https://github.com/andim/noisyopt/blob/91a748f59acc357622eb4feb58057f8414de7b90/noisyopt/main.py#L466-L476
9,899
goodmami/penman
penman.py
alphanum_order
def alphanum_order(triples): """ Sort a list of triples by relation name. Embedded integers are sorted numerically, but otherwise the sorting is alphabetic. """ return sorted( triples, key=lambda t: [ int(t) if t.isdigit() else t for t in re.split(r'([0-9]+)', t.relation or '') ] )
python
def alphanum_order(triples): return sorted( triples, key=lambda t: [ int(t) if t.isdigit() else t for t in re.split(r'([0-9]+)', t.relation or '') ] )
[ "def", "alphanum_order", "(", "triples", ")", ":", "return", "sorted", "(", "triples", ",", "key", "=", "lambda", "t", ":", "[", "int", "(", "t", ")", "if", "t", ".", "isdigit", "(", ")", "else", "t", "for", "t", "in", "re", ".", "split", "(", ...
Sort a list of triples by relation name. Embedded integers are sorted numerically, but otherwise the sorting is alphabetic.
[ "Sort", "a", "list", "of", "triples", "by", "relation", "name", "." ]
a2563ca16063a7330e2028eb489a99cc8e425c41
https://github.com/goodmami/penman/blob/a2563ca16063a7330e2028eb489a99cc8e425c41/penman.py#L95-L108