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
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
239,500
pip-services3-python/pip-services3-commons-python
pip_services3_commons/data/AnyValueMap.py
AnyValueMap.get_as_nullable_float
def get_as_nullable_float(self, key): """ Converts map element into a float or returns None if conversion is not possible. :param key: an index of element to get. :return: float value of the element or None if conversion is not supported. """ value = self.get(key) return FloatConverter.to_nullable_float(value)
python
def get_as_nullable_float(self, key): """ Converts map element into a float or returns None if conversion is not possible. :param key: an index of element to get. :return: float value of the element or None if conversion is not supported. """ value = self.get(key) return FloatConverter.to_nullable_float(value)
[ "def", "get_as_nullable_float", "(", "self", ",", "key", ")", ":", "value", "=", "self", ".", "get", "(", "key", ")", "return", "FloatConverter", ".", "to_nullable_float", "(", "value", ")" ]
Converts map element into a float or returns None if conversion is not possible. :param key: an index of element to get. :return: float value of the element or None if conversion is not supported.
[ "Converts", "map", "element", "into", "a", "float", "or", "returns", "None", "if", "conversion", "is", "not", "possible", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/AnyValueMap.py#L281-L290
239,501
pip-services3-python/pip-services3-commons-python
pip_services3_commons/data/AnyValueMap.py
AnyValueMap.get_as_float
def get_as_float(self, key): """ Converts map element into a float or returns 0 if conversion is not possible. :param key: an index of element to get. :return: float value ot the element or 0 if conversion is not supported. """ value = self.get(key) return FloatConverter.to_float(value)
python
def get_as_float(self, key): """ Converts map element into a float or returns 0 if conversion is not possible. :param key: an index of element to get. :return: float value ot the element or 0 if conversion is not supported. """ value = self.get(key) return FloatConverter.to_float(value)
[ "def", "get_as_float", "(", "self", ",", "key", ")", ":", "value", "=", "self", ".", "get", "(", "key", ")", "return", "FloatConverter", ".", "to_float", "(", "value", ")" ]
Converts map element into a float or returns 0 if conversion is not possible. :param key: an index of element to get. :return: float value ot the element or 0 if conversion is not supported.
[ "Converts", "map", "element", "into", "a", "float", "or", "returns", "0", "if", "conversion", "is", "not", "possible", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/AnyValueMap.py#L292-L301
239,502
pip-services3-python/pip-services3-commons-python
pip_services3_commons/data/AnyValueMap.py
AnyValueMap.get_as_float_with_default
def get_as_float_with_default(self, key, default_value): """ Converts map element into a float or returns default value if conversion is not possible. :param key: an index of element to get. :param default_value: the default value :return: float value ot the element or default value if conversion is not supported. """ value = self.get(key) return FloatConverter.to_float_with_default(value, default_value)
python
def get_as_float_with_default(self, key, default_value): """ Converts map element into a float or returns default value if conversion is not possible. :param key: an index of element to get. :param default_value: the default value :return: float value ot the element or default value if conversion is not supported. """ value = self.get(key) return FloatConverter.to_float_with_default(value, default_value)
[ "def", "get_as_float_with_default", "(", "self", ",", "key", ",", "default_value", ")", ":", "value", "=", "self", ".", "get", "(", "key", ")", "return", "FloatConverter", ".", "to_float_with_default", "(", "value", ",", "default_value", ")" ]
Converts map element into a float or returns default value if conversion is not possible. :param key: an index of element to get. :param default_value: the default value :return: float value ot the element or default value if conversion is not supported.
[ "Converts", "map", "element", "into", "a", "float", "or", "returns", "default", "value", "if", "conversion", "is", "not", "possible", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/AnyValueMap.py#L303-L314
239,503
pip-services3-python/pip-services3-commons-python
pip_services3_commons/data/AnyValueMap.py
AnyValueMap.get_as_nullable_datetime
def get_as_nullable_datetime(self, key): """ Converts map element into a Date or returns None if conversion is not possible. :param key: an index of element to get. :return: Date value of the element or None if conversion is not supported. """ value = self.get(key) return DateTimeConverter.to_nullable_datetime(value)
python
def get_as_nullable_datetime(self, key): """ Converts map element into a Date or returns None if conversion is not possible. :param key: an index of element to get. :return: Date value of the element or None if conversion is not supported. """ value = self.get(key) return DateTimeConverter.to_nullable_datetime(value)
[ "def", "get_as_nullable_datetime", "(", "self", ",", "key", ")", ":", "value", "=", "self", ".", "get", "(", "key", ")", "return", "DateTimeConverter", ".", "to_nullable_datetime", "(", "value", ")" ]
Converts map element into a Date or returns None if conversion is not possible. :param key: an index of element to get. :return: Date value of the element or None if conversion is not supported.
[ "Converts", "map", "element", "into", "a", "Date", "or", "returns", "None", "if", "conversion", "is", "not", "possible", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/AnyValueMap.py#L316-L325
239,504
pip-services3-python/pip-services3-commons-python
pip_services3_commons/data/AnyValueMap.py
AnyValueMap.get_as_datetime
def get_as_datetime(self, key): """ Converts map element into a Date or returns the current date if conversion is not possible. :param key: an index of element to get. :return: Date value ot the element or the current date if conversion is not supported. """ value = self.get(key) return DateTimeConverter.to_datetime(value)
python
def get_as_datetime(self, key): """ Converts map element into a Date or returns the current date if conversion is not possible. :param key: an index of element to get. :return: Date value ot the element or the current date if conversion is not supported. """ value = self.get(key) return DateTimeConverter.to_datetime(value)
[ "def", "get_as_datetime", "(", "self", ",", "key", ")", ":", "value", "=", "self", ".", "get", "(", "key", ")", "return", "DateTimeConverter", ".", "to_datetime", "(", "value", ")" ]
Converts map element into a Date or returns the current date if conversion is not possible. :param key: an index of element to get. :return: Date value ot the element or the current date if conversion is not supported.
[ "Converts", "map", "element", "into", "a", "Date", "or", "returns", "the", "current", "date", "if", "conversion", "is", "not", "possible", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/AnyValueMap.py#L327-L336
239,505
pip-services3-python/pip-services3-commons-python
pip_services3_commons/data/AnyValueMap.py
AnyValueMap.get_as_datetime_with_default
def get_as_datetime_with_default(self, key, default_value): """ Converts map element into a Date or returns default value if conversion is not possible. :param key: an index of element to get. :param default_value: the default value :return: Date value ot the element or default value if conversion is not supported. """ value = self.get(key) return DateTimeConverter.to_datetime_with_default(value, default_value)
python
def get_as_datetime_with_default(self, key, default_value): """ Converts map element into a Date or returns default value if conversion is not possible. :param key: an index of element to get. :param default_value: the default value :return: Date value ot the element or default value if conversion is not supported. """ value = self.get(key) return DateTimeConverter.to_datetime_with_default(value, default_value)
[ "def", "get_as_datetime_with_default", "(", "self", ",", "key", ",", "default_value", ")", ":", "value", "=", "self", ".", "get", "(", "key", ")", "return", "DateTimeConverter", ".", "to_datetime_with_default", "(", "value", ",", "default_value", ")" ]
Converts map element into a Date or returns default value if conversion is not possible. :param key: an index of element to get. :param default_value: the default value :return: Date value ot the element or default value if conversion is not supported.
[ "Converts", "map", "element", "into", "a", "Date", "or", "returns", "default", "value", "if", "conversion", "is", "not", "possible", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/AnyValueMap.py#L338-L349
239,506
pip-services3-python/pip-services3-commons-python
pip_services3_commons/data/AnyValueMap.py
AnyValueMap.get_as_nullable_type
def get_as_nullable_type(self, key, value_type): """ Converts map element into a value defined by specied typecode. If conversion is not possible it returns None. :param key: an index of element to get. :param value_type: the TypeCode that defined the type of the result :return: element value defined by the typecode or None if conversion is not supported. """ value = self.get(key) return TypeConverter.to_nullable_type(value_type, value)
python
def get_as_nullable_type(self, key, value_type): """ Converts map element into a value defined by specied typecode. If conversion is not possible it returns None. :param key: an index of element to get. :param value_type: the TypeCode that defined the type of the result :return: element value defined by the typecode or None if conversion is not supported. """ value = self.get(key) return TypeConverter.to_nullable_type(value_type, value)
[ "def", "get_as_nullable_type", "(", "self", ",", "key", ",", "value_type", ")", ":", "value", "=", "self", ".", "get", "(", "key", ")", "return", "TypeConverter", ".", "to_nullable_type", "(", "value_type", ",", "value", ")" ]
Converts map element into a value defined by specied typecode. If conversion is not possible it returns None. :param key: an index of element to get. :param value_type: the TypeCode that defined the type of the result :return: element value defined by the typecode or None if conversion is not supported.
[ "Converts", "map", "element", "into", "a", "value", "defined", "by", "specied", "typecode", ".", "If", "conversion", "is", "not", "possible", "it", "returns", "None", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/AnyValueMap.py#L351-L363
239,507
pip-services3-python/pip-services3-commons-python
pip_services3_commons/data/AnyValueMap.py
AnyValueMap.get_as_type
def get_as_type(self, key, value_type): """ Converts map element into a value defined by specied typecode. If conversion is not possible it returns default value for the specified type. :param key: an index of element to get. :param value_type: the TypeCode that defined the type of the result :return: element value defined by the typecode or default if conversion is not supported. """ value = self.get(key) return TypeConverter.to_type(value_type, value)
python
def get_as_type(self, key, value_type): """ Converts map element into a value defined by specied typecode. If conversion is not possible it returns default value for the specified type. :param key: an index of element to get. :param value_type: the TypeCode that defined the type of the result :return: element value defined by the typecode or default if conversion is not supported. """ value = self.get(key) return TypeConverter.to_type(value_type, value)
[ "def", "get_as_type", "(", "self", ",", "key", ",", "value_type", ")", ":", "value", "=", "self", ".", "get", "(", "key", ")", "return", "TypeConverter", ".", "to_type", "(", "value_type", ",", "value", ")" ]
Converts map element into a value defined by specied typecode. If conversion is not possible it returns default value for the specified type. :param key: an index of element to get. :param value_type: the TypeCode that defined the type of the result :return: element value defined by the typecode or default if conversion is not supported.
[ "Converts", "map", "element", "into", "a", "value", "defined", "by", "specied", "typecode", ".", "If", "conversion", "is", "not", "possible", "it", "returns", "default", "value", "for", "the", "specified", "type", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/AnyValueMap.py#L365-L377
239,508
pip-services3-python/pip-services3-commons-python
pip_services3_commons/data/AnyValueMap.py
AnyValueMap.get_as_type_with_default
def get_as_type_with_default(self, key, value_type, default_value): """ Converts map element into a value defined by specied typecode. If conversion is not possible it returns default value. :param key: an index of element to get. :param value_type: the TypeCode that defined the type of the result :param default_value: the default value :return: element value defined by the typecode or default value if conversion is not supported. """ value = self.get(key) return TypeConverter.to_type_with_default(value_type, value, default_value)
python
def get_as_type_with_default(self, key, value_type, default_value): """ Converts map element into a value defined by specied typecode. If conversion is not possible it returns default value. :param key: an index of element to get. :param value_type: the TypeCode that defined the type of the result :param default_value: the default value :return: element value defined by the typecode or default value if conversion is not supported. """ value = self.get(key) return TypeConverter.to_type_with_default(value_type, value, default_value)
[ "def", "get_as_type_with_default", "(", "self", ",", "key", ",", "value_type", ",", "default_value", ")", ":", "value", "=", "self", ".", "get", "(", "key", ")", "return", "TypeConverter", ".", "to_type_with_default", "(", "value_type", ",", "value", ",", "default_value", ")" ]
Converts map element into a value defined by specied typecode. If conversion is not possible it returns default value. :param key: an index of element to get. :param value_type: the TypeCode that defined the type of the result :param default_value: the default value :return: element value defined by the typecode or default value if conversion is not supported.
[ "Converts", "map", "element", "into", "a", "value", "defined", "by", "specied", "typecode", ".", "If", "conversion", "is", "not", "possible", "it", "returns", "default", "value", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/AnyValueMap.py#L379-L393
239,509
pip-services3-python/pip-services3-commons-python
pip_services3_commons/data/AnyValueMap.py
AnyValueMap.get_as_nullable_map
def get_as_nullable_map(self, key): """ Converts map element into an AnyValueMap or returns None if conversion is not possible. :param key: a key of element to get. :return: AnyValueMap value of the element or None if conversion is not supported. """ value = self.get_as_object(key) return AnyValueMap.from_value(value)
python
def get_as_nullable_map(self, key): """ Converts map element into an AnyValueMap or returns None if conversion is not possible. :param key: a key of element to get. :return: AnyValueMap value of the element or None if conversion is not supported. """ value = self.get_as_object(key) return AnyValueMap.from_value(value)
[ "def", "get_as_nullable_map", "(", "self", ",", "key", ")", ":", "value", "=", "self", ".", "get_as_object", "(", "key", ")", "return", "AnyValueMap", ".", "from_value", "(", "value", ")" ]
Converts map element into an AnyValueMap or returns None if conversion is not possible. :param key: a key of element to get. :return: AnyValueMap value of the element or None if conversion is not supported.
[ "Converts", "map", "element", "into", "an", "AnyValueMap", "or", "returns", "None", "if", "conversion", "is", "not", "possible", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/AnyValueMap.py#L406-L415
239,510
pip-services3-python/pip-services3-commons-python
pip_services3_commons/data/AnyValueMap.py
AnyValueMap.get_as_map_with_default
def get_as_map_with_default(self, key, default_value): """ Converts map element into an AnyValueMap or returns default value if conversion is not possible. :param key: a key of element to get. :param default_value: the default value :return: AnyValueMap value of the element or default value if conversion is not supported. """ value = self.get_as_nullable_map(key) return MapConverter.to_map_with_default(value, default_value)
python
def get_as_map_with_default(self, key, default_value): """ Converts map element into an AnyValueMap or returns default value if conversion is not possible. :param key: a key of element to get. :param default_value: the default value :return: AnyValueMap value of the element or default value if conversion is not supported. """ value = self.get_as_nullable_map(key) return MapConverter.to_map_with_default(value, default_value)
[ "def", "get_as_map_with_default", "(", "self", ",", "key", ",", "default_value", ")", ":", "value", "=", "self", ".", "get_as_nullable_map", "(", "key", ")", "return", "MapConverter", ".", "to_map_with_default", "(", "value", ",", "default_value", ")" ]
Converts map element into an AnyValueMap or returns default value if conversion is not possible. :param key: a key of element to get. :param default_value: the default value :return: AnyValueMap value of the element or default value if conversion is not supported.
[ "Converts", "map", "element", "into", "an", "AnyValueMap", "or", "returns", "default", "value", "if", "conversion", "is", "not", "possible", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/AnyValueMap.py#L421-L432
239,511
borzecki/q
quicksearch/launch.py
open
def open(url): """ Launches browser depending on os """ if sys.platform == 'win32': os.startfile(url) elif sys.platform == 'darwin': subprocess.Popen(['open', url]) else: try: subprocess.Popen(['xdg-open', url]) except OSError: import webbrowser webbrowser.open(url)
python
def open(url): """ Launches browser depending on os """ if sys.platform == 'win32': os.startfile(url) elif sys.platform == 'darwin': subprocess.Popen(['open', url]) else: try: subprocess.Popen(['xdg-open', url]) except OSError: import webbrowser webbrowser.open(url)
[ "def", "open", "(", "url", ")", ":", "if", "sys", ".", "platform", "==", "'win32'", ":", "os", ".", "startfile", "(", "url", ")", "elif", "sys", ".", "platform", "==", "'darwin'", ":", "subprocess", ".", "Popen", "(", "[", "'open'", ",", "url", "]", ")", "else", ":", "try", ":", "subprocess", ".", "Popen", "(", "[", "'xdg-open'", ",", "url", "]", ")", "except", "OSError", ":", "import", "webbrowser", "webbrowser", ".", "open", "(", "url", ")" ]
Launches browser depending on os
[ "Launches", "browser", "depending", "on", "os" ]
9d5c153fb12b353a73d6909599ad4b1e4e56304d
https://github.com/borzecki/q/blob/9d5c153fb12b353a73d6909599ad4b1e4e56304d/quicksearch/launch.py#L6-L17
239,512
siemens/django-dingos
dingos/core/decorators.py
print_arguments
def print_arguments(): """ Decorator that provides the wrapped function with an attribute 'print_arguments' containing just those keyword arguments actually passed in to the function. To use the decorator for debugging, preface the function into whose calls you are interested with '@print_arguments()' """ def decorator(function): def inner(*args, **kwargs): if args: print "Passed arguments:" for i in args: pp.pprint(i) print "Passed keyword arguments:" pp.pprint(kwargs) return function(*args, **kwargs) return inner return decorator
python
def print_arguments(): """ Decorator that provides the wrapped function with an attribute 'print_arguments' containing just those keyword arguments actually passed in to the function. To use the decorator for debugging, preface the function into whose calls you are interested with '@print_arguments()' """ def decorator(function): def inner(*args, **kwargs): if args: print "Passed arguments:" for i in args: pp.pprint(i) print "Passed keyword arguments:" pp.pprint(kwargs) return function(*args, **kwargs) return inner return decorator
[ "def", "print_arguments", "(", ")", ":", "def", "decorator", "(", "function", ")", ":", "def", "inner", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", ":", "print", "\"Passed arguments:\"", "for", "i", "in", "args", ":", "pp", ".", "pprint", "(", "i", ")", "print", "\"Passed keyword arguments:\"", "pp", ".", "pprint", "(", "kwargs", ")", "return", "function", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "inner", "return", "decorator" ]
Decorator that provides the wrapped function with an attribute 'print_arguments' containing just those keyword arguments actually passed in to the function. To use the decorator for debugging, preface the function into whose calls you are interested with '@print_arguments()'
[ "Decorator", "that", "provides", "the", "wrapped", "function", "with", "an", "attribute", "print_arguments", "containing", "just", "those", "keyword", "arguments", "actually", "passed", "in", "to", "the", "function", "." ]
7154f75b06d2538568e2f2455a76f3d0db0b7d70
https://github.com/siemens/django-dingos/blob/7154f75b06d2538568e2f2455a76f3d0db0b7d70/dingos/core/decorators.py#L23-L41
239,513
TestInABox/stackInABox
stackinabox/services/service.py
StackInABoxServiceRouter.set_subservice
def set_subservice(self, obj): """Add a sub-service object. :param obj: stackinabox.services.StackInABoxService instance :raises: RouteAlreadyRegisteredError if the route is already registered :returns: n/a """ # ensure there is not already a sub-service if self.obj is not None: raise RouteAlreadyRegisteredError( 'Service Router ({0} - {1}): Route {2} already has a ' 'sub-service handler' .format(id(self), self.service_name, self.uri)) # warn if any methods are already registered if len(self.methods): logger.debug( 'WARNING: Service Router ({0} - {1}): Methods detected ' 'on Route {2}. Sub-Service {3} may be hidden.' .format(id(self), self.service_name, self.uri, obj.name)) # Ensure we do not have any circular references assert(obj != self.parent_obj) # if no errors, save the object and update the URI self.obj = obj self.obj.base_url = '{0}/{1}'.format(self.uri, self.service_name)
python
def set_subservice(self, obj): """Add a sub-service object. :param obj: stackinabox.services.StackInABoxService instance :raises: RouteAlreadyRegisteredError if the route is already registered :returns: n/a """ # ensure there is not already a sub-service if self.obj is not None: raise RouteAlreadyRegisteredError( 'Service Router ({0} - {1}): Route {2} already has a ' 'sub-service handler' .format(id(self), self.service_name, self.uri)) # warn if any methods are already registered if len(self.methods): logger.debug( 'WARNING: Service Router ({0} - {1}): Methods detected ' 'on Route {2}. Sub-Service {3} may be hidden.' .format(id(self), self.service_name, self.uri, obj.name)) # Ensure we do not have any circular references assert(obj != self.parent_obj) # if no errors, save the object and update the URI self.obj = obj self.obj.base_url = '{0}/{1}'.format(self.uri, self.service_name)
[ "def", "set_subservice", "(", "self", ",", "obj", ")", ":", "# ensure there is not already a sub-service", "if", "self", ".", "obj", "is", "not", "None", ":", "raise", "RouteAlreadyRegisteredError", "(", "'Service Router ({0} - {1}): Route {2} already has a '", "'sub-service handler'", ".", "format", "(", "id", "(", "self", ")", ",", "self", ".", "service_name", ",", "self", ".", "uri", ")", ")", "# warn if any methods are already registered", "if", "len", "(", "self", ".", "methods", ")", ":", "logger", ".", "debug", "(", "'WARNING: Service Router ({0} - {1}): Methods detected '", "'on Route {2}. Sub-Service {3} may be hidden.'", ".", "format", "(", "id", "(", "self", ")", ",", "self", ".", "service_name", ",", "self", ".", "uri", ",", "obj", ".", "name", ")", ")", "# Ensure we do not have any circular references", "assert", "(", "obj", "!=", "self", ".", "parent_obj", ")", "# if no errors, save the object and update the URI", "self", ".", "obj", "=", "obj", "self", ".", "obj", ".", "base_url", "=", "'{0}/{1}'", ".", "format", "(", "self", ".", "uri", ",", "self", ".", "service_name", ")" ]
Add a sub-service object. :param obj: stackinabox.services.StackInABoxService instance :raises: RouteAlreadyRegisteredError if the route is already registered :returns: n/a
[ "Add", "a", "sub", "-", "service", "object", "." ]
63ee457401e9a88d987f85f513eb512dcb12d984
https://github.com/TestInABox/stackInABox/blob/63ee457401e9a88d987f85f513eb512dcb12d984/stackinabox/services/service.py#L66-L92
239,514
TestInABox/stackInABox
stackinabox/services/service.py
StackInABoxServiceRouter.update_uris
def update_uris(self, new_uri): """Update all URIS. :param new_uri: URI to switch to and update the matching :returns: n/a Note: This overwrites any existing URI """ self.uri = new_uri # if there is a sub-service, update it too if self.obj: self.obj.base_url = '{0}/{1}'.format(self.uri, self.service_name)
python
def update_uris(self, new_uri): """Update all URIS. :param new_uri: URI to switch to and update the matching :returns: n/a Note: This overwrites any existing URI """ self.uri = new_uri # if there is a sub-service, update it too if self.obj: self.obj.base_url = '{0}/{1}'.format(self.uri, self.service_name)
[ "def", "update_uris", "(", "self", ",", "new_uri", ")", ":", "self", ".", "uri", "=", "new_uri", "# if there is a sub-service, update it too", "if", "self", ".", "obj", ":", "self", ".", "obj", ".", "base_url", "=", "'{0}/{1}'", ".", "format", "(", "self", ".", "uri", ",", "self", ".", "service_name", ")" ]
Update all URIS. :param new_uri: URI to switch to and update the matching :returns: n/a Note: This overwrites any existing URI
[ "Update", "all", "URIS", "." ]
63ee457401e9a88d987f85f513eb512dcb12d984
https://github.com/TestInABox/stackInABox/blob/63ee457401e9a88d987f85f513eb512dcb12d984/stackinabox/services/service.py#L94-L106
239,515
TestInABox/stackInABox
stackinabox/services/service.py
StackInABoxServiceRouter.register_method
def register_method(self, method, fn): """Register an HTTP method and handler function. :param method: string, HTTP verb :param fn: python function handling the request :raises: RouteAlreadyRegisteredError if the route is already registered :returns: n/a """ # ensure the HTTP verb is not already registered if method not in self.methods.keys(): logger.debug('Service Router ({0} - {1}): Adding method {2} on ' 'route {3}' .format(id(self), self.service_name, method, self.uri)) self.methods[method] = fn else: raise RouteAlreadyRegisteredError( 'Service Router ({0} - {1}): Method {2} already registered ' 'on Route {3}' .format(id(self), self.service_name, method, self.uri))
python
def register_method(self, method, fn): """Register an HTTP method and handler function. :param method: string, HTTP verb :param fn: python function handling the request :raises: RouteAlreadyRegisteredError if the route is already registered :returns: n/a """ # ensure the HTTP verb is not already registered if method not in self.methods.keys(): logger.debug('Service Router ({0} - {1}): Adding method {2} on ' 'route {3}' .format(id(self), self.service_name, method, self.uri)) self.methods[method] = fn else: raise RouteAlreadyRegisteredError( 'Service Router ({0} - {1}): Method {2} already registered ' 'on Route {3}' .format(id(self), self.service_name, method, self.uri))
[ "def", "register_method", "(", "self", ",", "method", ",", "fn", ")", ":", "# ensure the HTTP verb is not already registered", "if", "method", "not", "in", "self", ".", "methods", ".", "keys", "(", ")", ":", "logger", ".", "debug", "(", "'Service Router ({0} - {1}): Adding method {2} on '", "'route {3}'", ".", "format", "(", "id", "(", "self", ")", ",", "self", ".", "service_name", ",", "method", ",", "self", ".", "uri", ")", ")", "self", ".", "methods", "[", "method", "]", "=", "fn", "else", ":", "raise", "RouteAlreadyRegisteredError", "(", "'Service Router ({0} - {1}): Method {2} already registered '", "'on Route {3}'", ".", "format", "(", "id", "(", "self", ")", ",", "self", ".", "service_name", ",", "method", ",", "self", ".", "uri", ")", ")" ]
Register an HTTP method and handler function. :param method: string, HTTP verb :param fn: python function handling the request :raises: RouteAlreadyRegisteredError if the route is already registered :returns: n/a
[ "Register", "an", "HTTP", "method", "and", "handler", "function", "." ]
63ee457401e9a88d987f85f513eb512dcb12d984
https://github.com/TestInABox/stackInABox/blob/63ee457401e9a88d987f85f513eb512dcb12d984/stackinabox/services/service.py#L108-L134
239,516
TestInABox/stackInABox
stackinabox/services/service.py
StackInABoxService.validate_regex
def validate_regex(regex, sub_service): """Is the regex valid for StackInABox routing? :param regex: Python regex object to match the URI :param sub_service: boolean for whether or not the regex is for a sub-service :raises: InvalidRouteRegexError if the regex does not meet the requirements. """ # The regex generated by stackinabox starts with ^ # and ends with $. Enforce that the provided regex does the same. if regex.pattern.startswith('^') is False: logger.debug('StackInABoxService: Pattern must start with ^') raise InvalidRouteRegexError('Pattern must start with ^') # Note: pattern may end with $ even if sub_service is True if regex.pattern.endswith('$') is False and sub_service is False: logger.debug('StackInABoxService: Pattern must end with $') raise InvalidRouteRegexError('Pattern must end with $') # Enforce that if the pattern does not end with $ that it is a service if regex.pattern.endswith('$') is True and sub_service is True: logger.debug( 'StackInABoxService: Sub-Service RegEx Pattern must not ' 'end with $') raise InvalidRouteRegexError('Pattern must end with $')
python
def validate_regex(regex, sub_service): """Is the regex valid for StackInABox routing? :param regex: Python regex object to match the URI :param sub_service: boolean for whether or not the regex is for a sub-service :raises: InvalidRouteRegexError if the regex does not meet the requirements. """ # The regex generated by stackinabox starts with ^ # and ends with $. Enforce that the provided regex does the same. if regex.pattern.startswith('^') is False: logger.debug('StackInABoxService: Pattern must start with ^') raise InvalidRouteRegexError('Pattern must start with ^') # Note: pattern may end with $ even if sub_service is True if regex.pattern.endswith('$') is False and sub_service is False: logger.debug('StackInABoxService: Pattern must end with $') raise InvalidRouteRegexError('Pattern must end with $') # Enforce that if the pattern does not end with $ that it is a service if regex.pattern.endswith('$') is True and sub_service is True: logger.debug( 'StackInABoxService: Sub-Service RegEx Pattern must not ' 'end with $') raise InvalidRouteRegexError('Pattern must end with $')
[ "def", "validate_regex", "(", "regex", ",", "sub_service", ")", ":", "# The regex generated by stackinabox starts with ^", "# and ends with $. Enforce that the provided regex does the same.", "if", "regex", ".", "pattern", ".", "startswith", "(", "'^'", ")", "is", "False", ":", "logger", ".", "debug", "(", "'StackInABoxService: Pattern must start with ^'", ")", "raise", "InvalidRouteRegexError", "(", "'Pattern must start with ^'", ")", "# Note: pattern may end with $ even if sub_service is True", "if", "regex", ".", "pattern", ".", "endswith", "(", "'$'", ")", "is", "False", "and", "sub_service", "is", "False", ":", "logger", ".", "debug", "(", "'StackInABoxService: Pattern must end with $'", ")", "raise", "InvalidRouteRegexError", "(", "'Pattern must end with $'", ")", "# Enforce that if the pattern does not end with $ that it is a service", "if", "regex", ".", "pattern", ".", "endswith", "(", "'$'", ")", "is", "True", "and", "sub_service", "is", "True", ":", "logger", ".", "debug", "(", "'StackInABoxService: Sub-Service RegEx Pattern must not '", "'end with $'", ")", "raise", "InvalidRouteRegexError", "(", "'Pattern must end with $'", ")" ]
Is the regex valid for StackInABox routing? :param regex: Python regex object to match the URI :param sub_service: boolean for whether or not the regex is for a sub-service :raises: InvalidRouteRegexError if the regex does not meet the requirements.
[ "Is", "the", "regex", "valid", "for", "StackInABox", "routing?" ]
63ee457401e9a88d987f85f513eb512dcb12d984
https://github.com/TestInABox/stackInABox/blob/63ee457401e9a88d987f85f513eb512dcb12d984/stackinabox/services/service.py#L237-L264
239,517
TestInABox/stackInABox
stackinabox/services/service.py
StackInABoxService.get_service_regex
def get_service_regex(base_url, service_url, sub_service): """Get the regex for a given service. :param base_url: string - Base URI :param service_url: string - Service URI under the Base URI :param sub_service: boolean - is the Service URI for a sub-service? :returns: Python Regex object containing the regex for the Service """ # if the specified service_url is already a regex # then just use. Otherwise create what we need if StackInABoxService.is_regex(service_url): logger.debug('StackInABoxService: Received regex {0} for use...' .format(service_url.pattern)) # Validate the regex against StackInABoxService requirement StackInABoxService.validate_regex(service_url, sub_service) return service_url else: regex = '^{0}{1}$'.format('', service_url) logger.debug('StackInABoxService: {0} + {1} -> {2}' .format(base_url, service_url, regex)) return re.compile(regex)
python
def get_service_regex(base_url, service_url, sub_service): """Get the regex for a given service. :param base_url: string - Base URI :param service_url: string - Service URI under the Base URI :param sub_service: boolean - is the Service URI for a sub-service? :returns: Python Regex object containing the regex for the Service """ # if the specified service_url is already a regex # then just use. Otherwise create what we need if StackInABoxService.is_regex(service_url): logger.debug('StackInABoxService: Received regex {0} for use...' .format(service_url.pattern)) # Validate the regex against StackInABoxService requirement StackInABoxService.validate_regex(service_url, sub_service) return service_url else: regex = '^{0}{1}$'.format('', service_url) logger.debug('StackInABoxService: {0} + {1} -> {2}' .format(base_url, service_url, regex)) return re.compile(regex)
[ "def", "get_service_regex", "(", "base_url", ",", "service_url", ",", "sub_service", ")", ":", "# if the specified service_url is already a regex", "# then just use. Otherwise create what we need", "if", "StackInABoxService", ".", "is_regex", "(", "service_url", ")", ":", "logger", ".", "debug", "(", "'StackInABoxService: Received regex {0} for use...'", ".", "format", "(", "service_url", ".", "pattern", ")", ")", "# Validate the regex against StackInABoxService requirement", "StackInABoxService", ".", "validate_regex", "(", "service_url", ",", "sub_service", ")", "return", "service_url", "else", ":", "regex", "=", "'^{0}{1}$'", ".", "format", "(", "''", ",", "service_url", ")", "logger", ".", "debug", "(", "'StackInABoxService: {0} + {1} -> {2}'", ".", "format", "(", "base_url", ",", "service_url", ",", "regex", ")", ")", "return", "re", ".", "compile", "(", "regex", ")" ]
Get the regex for a given service. :param base_url: string - Base URI :param service_url: string - Service URI under the Base URI :param sub_service: boolean - is the Service URI for a sub-service? :returns: Python Regex object containing the regex for the Service
[ "Get", "the", "regex", "for", "a", "given", "service", "." ]
63ee457401e9a88d987f85f513eb512dcb12d984
https://github.com/TestInABox/stackInABox/blob/63ee457401e9a88d987f85f513eb512dcb12d984/stackinabox/services/service.py#L267-L290
239,518
TestInABox/stackInABox
stackinabox/services/service.py
StackInABoxService.base_url
def base_url(self, value): """Set the Base URI value. :param value: the new URI to use for the Base URI """ logger.debug('StackInABoxService ({0}:{1}) Updating Base URL ' 'from {2} to {3}' .format(self.__id, self.name, self.__base_url, value)) self.__base_url = value for k, v in six.iteritems(self.routes): v['regex'] = StackInABoxService.get_service_regex( value, v['uri'], v['handlers'].is_subservice)
python
def base_url(self, value): """Set the Base URI value. :param value: the new URI to use for the Base URI """ logger.debug('StackInABoxService ({0}:{1}) Updating Base URL ' 'from {2} to {3}' .format(self.__id, self.name, self.__base_url, value)) self.__base_url = value for k, v in six.iteritems(self.routes): v['regex'] = StackInABoxService.get_service_regex( value, v['uri'], v['handlers'].is_subservice)
[ "def", "base_url", "(", "self", ",", "value", ")", ":", "logger", ".", "debug", "(", "'StackInABoxService ({0}:{1}) Updating Base URL '", "'from {2} to {3}'", ".", "format", "(", "self", ".", "__id", ",", "self", ".", "name", ",", "self", ".", "__base_url", ",", "value", ")", ")", "self", ".", "__base_url", "=", "value", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "self", ".", "routes", ")", ":", "v", "[", "'regex'", "]", "=", "StackInABoxService", ".", "get_service_regex", "(", "value", ",", "v", "[", "'uri'", "]", ",", "v", "[", "'handlers'", "]", ".", "is_subservice", ")" ]
Set the Base URI value. :param value: the new URI to use for the Base URI
[ "Set", "the", "Base", "URI", "value", "." ]
63ee457401e9a88d987f85f513eb512dcb12d984
https://github.com/TestInABox/stackInABox/blob/63ee457401e9a88d987f85f513eb512dcb12d984/stackinabox/services/service.py#L298-L314
239,519
TestInABox/stackInABox
stackinabox/services/service.py
StackInABoxService.reset
def reset(self): """Reset the service to its' initial state.""" logger.debug('StackInABoxService ({0}): Reset' .format(self.__id, self.name)) self.base_url = '/{0}'.format(self.name) logger.debug('StackInABoxService ({0}): Hosting Service {1}' .format(self.__id, self.name))
python
def reset(self): """Reset the service to its' initial state.""" logger.debug('StackInABoxService ({0}): Reset' .format(self.__id, self.name)) self.base_url = '/{0}'.format(self.name) logger.debug('StackInABoxService ({0}): Hosting Service {1}' .format(self.__id, self.name))
[ "def", "reset", "(", "self", ")", ":", "logger", ".", "debug", "(", "'StackInABoxService ({0}): Reset'", ".", "format", "(", "self", ".", "__id", ",", "self", ".", "name", ")", ")", "self", ".", "base_url", "=", "'/{0}'", ".", "format", "(", "self", ".", "name", ")", "logger", ".", "debug", "(", "'StackInABoxService ({0}): Hosting Service {1}'", ".", "format", "(", "self", ".", "__id", ",", "self", ".", "name", ")", ")" ]
Reset the service to its' initial state.
[ "Reset", "the", "service", "to", "its", "initial", "state", "." ]
63ee457401e9a88d987f85f513eb512dcb12d984
https://github.com/TestInABox/stackInABox/blob/63ee457401e9a88d987f85f513eb512dcb12d984/stackinabox/services/service.py#L316-L322
239,520
TestInABox/stackInABox
stackinabox/services/service.py
StackInABoxService.try_handle_route
def try_handle_route(self, route_uri, method, request, uri, headers): """Try to handle the supplied request on the specified routing URI. :param route_uri: string - URI of the request :param method: string - HTTP Verb :param request: request object describing the HTTP request :param uri: URI of the reuqest :param headers: case-insensitive headers dict :returns: tuple - (int, dict, string) containing: int - the http response status code dict - the headers for the http response string - http string response """ uri_path = route_uri if '?' in uri: logger.debug('StackInABoxService ({0}:{1}): Found query string ' 'removing for match operation.' .format(self.__id, self.name)) uri_path, uri_qs = uri.split('?') logger.debug('StackInABoxService ({0}:{1}): uri = "{2}", ' 'query = "{3}"' .format(self.__id, self.name, uri_path, uri_qs)) for k, v in six.iteritems(self.routes): logger.debug('StackInABoxService ({0}:{1}): Checking if ' 'route {2} handles...' .format(self.__id, self.name, v['uri'])) logger.debug('StackInABoxService ({0}:{1}): ...using regex ' 'pattern {2} against {3}' .format(self.__id, self.name, v['regex'].pattern, uri_path)) if v['regex'].match(uri_path): logger.debug('StackInABoxService ({0}:{1}): Checking if ' 'route {2} handles method {2}...' .format(self.__id, self.name, v['uri'], method)) return v['handlers'](method, request, uri, headers) return (595, headers, 'Route ({0}) Not Handled'.format(uri))
python
def try_handle_route(self, route_uri, method, request, uri, headers): """Try to handle the supplied request on the specified routing URI. :param route_uri: string - URI of the request :param method: string - HTTP Verb :param request: request object describing the HTTP request :param uri: URI of the reuqest :param headers: case-insensitive headers dict :returns: tuple - (int, dict, string) containing: int - the http response status code dict - the headers for the http response string - http string response """ uri_path = route_uri if '?' in uri: logger.debug('StackInABoxService ({0}:{1}): Found query string ' 'removing for match operation.' .format(self.__id, self.name)) uri_path, uri_qs = uri.split('?') logger.debug('StackInABoxService ({0}:{1}): uri = "{2}", ' 'query = "{3}"' .format(self.__id, self.name, uri_path, uri_qs)) for k, v in six.iteritems(self.routes): logger.debug('StackInABoxService ({0}:{1}): Checking if ' 'route {2} handles...' .format(self.__id, self.name, v['uri'])) logger.debug('StackInABoxService ({0}:{1}): ...using regex ' 'pattern {2} against {3}' .format(self.__id, self.name, v['regex'].pattern, uri_path)) if v['regex'].match(uri_path): logger.debug('StackInABoxService ({0}:{1}): Checking if ' 'route {2} handles method {2}...' .format(self.__id, self.name, v['uri'], method)) return v['handlers'](method, request, uri, headers) return (595, headers, 'Route ({0}) Not Handled'.format(uri))
[ "def", "try_handle_route", "(", "self", ",", "route_uri", ",", "method", ",", "request", ",", "uri", ",", "headers", ")", ":", "uri_path", "=", "route_uri", "if", "'?'", "in", "uri", ":", "logger", ".", "debug", "(", "'StackInABoxService ({0}:{1}): Found query string '", "'removing for match operation.'", ".", "format", "(", "self", ".", "__id", ",", "self", ".", "name", ")", ")", "uri_path", ",", "uri_qs", "=", "uri", ".", "split", "(", "'?'", ")", "logger", ".", "debug", "(", "'StackInABoxService ({0}:{1}): uri = \"{2}\", '", "'query = \"{3}\"'", ".", "format", "(", "self", ".", "__id", ",", "self", ".", "name", ",", "uri_path", ",", "uri_qs", ")", ")", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "self", ".", "routes", ")", ":", "logger", ".", "debug", "(", "'StackInABoxService ({0}:{1}): Checking if '", "'route {2} handles...'", ".", "format", "(", "self", ".", "__id", ",", "self", ".", "name", ",", "v", "[", "'uri'", "]", ")", ")", "logger", ".", "debug", "(", "'StackInABoxService ({0}:{1}): ...using regex '", "'pattern {2} against {3}'", ".", "format", "(", "self", ".", "__id", ",", "self", ".", "name", ",", "v", "[", "'regex'", "]", ".", "pattern", ",", "uri_path", ")", ")", "if", "v", "[", "'regex'", "]", ".", "match", "(", "uri_path", ")", ":", "logger", ".", "debug", "(", "'StackInABoxService ({0}:{1}): Checking if '", "'route {2} handles method {2}...'", ".", "format", "(", "self", ".", "__id", ",", "self", ".", "name", ",", "v", "[", "'uri'", "]", ",", "method", ")", ")", "return", "v", "[", "'handlers'", "]", "(", "method", ",", "request", ",", "uri", ",", "headers", ")", "return", "(", "595", ",", "headers", ",", "'Route ({0}) Not Handled'", ".", "format", "(", "uri", ")", ")" ]
Try to handle the supplied request on the specified routing URI. :param route_uri: string - URI of the request :param method: string - HTTP Verb :param request: request object describing the HTTP request :param uri: URI of the reuqest :param headers: case-insensitive headers dict :returns: tuple - (int, dict, string) containing: int - the http response status code dict - the headers for the http response string - http string response
[ "Try", "to", "handle", "the", "supplied", "request", "on", "the", "specified", "routing", "URI", "." ]
63ee457401e9a88d987f85f513eb512dcb12d984
https://github.com/TestInABox/stackInABox/blob/63ee457401e9a88d987f85f513eb512dcb12d984/stackinabox/services/service.py#L324-L366
239,521
TestInABox/stackInABox
stackinabox/services/service.py
StackInABoxService.sub_request
def sub_request(self, method, request, uri, headers): """Handle the supplied sub-service request on the specified routing URI. :param method: string - HTTP Verb :param request: request object describing the HTTP request :param uri: URI of the reuqest :param headers: case-insensitive headers dict :returns: tuple - (int, dict, string) containing: int - the http response status code dict - the headers for the http response string - http string response """ logger.debug('StackInABoxService ({0}:{1}): Sub-Request Received ' '{2} - {3}' .format(self.__id, self.name, method, uri)) return self.request(method, request, uri, headers)
python
def sub_request(self, method, request, uri, headers): """Handle the supplied sub-service request on the specified routing URI. :param method: string - HTTP Verb :param request: request object describing the HTTP request :param uri: URI of the reuqest :param headers: case-insensitive headers dict :returns: tuple - (int, dict, string) containing: int - the http response status code dict - the headers for the http response string - http string response """ logger.debug('StackInABoxService ({0}:{1}): Sub-Request Received ' '{2} - {3}' .format(self.__id, self.name, method, uri)) return self.request(method, request, uri, headers)
[ "def", "sub_request", "(", "self", ",", "method", ",", "request", ",", "uri", ",", "headers", ")", ":", "logger", ".", "debug", "(", "'StackInABoxService ({0}:{1}): Sub-Request Received '", "'{2} - {3}'", ".", "format", "(", "self", ".", "__id", ",", "self", ".", "name", ",", "method", ",", "uri", ")", ")", "return", "self", ".", "request", "(", "method", ",", "request", ",", "uri", ",", "headers", ")" ]
Handle the supplied sub-service request on the specified routing URI. :param method: string - HTTP Verb :param request: request object describing the HTTP request :param uri: URI of the reuqest :param headers: case-insensitive headers dict :returns: tuple - (int, dict, string) containing: int - the http response status code dict - the headers for the http response string - http string response
[ "Handle", "the", "supplied", "sub", "-", "service", "request", "on", "the", "specified", "routing", "URI", "." ]
63ee457401e9a88d987f85f513eb512dcb12d984
https://github.com/TestInABox/stackInABox/blob/63ee457401e9a88d987f85f513eb512dcb12d984/stackinabox/services/service.py#L385-L401
239,522
TestInABox/stackInABox
stackinabox/services/service.py
StackInABoxService.create_route
def create_route(self, uri, sub_service): """Create the route for the URI. :param uri: string - URI to be routed :param sub_service: boolean - is the URI for a sub-service :returns: n/a """ if uri not in self.routes.keys(): logger.debug('Service ({0}): Creating routes' .format(self.name)) self.routes[uri] = { 'regex': StackInABoxService.get_service_regex(self.base_url, uri, sub_service), 'uri': uri, 'handlers': StackInABoxServiceRouter(self.name, uri, None, self) }
python
def create_route(self, uri, sub_service): """Create the route for the URI. :param uri: string - URI to be routed :param sub_service: boolean - is the URI for a sub-service :returns: n/a """ if uri not in self.routes.keys(): logger.debug('Service ({0}): Creating routes' .format(self.name)) self.routes[uri] = { 'regex': StackInABoxService.get_service_regex(self.base_url, uri, sub_service), 'uri': uri, 'handlers': StackInABoxServiceRouter(self.name, uri, None, self) }
[ "def", "create_route", "(", "self", ",", "uri", ",", "sub_service", ")", ":", "if", "uri", "not", "in", "self", ".", "routes", ".", "keys", "(", ")", ":", "logger", ".", "debug", "(", "'Service ({0}): Creating routes'", ".", "format", "(", "self", ".", "name", ")", ")", "self", ".", "routes", "[", "uri", "]", "=", "{", "'regex'", ":", "StackInABoxService", ".", "get_service_regex", "(", "self", ".", "base_url", ",", "uri", ",", "sub_service", ")", ",", "'uri'", ":", "uri", ",", "'handlers'", ":", "StackInABoxServiceRouter", "(", "self", ".", "name", ",", "uri", ",", "None", ",", "self", ")", "}" ]
Create the route for the URI. :param uri: string - URI to be routed :param sub_service: boolean - is the URI for a sub-service :returns: n/a
[ "Create", "the", "route", "for", "the", "URI", "." ]
63ee457401e9a88d987f85f513eb512dcb12d984
https://github.com/TestInABox/stackInABox/blob/63ee457401e9a88d987f85f513eb512dcb12d984/stackinabox/services/service.py#L403-L423
239,523
TestInABox/stackInABox
stackinabox/services/service.py
StackInABoxService.register
def register(self, method, uri, call_back): """Register a class instance function to handle a request. :param method: string - HTTP Verb :param uri: string - URI for the request :param call_back: class instance function that handles the request :returns: n/a """ found = False self.create_route(uri, False) self.routes[uri]['handlers'].register_method(method, call_back)
python
def register(self, method, uri, call_back): """Register a class instance function to handle a request. :param method: string - HTTP Verb :param uri: string - URI for the request :param call_back: class instance function that handles the request :returns: n/a """ found = False self.create_route(uri, False) self.routes[uri]['handlers'].register_method(method, call_back)
[ "def", "register", "(", "self", ",", "method", ",", "uri", ",", "call_back", ")", ":", "found", "=", "False", "self", ".", "create_route", "(", "uri", ",", "False", ")", "self", ".", "routes", "[", "uri", "]", "[", "'handlers'", "]", ".", "register_method", "(", "method", ",", "call_back", ")" ]
Register a class instance function to handle a request. :param method: string - HTTP Verb :param uri: string - URI for the request :param call_back: class instance function that handles the request :returns: n/a
[ "Register", "a", "class", "instance", "function", "to", "handle", "a", "request", "." ]
63ee457401e9a88d987f85f513eb512dcb12d984
https://github.com/TestInABox/stackInABox/blob/63ee457401e9a88d987f85f513eb512dcb12d984/stackinabox/services/service.py#L425-L438
239,524
TestInABox/stackInABox
stackinabox/services/service.py
StackInABoxService.register_subservice
def register_subservice(self, uri, service): """Register a class instance to handle a URI. :param uri: string - URI for the request :param service: StackInABoxService object instance that handles the request :returns: n/a """ found = False self.create_route(uri, True) self.routes[uri]['handlers'].set_subservice(service)
python
def register_subservice(self, uri, service): """Register a class instance to handle a URI. :param uri: string - URI for the request :param service: StackInABoxService object instance that handles the request :returns: n/a """ found = False self.create_route(uri, True) self.routes[uri]['handlers'].set_subservice(service)
[ "def", "register_subservice", "(", "self", ",", "uri", ",", "service", ")", ":", "found", "=", "False", "self", ".", "create_route", "(", "uri", ",", "True", ")", "self", ".", "routes", "[", "uri", "]", "[", "'handlers'", "]", ".", "set_subservice", "(", "service", ")" ]
Register a class instance to handle a URI. :param uri: string - URI for the request :param service: StackInABoxService object instance that handles the request :returns: n/a
[ "Register", "a", "class", "instance", "to", "handle", "a", "URI", "." ]
63ee457401e9a88d987f85f513eb512dcb12d984
https://github.com/TestInABox/stackInABox/blob/63ee457401e9a88d987f85f513eb512dcb12d984/stackinabox/services/service.py#L440-L452
239,525
kervi/kervi-devices
kervi/devices/gpio/MCP230XX.py
_MCP230XX.pullup
def pullup(self, pin, enabled): """Turn on the pull-up resistor for the specified pin if enabled is True, otherwise turn off the pull-up resistor. """ self._validate_channel(pin) if enabled: self.gppu[int(pin/8)] |= 1 << (int(pin%8)) else: self.gppu[int(pin/8)] &= ~(1 << (int(pin%8))) self._write_gppu()
python
def pullup(self, pin, enabled): """Turn on the pull-up resistor for the specified pin if enabled is True, otherwise turn off the pull-up resistor. """ self._validate_channel(pin) if enabled: self.gppu[int(pin/8)] |= 1 << (int(pin%8)) else: self.gppu[int(pin/8)] &= ~(1 << (int(pin%8))) self._write_gppu()
[ "def", "pullup", "(", "self", ",", "pin", ",", "enabled", ")", ":", "self", ".", "_validate_channel", "(", "pin", ")", "if", "enabled", ":", "self", ".", "gppu", "[", "int", "(", "pin", "/", "8", ")", "]", "|=", "1", "<<", "(", "int", "(", "pin", "%", "8", ")", ")", "else", ":", "self", ".", "gppu", "[", "int", "(", "pin", "/", "8", ")", "]", "&=", "~", "(", "1", "<<", "(", "int", "(", "pin", "%", "8", ")", ")", ")", "self", ".", "_write_gppu", "(", ")" ]
Turn on the pull-up resistor for the specified pin if enabled is True, otherwise turn off the pull-up resistor.
[ "Turn", "on", "the", "pull", "-", "up", "resistor", "for", "the", "specified", "pin", "if", "enabled", "is", "True", "otherwise", "turn", "off", "the", "pull", "-", "up", "resistor", "." ]
c6aaddc6da1d0bce0ea2b0c6eb8393ba10aefa56
https://github.com/kervi/kervi-devices/blob/c6aaddc6da1d0bce0ea2b0c6eb8393ba10aefa56/kervi/devices/gpio/MCP230XX.py#L116-L125
239,526
kervi/kervi-devices
kervi/devices/gpio/MCP230XX.py
_MCP230XX._write_gpio
def _write_gpio(self, gpio=None): """Write the specified byte value to the GPIO registor. If no value specified the current buffered value will be written. """ if gpio is not None: self.gpio = gpio self.i2c.write_list(self.GPIO, self.gpio)
python
def _write_gpio(self, gpio=None): """Write the specified byte value to the GPIO registor. If no value specified the current buffered value will be written. """ if gpio is not None: self.gpio = gpio self.i2c.write_list(self.GPIO, self.gpio)
[ "def", "_write_gpio", "(", "self", ",", "gpio", "=", "None", ")", ":", "if", "gpio", "is", "not", "None", ":", "self", ".", "gpio", "=", "gpio", "self", ".", "i2c", ".", "write_list", "(", "self", ".", "GPIO", ",", "self", ".", "gpio", ")" ]
Write the specified byte value to the GPIO registor. If no value specified the current buffered value will be written.
[ "Write", "the", "specified", "byte", "value", "to", "the", "GPIO", "registor", ".", "If", "no", "value", "specified", "the", "current", "buffered", "value", "will", "be", "written", "." ]
c6aaddc6da1d0bce0ea2b0c6eb8393ba10aefa56
https://github.com/kervi/kervi-devices/blob/c6aaddc6da1d0bce0ea2b0c6eb8393ba10aefa56/kervi/devices/gpio/MCP230XX.py#L127-L133
239,527
kervi/kervi-devices
kervi/devices/gpio/MCP230XX.py
_MCP230XX._write_iodir
def _write_iodir(self, iodir=None): """Write the specified byte value to the IODIR registor. If no value specified the current buffered value will be written. """ if iodir is not None: self.iodir = iodir self.i2c.write_list(self.IODIR, self.iodir)
python
def _write_iodir(self, iodir=None): """Write the specified byte value to the IODIR registor. If no value specified the current buffered value will be written. """ if iodir is not None: self.iodir = iodir self.i2c.write_list(self.IODIR, self.iodir)
[ "def", "_write_iodir", "(", "self", ",", "iodir", "=", "None", ")", ":", "if", "iodir", "is", "not", "None", ":", "self", ".", "iodir", "=", "iodir", "self", ".", "i2c", ".", "write_list", "(", "self", ".", "IODIR", ",", "self", ".", "iodir", ")" ]
Write the specified byte value to the IODIR registor. If no value specified the current buffered value will be written.
[ "Write", "the", "specified", "byte", "value", "to", "the", "IODIR", "registor", ".", "If", "no", "value", "specified", "the", "current", "buffered", "value", "will", "be", "written", "." ]
c6aaddc6da1d0bce0ea2b0c6eb8393ba10aefa56
https://github.com/kervi/kervi-devices/blob/c6aaddc6da1d0bce0ea2b0c6eb8393ba10aefa56/kervi/devices/gpio/MCP230XX.py#L135-L141
239,528
kervi/kervi-devices
kervi/devices/gpio/MCP230XX.py
_MCP230XX._write_gppu
def _write_gppu(self, gppu=None): """Write the specified byte value to the GPPU registor. If no value specified the current buffered value will be written. """ if gppu is not None: self.gppu = gppu self.i2c.write_list(self.GPPU, self.gppu)
python
def _write_gppu(self, gppu=None): """Write the specified byte value to the GPPU registor. If no value specified the current buffered value will be written. """ if gppu is not None: self.gppu = gppu self.i2c.write_list(self.GPPU, self.gppu)
[ "def", "_write_gppu", "(", "self", ",", "gppu", "=", "None", ")", ":", "if", "gppu", "is", "not", "None", ":", "self", ".", "gppu", "=", "gppu", "self", ".", "i2c", ".", "write_list", "(", "self", ".", "GPPU", ",", "self", ".", "gppu", ")" ]
Write the specified byte value to the GPPU registor. If no value specified the current buffered value will be written.
[ "Write", "the", "specified", "byte", "value", "to", "the", "GPPU", "registor", ".", "If", "no", "value", "specified", "the", "current", "buffered", "value", "will", "be", "written", "." ]
c6aaddc6da1d0bce0ea2b0c6eb8393ba10aefa56
https://github.com/kervi/kervi-devices/blob/c6aaddc6da1d0bce0ea2b0c6eb8393ba10aefa56/kervi/devices/gpio/MCP230XX.py#L143-L149
239,529
Zincr0/pyscrap
pyscrap/spiders.py
getJson
def getJson(url): """Download json and return simplejson object""" site = urllib2.urlopen(url, timeout=300) return json.load(site)
python
def getJson(url): """Download json and return simplejson object""" site = urllib2.urlopen(url, timeout=300) return json.load(site)
[ "def", "getJson", "(", "url", ")", ":", "site", "=", "urllib2", ".", "urlopen", "(", "url", ",", "timeout", "=", "300", ")", "return", "json", ".", "load", "(", "site", ")" ]
Download json and return simplejson object
[ "Download", "json", "and", "return", "simplejson", "object" ]
69b4c2bd42dbec125444ad68a1f76168fab7607e
https://github.com/Zincr0/pyscrap/blob/69b4c2bd42dbec125444ad68a1f76168fab7607e/pyscrap/spiders.py#L43-L46
239,530
Zincr0/pyscrap
pyscrap/spiders.py
getWeb
def getWeb(url, isFeed): """Download url and parse it with lxml. If "isFeed" is True returns lxml.etree else, returns lxml.html """ socket.setdefaulttimeout(300) loadedWeb = urllib2.build_opener() loadedWeb.addheaders = getHeaders() if isFeed: web = etree.parse(loadedWeb.open(url)) else: web = html.parse(loadedWeb.open(url)) return web
python
def getWeb(url, isFeed): """Download url and parse it with lxml. If "isFeed" is True returns lxml.etree else, returns lxml.html """ socket.setdefaulttimeout(300) loadedWeb = urllib2.build_opener() loadedWeb.addheaders = getHeaders() if isFeed: web = etree.parse(loadedWeb.open(url)) else: web = html.parse(loadedWeb.open(url)) return web
[ "def", "getWeb", "(", "url", ",", "isFeed", ")", ":", "socket", ".", "setdefaulttimeout", "(", "300", ")", "loadedWeb", "=", "urllib2", ".", "build_opener", "(", ")", "loadedWeb", ".", "addheaders", "=", "getHeaders", "(", ")", "if", "isFeed", ":", "web", "=", "etree", ".", "parse", "(", "loadedWeb", ".", "open", "(", "url", ")", ")", "else", ":", "web", "=", "html", ".", "parse", "(", "loadedWeb", ".", "open", "(", "url", ")", ")", "return", "web" ]
Download url and parse it with lxml. If "isFeed" is True returns lxml.etree else, returns lxml.html
[ "Download", "url", "and", "parse", "it", "with", "lxml", ".", "If", "isFeed", "is", "True", "returns", "lxml", ".", "etree", "else", "returns", "lxml", ".", "html" ]
69b4c2bd42dbec125444ad68a1f76168fab7607e
https://github.com/Zincr0/pyscrap/blob/69b4c2bd42dbec125444ad68a1f76168fab7607e/pyscrap/spiders.py#L49-L61
239,531
Zincr0/pyscrap
pyscrap/spiders.py
rmSelf
def rmSelf(f): """f -> function. Decorator, removes first argument from f parameters. """ def new_f(*args, **kwargs): newArgs = args[1:] result = f(*newArgs, **kwargs) return result return new_f
python
def rmSelf(f): """f -> function. Decorator, removes first argument from f parameters. """ def new_f(*args, **kwargs): newArgs = args[1:] result = f(*newArgs, **kwargs) return result return new_f
[ "def", "rmSelf", "(", "f", ")", ":", "def", "new_f", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "newArgs", "=", "args", "[", "1", ":", "]", "result", "=", "f", "(", "*", "newArgs", ",", "*", "*", "kwargs", ")", "return", "result", "return", "new_f" ]
f -> function. Decorator, removes first argument from f parameters.
[ "f", "-", ">", "function", ".", "Decorator", "removes", "first", "argument", "from", "f", "parameters", "." ]
69b4c2bd42dbec125444ad68a1f76168fab7607e
https://github.com/Zincr0/pyscrap/blob/69b4c2bd42dbec125444ad68a1f76168fab7607e/pyscrap/spiders.py#L64-L72
239,532
roboogle/gtkmvc3
gtkmvco/gtkmvc3/view.py
View.__builder_connect_pending_signals
def __builder_connect_pending_signals(self): """Called internally to actually make the internal Gtk.Builder instance connect all signals found in controllers controlling self.""" class _MultiHandlersProxy (object): def __init__(self, funcs): self.funcs = funcs def __call__(self, *args, **kwargs): # according to gtk documentation, the return value of # a signal is the return value of the last executed # handler for func in self.funcs: res = func(*args, **kwargs) return res final_dict = {n: (v.pop() if len(v) == 1 else _MultiHandlersProxy(v)) for n, v in self.builder_pending_callbacks.items()} self._builder.connect_signals(final_dict) self.builder_connected = True self.builder_pending_callbacks = {}
python
def __builder_connect_pending_signals(self): """Called internally to actually make the internal Gtk.Builder instance connect all signals found in controllers controlling self.""" class _MultiHandlersProxy (object): def __init__(self, funcs): self.funcs = funcs def __call__(self, *args, **kwargs): # according to gtk documentation, the return value of # a signal is the return value of the last executed # handler for func in self.funcs: res = func(*args, **kwargs) return res final_dict = {n: (v.pop() if len(v) == 1 else _MultiHandlersProxy(v)) for n, v in self.builder_pending_callbacks.items()} self._builder.connect_signals(final_dict) self.builder_connected = True self.builder_pending_callbacks = {}
[ "def", "__builder_connect_pending_signals", "(", "self", ")", ":", "class", "_MultiHandlersProxy", "(", "object", ")", ":", "def", "__init__", "(", "self", ",", "funcs", ")", ":", "self", ".", "funcs", "=", "funcs", "def", "__call__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# according to gtk documentation, the return value of", "# a signal is the return value of the last executed", "# handler", "for", "func", "in", "self", ".", "funcs", ":", "res", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "res", "final_dict", "=", "{", "n", ":", "(", "v", ".", "pop", "(", ")", "if", "len", "(", "v", ")", "==", "1", "else", "_MultiHandlersProxy", "(", "v", ")", ")", "for", "n", ",", "v", "in", "self", ".", "builder_pending_callbacks", ".", "items", "(", ")", "}", "self", ".", "_builder", ".", "connect_signals", "(", "final_dict", ")", "self", ".", "builder_connected", "=", "True", "self", ".", "builder_pending_callbacks", "=", "{", "}" ]
Called internally to actually make the internal Gtk.Builder instance connect all signals found in controllers controlling self.
[ "Called", "internally", "to", "actually", "make", "the", "internal", "Gtk", ".", "Builder", "instance", "connect", "all", "signals", "found", "in", "controllers", "controlling", "self", "." ]
63405fd8d2056be26af49103b13a8d5e57fe4dff
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/view.py#L222-L243
239,533
roboogle/gtkmvc3
gtkmvco/gtkmvc3/view.py
View._builder_connect_signals
def _builder_connect_signals(self, _dict): """Called by controllers which want to autoconnect their handlers with signals declared in internal Gtk.Builder. This method accumulates handlers, and books signal autoconnection later on the idle of the next occurring gtk loop. After the autoconnection is done, this method cannot be called anymore.""" assert not self.builder_connected, "Gtk.Builder not already connected" if _dict and not self.builder_pending_callbacks: # this is the first call, book the builder connection for # later gtk loop GLib.idle_add(self.__builder_connect_pending_signals) for n, v in _dict.items(): if n not in self.builder_pending_callbacks: _set = set() self.builder_pending_callbacks[n] = _set else: _set = self.builder_pending_callbacks[n] _set.add(v)
python
def _builder_connect_signals(self, _dict): """Called by controllers which want to autoconnect their handlers with signals declared in internal Gtk.Builder. This method accumulates handlers, and books signal autoconnection later on the idle of the next occurring gtk loop. After the autoconnection is done, this method cannot be called anymore.""" assert not self.builder_connected, "Gtk.Builder not already connected" if _dict and not self.builder_pending_callbacks: # this is the first call, book the builder connection for # later gtk loop GLib.idle_add(self.__builder_connect_pending_signals) for n, v in _dict.items(): if n not in self.builder_pending_callbacks: _set = set() self.builder_pending_callbacks[n] = _set else: _set = self.builder_pending_callbacks[n] _set.add(v)
[ "def", "_builder_connect_signals", "(", "self", ",", "_dict", ")", ":", "assert", "not", "self", ".", "builder_connected", ",", "\"Gtk.Builder not already connected\"", "if", "_dict", "and", "not", "self", ".", "builder_pending_callbacks", ":", "# this is the first call, book the builder connection for", "# later gtk loop", "GLib", ".", "idle_add", "(", "self", ".", "__builder_connect_pending_signals", ")", "for", "n", ",", "v", "in", "_dict", ".", "items", "(", ")", ":", "if", "n", "not", "in", "self", ".", "builder_pending_callbacks", ":", "_set", "=", "set", "(", ")", "self", ".", "builder_pending_callbacks", "[", "n", "]", "=", "_set", "else", ":", "_set", "=", "self", ".", "builder_pending_callbacks", "[", "n", "]", "_set", ".", "add", "(", "v", ")" ]
Called by controllers which want to autoconnect their handlers with signals declared in internal Gtk.Builder. This method accumulates handlers, and books signal autoconnection later on the idle of the next occurring gtk loop. After the autoconnection is done, this method cannot be called anymore.
[ "Called", "by", "controllers", "which", "want", "to", "autoconnect", "their", "handlers", "with", "signals", "declared", "in", "internal", "Gtk", ".", "Builder", "." ]
63405fd8d2056be26af49103b13a8d5e57fe4dff
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/view.py#L245-L267
239,534
roboogle/gtkmvc3
gtkmvco/gtkmvc3/view.py
View.__extract_autoWidgets
def __extract_autoWidgets(self): """Extract autoWidgets map if needed, out of the glade specifications and gtk builder""" if self.__autoWidgets_calculated: return if self._builder is not None: for wid in self._builder.get_objects(): # General workaround for issue # https://bugzilla.gnome.org/show_bug.cgi?id=607492 try: name = Gtk.Buildable.get_name(wid) except TypeError: continue if name in self.autoWidgets and self.autoWidgets[name] != wid: raise ViewError("Widget '%s' in builder also found in " "glade specification" % name) self.autoWidgets[name] = wid self.__autowidgets_calculated = True
python
def __extract_autoWidgets(self): """Extract autoWidgets map if needed, out of the glade specifications and gtk builder""" if self.__autoWidgets_calculated: return if self._builder is not None: for wid in self._builder.get_objects(): # General workaround for issue # https://bugzilla.gnome.org/show_bug.cgi?id=607492 try: name = Gtk.Buildable.get_name(wid) except TypeError: continue if name in self.autoWidgets and self.autoWidgets[name] != wid: raise ViewError("Widget '%s' in builder also found in " "glade specification" % name) self.autoWidgets[name] = wid self.__autowidgets_calculated = True
[ "def", "__extract_autoWidgets", "(", "self", ")", ":", "if", "self", ".", "__autoWidgets_calculated", ":", "return", "if", "self", ".", "_builder", "is", "not", "None", ":", "for", "wid", "in", "self", ".", "_builder", ".", "get_objects", "(", ")", ":", "# General workaround for issue", "# https://bugzilla.gnome.org/show_bug.cgi?id=607492", "try", ":", "name", "=", "Gtk", ".", "Buildable", ".", "get_name", "(", "wid", ")", "except", "TypeError", ":", "continue", "if", "name", "in", "self", ".", "autoWidgets", "and", "self", ".", "autoWidgets", "[", "name", "]", "!=", "wid", ":", "raise", "ViewError", "(", "\"Widget '%s' in builder also found in \"", "\"glade specification\"", "%", "name", ")", "self", ".", "autoWidgets", "[", "name", "]", "=", "wid", "self", ".", "__autowidgets_calculated", "=", "True" ]
Extract autoWidgets map if needed, out of the glade specifications and gtk builder
[ "Extract", "autoWidgets", "map", "if", "needed", "out", "of", "the", "glade", "specifications", "and", "gtk", "builder" ]
63405fd8d2056be26af49103b13a8d5e57fe4dff
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/view.py#L284-L304
239,535
clef/clef-python
clef/clef.py
clef_error_check
def clef_error_check(func_to_decorate): """Return JSON decoded response from API call. Handle errors when bad response encountered.""" def wrapper(*args, **kwargs): try: response = func_to_decorate(*args, **kwargs) except requests.exceptions.RequestException: raise ConnectionError( 'Clef encountered a network connectivity problem. Are you sure you are connected to the Internet?' ) else: raise_right_error(response) return response.json() # decode json return wrapper
python
def clef_error_check(func_to_decorate): """Return JSON decoded response from API call. Handle errors when bad response encountered.""" def wrapper(*args, **kwargs): try: response = func_to_decorate(*args, **kwargs) except requests.exceptions.RequestException: raise ConnectionError( 'Clef encountered a network connectivity problem. Are you sure you are connected to the Internet?' ) else: raise_right_error(response) return response.json() # decode json return wrapper
[ "def", "clef_error_check", "(", "func_to_decorate", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "response", "=", "func_to_decorate", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "requests", ".", "exceptions", ".", "RequestException", ":", "raise", "ConnectionError", "(", "'Clef encountered a network connectivity problem. Are you sure you are connected to the Internet?'", ")", "else", ":", "raise_right_error", "(", "response", ")", "return", "response", ".", "json", "(", ")", "# decode json", "return", "wrapper" ]
Return JSON decoded response from API call. Handle errors when bad response encountered.
[ "Return", "JSON", "decoded", "response", "from", "API", "call", ".", "Handle", "errors", "when", "bad", "response", "encountered", "." ]
bee3cfd26c76fc9df64877b214181121f8bfad80
https://github.com/clef/clef-python/blob/bee3cfd26c76fc9df64877b214181121f8bfad80/clef/clef.py#L29-L41
239,536
clef/clef-python
clef/clef.py
raise_right_error
def raise_right_error(response): """Raise appropriate error when bad response received.""" if response.status_code == 200: return if response.status_code == 500: raise ServerError('Clef servers are down.') if response.status_code == 403: message = response.json().get('error') error_class = MESSAGE_TO_ERROR_MAP[message] if error_class == InvalidOAuthTokenError: message = 'Something went wrong at Clef. Unable to retrieve user information with this token.' raise error_class(message) if response.status_code == 400: message = response.json().get('error') error_class = MESSAGE_TO_ERROR_MAP[message] if error_class: raise error_class(message) else: raise InvalidLogoutTokenError(message) if response.status_code == 404: raise NotFoundError('Unable to retrieve the page. Are you sure the Clef API endpoint is configured right?') raise APIError
python
def raise_right_error(response): """Raise appropriate error when bad response received.""" if response.status_code == 200: return if response.status_code == 500: raise ServerError('Clef servers are down.') if response.status_code == 403: message = response.json().get('error') error_class = MESSAGE_TO_ERROR_MAP[message] if error_class == InvalidOAuthTokenError: message = 'Something went wrong at Clef. Unable to retrieve user information with this token.' raise error_class(message) if response.status_code == 400: message = response.json().get('error') error_class = MESSAGE_TO_ERROR_MAP[message] if error_class: raise error_class(message) else: raise InvalidLogoutTokenError(message) if response.status_code == 404: raise NotFoundError('Unable to retrieve the page. Are you sure the Clef API endpoint is configured right?') raise APIError
[ "def", "raise_right_error", "(", "response", ")", ":", "if", "response", ".", "status_code", "==", "200", ":", "return", "if", "response", ".", "status_code", "==", "500", ":", "raise", "ServerError", "(", "'Clef servers are down.'", ")", "if", "response", ".", "status_code", "==", "403", ":", "message", "=", "response", ".", "json", "(", ")", ".", "get", "(", "'error'", ")", "error_class", "=", "MESSAGE_TO_ERROR_MAP", "[", "message", "]", "if", "error_class", "==", "InvalidOAuthTokenError", ":", "message", "=", "'Something went wrong at Clef. Unable to retrieve user information with this token.'", "raise", "error_class", "(", "message", ")", "if", "response", ".", "status_code", "==", "400", ":", "message", "=", "response", ".", "json", "(", ")", ".", "get", "(", "'error'", ")", "error_class", "=", "MESSAGE_TO_ERROR_MAP", "[", "message", "]", "if", "error_class", ":", "raise", "error_class", "(", "message", ")", "else", ":", "raise", "InvalidLogoutTokenError", "(", "message", ")", "if", "response", ".", "status_code", "==", "404", ":", "raise", "NotFoundError", "(", "'Unable to retrieve the page. Are you sure the Clef API endpoint is configured right?'", ")", "raise", "APIError" ]
Raise appropriate error when bad response received.
[ "Raise", "appropriate", "error", "when", "bad", "response", "received", "." ]
bee3cfd26c76fc9df64877b214181121f8bfad80
https://github.com/clef/clef-python/blob/bee3cfd26c76fc9df64877b214181121f8bfad80/clef/clef.py#L43-L64
239,537
clef/clef-python
clef/clef.py
ClefAPI._call
def _call(self, method, url, params): """Return response from Clef API call.""" request_params = {} if method == 'GET': request_params['params'] = params elif method == 'POST': request_params['data'] = params response = requests.request(method, url, **request_params) return response
python
def _call(self, method, url, params): """Return response from Clef API call.""" request_params = {} if method == 'GET': request_params['params'] = params elif method == 'POST': request_params['data'] = params response = requests.request(method, url, **request_params) return response
[ "def", "_call", "(", "self", ",", "method", ",", "url", ",", "params", ")", ":", "request_params", "=", "{", "}", "if", "method", "==", "'GET'", ":", "request_params", "[", "'params'", "]", "=", "params", "elif", "method", "==", "'POST'", ":", "request_params", "[", "'data'", "]", "=", "params", "response", "=", "requests", ".", "request", "(", "method", ",", "url", ",", "*", "*", "request_params", ")", "return", "response" ]
Return response from Clef API call.
[ "Return", "response", "from", "Clef", "API", "call", "." ]
bee3cfd26c76fc9df64877b214181121f8bfad80
https://github.com/clef/clef-python/blob/bee3cfd26c76fc9df64877b214181121f8bfad80/clef/clef.py#L80-L88
239,538
clef/clef-python
clef/clef.py
ClefAPI.get_login_information
def get_login_information(self, code=None): """Return Clef user info after exchanging code for OAuth token.""" # do the handshake to get token access_token = self._get_access_token(code) # make request with token to get user details return self._get_user_info(access_token)
python
def get_login_information(self, code=None): """Return Clef user info after exchanging code for OAuth token.""" # do the handshake to get token access_token = self._get_access_token(code) # make request with token to get user details return self._get_user_info(access_token)
[ "def", "get_login_information", "(", "self", ",", "code", "=", "None", ")", ":", "# do the handshake to get token", "access_token", "=", "self", ".", "_get_access_token", "(", "code", ")", "# make request with token to get user details", "return", "self", ".", "_get_user_info", "(", "access_token", ")" ]
Return Clef user info after exchanging code for OAuth token.
[ "Return", "Clef", "user", "info", "after", "exchanging", "code", "for", "OAuth", "token", "." ]
bee3cfd26c76fc9df64877b214181121f8bfad80
https://github.com/clef/clef-python/blob/bee3cfd26c76fc9df64877b214181121f8bfad80/clef/clef.py#L90-L95
239,539
clef/clef-python
clef/clef.py
ClefAPI._get_user_info
def _get_user_info(self, access_token): """Return Clef user info.""" info_response = self._call('GET', self.info_url, params={'access_token': access_token}) user_info = info_response.get('info') return user_info
python
def _get_user_info(self, access_token): """Return Clef user info.""" info_response = self._call('GET', self.info_url, params={'access_token': access_token}) user_info = info_response.get('info') return user_info
[ "def", "_get_user_info", "(", "self", ",", "access_token", ")", ":", "info_response", "=", "self", ".", "_call", "(", "'GET'", ",", "self", ".", "info_url", ",", "params", "=", "{", "'access_token'", ":", "access_token", "}", ")", "user_info", "=", "info_response", ".", "get", "(", "'info'", ")", "return", "user_info" ]
Return Clef user info.
[ "Return", "Clef", "user", "info", "." ]
bee3cfd26c76fc9df64877b214181121f8bfad80
https://github.com/clef/clef-python/blob/bee3cfd26c76fc9df64877b214181121f8bfad80/clef/clef.py#L107-L111
239,540
clef/clef-python
clef/clef.py
ClefAPI.get_logout_information
def get_logout_information(self, logout_token): """Return Clef user info after exchanging logout token.""" data = dict(logout_token=logout_token, app_id=self.app_id, app_secret=self.app_secret) logout_response = self._call('POST', self.logout_url, params=data) clef_user_id = logout_response.get('clef_id') return clef_user_id
python
def get_logout_information(self, logout_token): """Return Clef user info after exchanging logout token.""" data = dict(logout_token=logout_token, app_id=self.app_id, app_secret=self.app_secret) logout_response = self._call('POST', self.logout_url, params=data) clef_user_id = logout_response.get('clef_id') return clef_user_id
[ "def", "get_logout_information", "(", "self", ",", "logout_token", ")", ":", "data", "=", "dict", "(", "logout_token", "=", "logout_token", ",", "app_id", "=", "self", ".", "app_id", ",", "app_secret", "=", "self", ".", "app_secret", ")", "logout_response", "=", "self", ".", "_call", "(", "'POST'", ",", "self", ".", "logout_url", ",", "params", "=", "data", ")", "clef_user_id", "=", "logout_response", ".", "get", "(", "'clef_id'", ")", "return", "clef_user_id" ]
Return Clef user info after exchanging logout token.
[ "Return", "Clef", "user", "info", "after", "exchanging", "logout", "token", "." ]
bee3cfd26c76fc9df64877b214181121f8bfad80
https://github.com/clef/clef-python/blob/bee3cfd26c76fc9df64877b214181121f8bfad80/clef/clef.py#L113-L118
239,541
roboogle/gtkmvc3
gtkmvco/gtkmvc3/observer.py
Observer.remove_observing_method
def remove_observing_method(self, prop_names, method): """ Remove dynamic notifications. *method* a callable that was registered with :meth:`observe`. *prop_names* a sequence of strings. This need not correspond to any one `observe` call. .. note:: This can revert even the effects of decorator `observe` at runtime. Don't. """ for prop_name in prop_names: if prop_name in self.__PROP_TO_METHS: # exact match self.__PROP_TO_METHS[prop_name].remove(method) del self.__PAT_METH_TO_KWARGS[(prop_name, method)] elif method in self.__METH_TO_PAT: # found a pattern matching pat = self.__METH_TO_PAT[method] if fnmatch.fnmatch(prop_name, pat): del self.__METH_TO_PAT[method] self.__PAT_TO_METHS[pat].remove(method) del self.__PAT_METH_TO_KWARGS[(pat, method)]
python
def remove_observing_method(self, prop_names, method): """ Remove dynamic notifications. *method* a callable that was registered with :meth:`observe`. *prop_names* a sequence of strings. This need not correspond to any one `observe` call. .. note:: This can revert even the effects of decorator `observe` at runtime. Don't. """ for prop_name in prop_names: if prop_name in self.__PROP_TO_METHS: # exact match self.__PROP_TO_METHS[prop_name].remove(method) del self.__PAT_METH_TO_KWARGS[(prop_name, method)] elif method in self.__METH_TO_PAT: # found a pattern matching pat = self.__METH_TO_PAT[method] if fnmatch.fnmatch(prop_name, pat): del self.__METH_TO_PAT[method] self.__PAT_TO_METHS[pat].remove(method) del self.__PAT_METH_TO_KWARGS[(pat, method)]
[ "def", "remove_observing_method", "(", "self", ",", "prop_names", ",", "method", ")", ":", "for", "prop_name", "in", "prop_names", ":", "if", "prop_name", "in", "self", ".", "__PROP_TO_METHS", ":", "# exact match", "self", ".", "__PROP_TO_METHS", "[", "prop_name", "]", ".", "remove", "(", "method", ")", "del", "self", ".", "__PAT_METH_TO_KWARGS", "[", "(", "prop_name", ",", "method", ")", "]", "elif", "method", "in", "self", ".", "__METH_TO_PAT", ":", "# found a pattern matching", "pat", "=", "self", ".", "__METH_TO_PAT", "[", "method", "]", "if", "fnmatch", ".", "fnmatch", "(", "prop_name", ",", "pat", ")", ":", "del", "self", ".", "__METH_TO_PAT", "[", "method", "]", "self", ".", "__PAT_TO_METHS", "[", "pat", "]", ".", "remove", "(", "method", ")", "del", "self", ".", "__PAT_METH_TO_KWARGS", "[", "(", "pat", ",", "method", ")", "]" ]
Remove dynamic notifications. *method* a callable that was registered with :meth:`observe`. *prop_names* a sequence of strings. This need not correspond to any one `observe` call. .. note:: This can revert even the effects of decorator `observe` at runtime. Don't.
[ "Remove", "dynamic", "notifications", "." ]
63405fd8d2056be26af49103b13a8d5e57fe4dff
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/observer.py#L401-L427
239,542
roboogle/gtkmvc3
gtkmvco/gtkmvc3/observer.py
Observer.is_observing_method
def is_observing_method(self, prop_name, method): """ Returns `True` if the given method was previously added as an observing method, either dynamically or via decorator. """ if (prop_name, method) in self.__PAT_METH_TO_KWARGS: return True if method in self.__METH_TO_PAT: pat = self.__METH_TO_PAT[method] if fnmatch.fnmatch(prop_name, pat): return True return False
python
def is_observing_method(self, prop_name, method): """ Returns `True` if the given method was previously added as an observing method, either dynamically or via decorator. """ if (prop_name, method) in self.__PAT_METH_TO_KWARGS: return True if method in self.__METH_TO_PAT: pat = self.__METH_TO_PAT[method] if fnmatch.fnmatch(prop_name, pat): return True return False
[ "def", "is_observing_method", "(", "self", ",", "prop_name", ",", "method", ")", ":", "if", "(", "prop_name", ",", "method", ")", "in", "self", ".", "__PAT_METH_TO_KWARGS", ":", "return", "True", "if", "method", "in", "self", ".", "__METH_TO_PAT", ":", "pat", "=", "self", ".", "__METH_TO_PAT", "[", "method", "]", "if", "fnmatch", ".", "fnmatch", "(", "prop_name", ",", "pat", ")", ":", "return", "True", "return", "False" ]
Returns `True` if the given method was previously added as an observing method, either dynamically or via decorator.
[ "Returns", "True", "if", "the", "given", "method", "was", "previously", "added", "as", "an", "observing", "method", "either", "dynamically", "or", "via", "decorator", "." ]
63405fd8d2056be26af49103b13a8d5e57fe4dff
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/observer.py#L429-L441
239,543
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/treemodel.py
ListItemData.set_data
def set_data(self, column, value, role): """Set the data for the given column to value The default implementation returns False :param column: the column to set :type column: int :param value: the value to set :param role: the role, usually EditRole :type role: :class:`QtCore.Qt.ItemDataRole` :returns: True, if editing was successfull :rtype: :class:`bool` :raises: None """ if role == QtCore.Qt.EditRole or role == QtCore.Qt.DisplayRole: self._list[column] = value return True else: return False
python
def set_data(self, column, value, role): """Set the data for the given column to value The default implementation returns False :param column: the column to set :type column: int :param value: the value to set :param role: the role, usually EditRole :type role: :class:`QtCore.Qt.ItemDataRole` :returns: True, if editing was successfull :rtype: :class:`bool` :raises: None """ if role == QtCore.Qt.EditRole or role == QtCore.Qt.DisplayRole: self._list[column] = value return True else: return False
[ "def", "set_data", "(", "self", ",", "column", ",", "value", ",", "role", ")", ":", "if", "role", "==", "QtCore", ".", "Qt", ".", "EditRole", "or", "role", "==", "QtCore", ".", "Qt", ".", "DisplayRole", ":", "self", ".", "_list", "[", "column", "]", "=", "value", "return", "True", "else", ":", "return", "False" ]
Set the data for the given column to value The default implementation returns False :param column: the column to set :type column: int :param value: the value to set :param role: the role, usually EditRole :type role: :class:`QtCore.Qt.ItemDataRole` :returns: True, if editing was successfull :rtype: :class:`bool` :raises: None
[ "Set", "the", "data", "for", "the", "given", "column", "to", "value" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/treemodel.py#L139-L157
239,544
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/treemodel.py
TreeItem.set_model
def set_model(self, model): """Set the model the item belongs to A TreeItem can only belong to one model. :param model: the model the item belongs to :type model: :class:`Treemodel` :returns: None :rtype: None :raises: None """ self._model = model for c in self.childItems: c.set_model(model)
python
def set_model(self, model): """Set the model the item belongs to A TreeItem can only belong to one model. :param model: the model the item belongs to :type model: :class:`Treemodel` :returns: None :rtype: None :raises: None """ self._model = model for c in self.childItems: c.set_model(model)
[ "def", "set_model", "(", "self", ",", "model", ")", ":", "self", ".", "_model", "=", "model", "for", "c", "in", "self", ".", "childItems", ":", "c", ".", "set_model", "(", "model", ")" ]
Set the model the item belongs to A TreeItem can only belong to one model. :param model: the model the item belongs to :type model: :class:`Treemodel` :returns: None :rtype: None :raises: None
[ "Set", "the", "model", "the", "item", "belongs", "to" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/treemodel.py#L241-L254
239,545
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/treemodel.py
TreeItem.add_child
def add_child(self, child): """Add child to children of this TreeItem :param child: the child TreeItem :type child: :class:`TreeItem` :returns: None :rtype: None :raises: None """ child.set_model(self._model) if self._model: row = len(self.childItems) parentindex = self._model.index_of_item(self) self._model.insertRow(row, child, parentindex) else: self.childItems.append(child)
python
def add_child(self, child): """Add child to children of this TreeItem :param child: the child TreeItem :type child: :class:`TreeItem` :returns: None :rtype: None :raises: None """ child.set_model(self._model) if self._model: row = len(self.childItems) parentindex = self._model.index_of_item(self) self._model.insertRow(row, child, parentindex) else: self.childItems.append(child)
[ "def", "add_child", "(", "self", ",", "child", ")", ":", "child", ".", "set_model", "(", "self", ".", "_model", ")", "if", "self", ".", "_model", ":", "row", "=", "len", "(", "self", ".", "childItems", ")", "parentindex", "=", "self", ".", "_model", ".", "index_of_item", "(", "self", ")", "self", ".", "_model", ".", "insertRow", "(", "row", ",", "child", ",", "parentindex", ")", "else", ":", "self", ".", "childItems", ".", "append", "(", "child", ")" ]
Add child to children of this TreeItem :param child: the child TreeItem :type child: :class:`TreeItem` :returns: None :rtype: None :raises: None
[ "Add", "child", "to", "children", "of", "this", "TreeItem" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/treemodel.py#L256-L271
239,546
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/treemodel.py
TreeItem.remove_child
def remove_child(self, child): """Remove the child from this TreeItem :param child: the child TreeItem :type child: :class:`TreeItem` :returns: None :rtype: None :raises: ValueError """ child.set_model(None) if self._model: row = self.childItems.index(child) parentindex = self._model.index_of_item(self) self._model.removeRow(row, parentindex) else: self.childItems.remove(child)
python
def remove_child(self, child): """Remove the child from this TreeItem :param child: the child TreeItem :type child: :class:`TreeItem` :returns: None :rtype: None :raises: ValueError """ child.set_model(None) if self._model: row = self.childItems.index(child) parentindex = self._model.index_of_item(self) self._model.removeRow(row, parentindex) else: self.childItems.remove(child)
[ "def", "remove_child", "(", "self", ",", "child", ")", ":", "child", ".", "set_model", "(", "None", ")", "if", "self", ".", "_model", ":", "row", "=", "self", ".", "childItems", ".", "index", "(", "child", ")", "parentindex", "=", "self", ".", "_model", ".", "index_of_item", "(", "self", ")", "self", ".", "_model", ".", "removeRow", "(", "row", ",", "parentindex", ")", "else", ":", "self", ".", "childItems", ".", "remove", "(", "child", ")" ]
Remove the child from this TreeItem :param child: the child TreeItem :type child: :class:`TreeItem` :returns: None :rtype: None :raises: ValueError
[ "Remove", "the", "child", "from", "this", "TreeItem" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/treemodel.py#L273-L288
239,547
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/treemodel.py
TreeItem.column_count
def column_count(self, ): """Return the number of columns that the children have If there are no children, return the column count of its own data. :returns: the column count of the children data :rtype: int :raises: None """ if self.child_count(): return self.childItems[0]._data.column_count() else: return self._data.column_count() if self._data else 0
python
def column_count(self, ): """Return the number of columns that the children have If there are no children, return the column count of its own data. :returns: the column count of the children data :rtype: int :raises: None """ if self.child_count(): return self.childItems[0]._data.column_count() else: return self._data.column_count() if self._data else 0
[ "def", "column_count", "(", "self", ",", ")", ":", "if", "self", ".", "child_count", "(", ")", ":", "return", "self", ".", "childItems", "[", "0", "]", ".", "_data", ".", "column_count", "(", ")", "else", ":", "return", "self", ".", "_data", ".", "column_count", "(", ")", "if", "self", ".", "_data", "else", "0" ]
Return the number of columns that the children have If there are no children, return the column count of its own data. :returns: the column count of the children data :rtype: int :raises: None
[ "Return", "the", "number", "of", "columns", "that", "the", "children", "have" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/treemodel.py#L321-L333
239,548
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/treemodel.py
TreeItem.data
def data(self, column, role): """Return the data for the column and role :param column: the data column :type column: int :param role: the data role :type role: QtCore.Qt.ItemDataRole :returns: data depending on the role :rtype: :raises: None """ if self._data is not None and (column >= 0 or column < self._data.column_count()): return self._data.data(column, role)
python
def data(self, column, role): """Return the data for the column and role :param column: the data column :type column: int :param role: the data role :type role: QtCore.Qt.ItemDataRole :returns: data depending on the role :rtype: :raises: None """ if self._data is not None and (column >= 0 or column < self._data.column_count()): return self._data.data(column, role)
[ "def", "data", "(", "self", ",", "column", ",", "role", ")", ":", "if", "self", ".", "_data", "is", "not", "None", "and", "(", "column", ">=", "0", "or", "column", "<", "self", ".", "_data", ".", "column_count", "(", ")", ")", ":", "return", "self", ".", "_data", ".", "data", "(", "column", ",", "role", ")" ]
Return the data for the column and role :param column: the data column :type column: int :param role: the data role :type role: QtCore.Qt.ItemDataRole :returns: data depending on the role :rtype: :raises: None
[ "Return", "the", "data", "for", "the", "column", "and", "role" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/treemodel.py#L335-L347
239,549
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/treemodel.py
TreeItem.set_data
def set_data(self, column, value, role): """Set the data of column to value :param column: the column to set :type column: int :param value: the value to set :param role: the role, usually EditRole :type role: :class:`QtCore.Qt.ItemDataRole` :returns: True, if data successfully changed :rtype: :class:`bool` :raises: None """ if not self._data or column >= self._data.column_count(): return False return self._data.set_data(column, value, role)
python
def set_data(self, column, value, role): """Set the data of column to value :param column: the column to set :type column: int :param value: the value to set :param role: the role, usually EditRole :type role: :class:`QtCore.Qt.ItemDataRole` :returns: True, if data successfully changed :rtype: :class:`bool` :raises: None """ if not self._data or column >= self._data.column_count(): return False return self._data.set_data(column, value, role)
[ "def", "set_data", "(", "self", ",", "column", ",", "value", ",", "role", ")", ":", "if", "not", "self", ".", "_data", "or", "column", ">=", "self", ".", "_data", ".", "column_count", "(", ")", ":", "return", "False", "return", "self", ".", "_data", ".", "set_data", "(", "column", ",", "value", ",", "role", ")" ]
Set the data of column to value :param column: the column to set :type column: int :param value: the value to set :param role: the role, usually EditRole :type role: :class:`QtCore.Qt.ItemDataRole` :returns: True, if data successfully changed :rtype: :class:`bool` :raises: None
[ "Set", "the", "data", "of", "column", "to", "value" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/treemodel.py#L349-L363
239,550
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/treemodel.py
TreeItem.set_parent
def set_parent(self, parent): """Set the parent of the treeitem :param parent: parent treeitem :type parent: :class:`TreeItem` | None :returns: None :rtype: None :raises: None """ if self._parent == parent: return if self._parent: self._parent.remove_child(self) self._parent = parent if parent: parent.add_child(self)
python
def set_parent(self, parent): """Set the parent of the treeitem :param parent: parent treeitem :type parent: :class:`TreeItem` | None :returns: None :rtype: None :raises: None """ if self._parent == parent: return if self._parent: self._parent.remove_child(self) self._parent = parent if parent: parent.add_child(self)
[ "def", "set_parent", "(", "self", ",", "parent", ")", ":", "if", "self", ".", "_parent", "==", "parent", ":", "return", "if", "self", ".", "_parent", ":", "self", ".", "_parent", ".", "remove_child", "(", "self", ")", "self", ".", "_parent", "=", "parent", "if", "parent", ":", "parent", ".", "add_child", "(", "self", ")" ]
Set the parent of the treeitem :param parent: parent treeitem :type parent: :class:`TreeItem` | None :returns: None :rtype: None :raises: None
[ "Set", "the", "parent", "of", "the", "treeitem" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/treemodel.py#L374-L389
239,551
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/treemodel.py
TreeModel.rowCount
def rowCount(self, parent): """Return the number of rows under the given parent. When the parent is valid return rowCount the number of children of parent. :param parent: the parent index :type parent: :class:`QtCore.QModelIndex`: :returns: the row count :rtype: int :raises: None """ if parent.column() > 0: return 0 if not parent.isValid(): parentItem = self._root else: parentItem = parent.internalPointer() return parentItem.child_count()
python
def rowCount(self, parent): """Return the number of rows under the given parent. When the parent is valid return rowCount the number of children of parent. :param parent: the parent index :type parent: :class:`QtCore.QModelIndex`: :returns: the row count :rtype: int :raises: None """ if parent.column() > 0: return 0 if not parent.isValid(): parentItem = self._root else: parentItem = parent.internalPointer() return parentItem.child_count()
[ "def", "rowCount", "(", "self", ",", "parent", ")", ":", "if", "parent", ".", "column", "(", ")", ">", "0", ":", "return", "0", "if", "not", "parent", ".", "isValid", "(", ")", ":", "parentItem", "=", "self", ".", "_root", "else", ":", "parentItem", "=", "parent", ".", "internalPointer", "(", ")", "return", "parentItem", ".", "child_count", "(", ")" ]
Return the number of rows under the given parent. When the parent is valid return rowCount the number of children of parent. :param parent: the parent index :type parent: :class:`QtCore.QModelIndex`: :returns: the row count :rtype: int :raises: None
[ "Return", "the", "number", "of", "rows", "under", "the", "given", "parent", ".", "When", "the", "parent", "is", "valid", "return", "rowCount", "the", "number", "of", "children", "of", "parent", "." ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/treemodel.py#L502-L519
239,552
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/treemodel.py
TreeModel.columnCount
def columnCount(self, parent): """Return the number of columns for the children of the given parent. :param parent: the parent index :type parent: :class:`QtCore.QModelIndex`: :returns: the column count :rtype: int :raises: None """ if parent.isValid(): return parent.internalPointer().column_count() else: return self._root.column_count()
python
def columnCount(self, parent): """Return the number of columns for the children of the given parent. :param parent: the parent index :type parent: :class:`QtCore.QModelIndex`: :returns: the column count :rtype: int :raises: None """ if parent.isValid(): return parent.internalPointer().column_count() else: return self._root.column_count()
[ "def", "columnCount", "(", "self", ",", "parent", ")", ":", "if", "parent", ".", "isValid", "(", ")", ":", "return", "parent", ".", "internalPointer", "(", ")", ".", "column_count", "(", ")", "else", ":", "return", "self", ".", "_root", ".", "column_count", "(", ")" ]
Return the number of columns for the children of the given parent. :param parent: the parent index :type parent: :class:`QtCore.QModelIndex`: :returns: the column count :rtype: int :raises: None
[ "Return", "the", "number", "of", "columns", "for", "the", "children", "of", "the", "given", "parent", "." ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/treemodel.py#L521-L533
239,553
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/treemodel.py
TreeModel.setData
def setData(self, index, value, role=QtCore.Qt.EditRole): """Set the data of the given index to value :param index: the index to set :type index: :class:`QtCore.QModelIndex` :param value: the value to set :param role: the role, usually edit role :type role: :data:`QtCore.Qt.ItemDataRole` :returns: True, if successfull, False if unsuccessfull :rtype: :class:`bool` :raises: None """ if not index.isValid(): return False item = index.internalPointer() r = item.set_data(index.column(), value, role) if r: self.dataChanged.emit(index, index) return r
python
def setData(self, index, value, role=QtCore.Qt.EditRole): """Set the data of the given index to value :param index: the index to set :type index: :class:`QtCore.QModelIndex` :param value: the value to set :param role: the role, usually edit role :type role: :data:`QtCore.Qt.ItemDataRole` :returns: True, if successfull, False if unsuccessfull :rtype: :class:`bool` :raises: None """ if not index.isValid(): return False item = index.internalPointer() r = item.set_data(index.column(), value, role) if r: self.dataChanged.emit(index, index) return r
[ "def", "setData", "(", "self", ",", "index", ",", "value", ",", "role", "=", "QtCore", ".", "Qt", ".", "EditRole", ")", ":", "if", "not", "index", ".", "isValid", "(", ")", ":", "return", "False", "item", "=", "index", ".", "internalPointer", "(", ")", "r", "=", "item", ".", "set_data", "(", "index", ".", "column", "(", ")", ",", "value", ",", "role", ")", "if", "r", ":", "self", ".", "dataChanged", ".", "emit", "(", "index", ",", "index", ")", "return", "r" ]
Set the data of the given index to value :param index: the index to set :type index: :class:`QtCore.QModelIndex` :param value: the value to set :param role: the role, usually edit role :type role: :data:`QtCore.Qt.ItemDataRole` :returns: True, if successfull, False if unsuccessfull :rtype: :class:`bool` :raises: None
[ "Set", "the", "data", "of", "the", "given", "index", "to", "value" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/treemodel.py#L550-L568
239,554
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/treemodel.py
TreeModel.headerData
def headerData(self, section, orientation, role): """Return the header data Will call :meth:`TreeItem.data` of the root :class:`TreeItem` with the given section (column) and role for horizontal orientations. Vertical orientations are numbered. :param section: the section in the header view :type section: int :param orientation: vertical or horizontal orientation :type orientation: :data:`QtCore.Qt.Vertical` | :data:`QtCore.Qt.Horizontal` :param role: the data role. :type role: :data:`QtCore.Qt.ItemDataRole` :returns: data for the header :raises: None """ if orientation == QtCore.Qt.Horizontal: d = self._root.data(section, role) if d is None and role == QtCore.Qt.DisplayRole: return str(section+1) return d if orientation == QtCore.Qt.Vertical and role == QtCore.Qt.DisplayRole: return str(section+1)
python
def headerData(self, section, orientation, role): """Return the header data Will call :meth:`TreeItem.data` of the root :class:`TreeItem` with the given section (column) and role for horizontal orientations. Vertical orientations are numbered. :param section: the section in the header view :type section: int :param orientation: vertical or horizontal orientation :type orientation: :data:`QtCore.Qt.Vertical` | :data:`QtCore.Qt.Horizontal` :param role: the data role. :type role: :data:`QtCore.Qt.ItemDataRole` :returns: data for the header :raises: None """ if orientation == QtCore.Qt.Horizontal: d = self._root.data(section, role) if d is None and role == QtCore.Qt.DisplayRole: return str(section+1) return d if orientation == QtCore.Qt.Vertical and role == QtCore.Qt.DisplayRole: return str(section+1)
[ "def", "headerData", "(", "self", ",", "section", ",", "orientation", ",", "role", ")", ":", "if", "orientation", "==", "QtCore", ".", "Qt", ".", "Horizontal", ":", "d", "=", "self", ".", "_root", ".", "data", "(", "section", ",", "role", ")", "if", "d", "is", "None", "and", "role", "==", "QtCore", ".", "Qt", ".", "DisplayRole", ":", "return", "str", "(", "section", "+", "1", ")", "return", "d", "if", "orientation", "==", "QtCore", ".", "Qt", ".", "Vertical", "and", "role", "==", "QtCore", ".", "Qt", ".", "DisplayRole", ":", "return", "str", "(", "section", "+", "1", ")" ]
Return the header data Will call :meth:`TreeItem.data` of the root :class:`TreeItem` with the given section (column) and role for horizontal orientations. Vertical orientations are numbered. :param section: the section in the header view :type section: int :param orientation: vertical or horizontal orientation :type orientation: :data:`QtCore.Qt.Vertical` | :data:`QtCore.Qt.Horizontal` :param role: the data role. :type role: :data:`QtCore.Qt.ItemDataRole` :returns: data for the header :raises: None
[ "Return", "the", "header", "data" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/treemodel.py#L570-L593
239,555
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/treemodel.py
TreeModel.insertRow
def insertRow(self, row, item, parent): """Insert a single item before the given row in the child items of the parent specified. :param row: the index where the rows get inserted :type row: int :param item: the item to insert. When creating the item, make sure it's parent is None. If not it will defeat the purpose of this function. :type item: :class:`TreeItem` :param parent: the parent :type parent: :class:`QtCore.QModelIndex` :returns: Returns true if the row is inserted; otherwise returns false. :rtype: bool :raises: None """ item.set_model(self) if parent.isValid(): parentitem = parent.internalPointer() else: parentitem = self._root self.beginInsertRows(parent, row, row) item._parent = parentitem if parentitem: parentitem.childItems.insert(row, item) self.endInsertRows() return True
python
def insertRow(self, row, item, parent): """Insert a single item before the given row in the child items of the parent specified. :param row: the index where the rows get inserted :type row: int :param item: the item to insert. When creating the item, make sure it's parent is None. If not it will defeat the purpose of this function. :type item: :class:`TreeItem` :param parent: the parent :type parent: :class:`QtCore.QModelIndex` :returns: Returns true if the row is inserted; otherwise returns false. :rtype: bool :raises: None """ item.set_model(self) if parent.isValid(): parentitem = parent.internalPointer() else: parentitem = self._root self.beginInsertRows(parent, row, row) item._parent = parentitem if parentitem: parentitem.childItems.insert(row, item) self.endInsertRows() return True
[ "def", "insertRow", "(", "self", ",", "row", ",", "item", ",", "parent", ")", ":", "item", ".", "set_model", "(", "self", ")", "if", "parent", ".", "isValid", "(", ")", ":", "parentitem", "=", "parent", ".", "internalPointer", "(", ")", "else", ":", "parentitem", "=", "self", ".", "_root", "self", ".", "beginInsertRows", "(", "parent", ",", "row", ",", "row", ")", "item", ".", "_parent", "=", "parentitem", "if", "parentitem", ":", "parentitem", ".", "childItems", ".", "insert", "(", "row", ",", "item", ")", "self", ".", "endInsertRows", "(", ")", "return", "True" ]
Insert a single item before the given row in the child items of the parent specified. :param row: the index where the rows get inserted :type row: int :param item: the item to insert. When creating the item, make sure it's parent is None. If not it will defeat the purpose of this function. :type item: :class:`TreeItem` :param parent: the parent :type parent: :class:`QtCore.QModelIndex` :returns: Returns true if the row is inserted; otherwise returns false. :rtype: bool :raises: None
[ "Insert", "a", "single", "item", "before", "the", "given", "row", "in", "the", "child", "items", "of", "the", "parent", "specified", "." ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/treemodel.py#L595-L619
239,556
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/treemodel.py
TreeModel.removeRow
def removeRow(self, row, parent): """Remove row from parent :param row: the row index :type row: int :param parent: the parent index :type parent: :class:`QtCore.QModelIndex` :returns: True if row is inserted; otherwise returns false. :rtype: bool :raises: None """ if parent.isValid(): parentitem = parent.internalPointer() else: parentitem = self._root self.beginRemoveRows(parent, row, row) item = parentitem.childItems[row] item.set_model(None) item._parent = None del parentitem.childItems[row] self.endRemoveRows() return True
python
def removeRow(self, row, parent): """Remove row from parent :param row: the row index :type row: int :param parent: the parent index :type parent: :class:`QtCore.QModelIndex` :returns: True if row is inserted; otherwise returns false. :rtype: bool :raises: None """ if parent.isValid(): parentitem = parent.internalPointer() else: parentitem = self._root self.beginRemoveRows(parent, row, row) item = parentitem.childItems[row] item.set_model(None) item._parent = None del parentitem.childItems[row] self.endRemoveRows() return True
[ "def", "removeRow", "(", "self", ",", "row", ",", "parent", ")", ":", "if", "parent", ".", "isValid", "(", ")", ":", "parentitem", "=", "parent", ".", "internalPointer", "(", ")", "else", ":", "parentitem", "=", "self", ".", "_root", "self", ".", "beginRemoveRows", "(", "parent", ",", "row", ",", "row", ")", "item", "=", "parentitem", ".", "childItems", "[", "row", "]", "item", ".", "set_model", "(", "None", ")", "item", ".", "_parent", "=", "None", "del", "parentitem", ".", "childItems", "[", "row", "]", "self", ".", "endRemoveRows", "(", ")", "return", "True" ]
Remove row from parent :param row: the row index :type row: int :param parent: the parent index :type parent: :class:`QtCore.QModelIndex` :returns: True if row is inserted; otherwise returns false. :rtype: bool :raises: None
[ "Remove", "row", "from", "parent" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/treemodel.py#L621-L642
239,557
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/treemodel.py
TreeModel.flags
def flags(self, index): """Return the flags for the given index This will call :meth:`TreeItem.flags` for valid ones. :param index: the index to query :type index: :class:`QtCore.QModelIndex` :returns: None :rtype: None :raises: None """ if index.isValid(): item = index.internalPointer() return item.flags(index) else: super(TreeModel, self).flags(index)
python
def flags(self, index): """Return the flags for the given index This will call :meth:`TreeItem.flags` for valid ones. :param index: the index to query :type index: :class:`QtCore.QModelIndex` :returns: None :rtype: None :raises: None """ if index.isValid(): item = index.internalPointer() return item.flags(index) else: super(TreeModel, self).flags(index)
[ "def", "flags", "(", "self", ",", "index", ")", ":", "if", "index", ".", "isValid", "(", ")", ":", "item", "=", "index", ".", "internalPointer", "(", ")", "return", "item", ".", "flags", "(", "index", ")", "else", ":", "super", "(", "TreeModel", ",", "self", ")", ".", "flags", "(", "index", ")" ]
Return the flags for the given index This will call :meth:`TreeItem.flags` for valid ones. :param index: the index to query :type index: :class:`QtCore.QModelIndex` :returns: None :rtype: None :raises: None
[ "Return", "the", "flags", "for", "the", "given", "index" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/treemodel.py#L654-L669
239,558
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/treemodel.py
TreeModel.index_of_item
def index_of_item(self, item): """Get the index for the given TreeItem :param item: the treeitem to query :type item: :class:`TreeItem` :returns: the index of the item :rtype: :class:`QtCore.QModelIndex` :raises: ValueError """ # root has an invalid index if item == self._root: return QtCore.QModelIndex() # find all parents to get their index parents = [item] i = item while True: parent = i.parent() # break if parent is root because we got all parents we need if parent == self._root: break if parent is None: # No new parent but last parent wasn't root! # This means that the item was not in the model! return QtCore.QModelIndex() # a new parent was found and we are still not at root # search further until we get to root i = parent parents.append(parent) # get the parent indexes until index = QtCore.QModelIndex() for treeitem in reversed(parents): parent = treeitem.parent() row = parent.childItems.index(treeitem) index = self.index(row, 0, index) return index
python
def index_of_item(self, item): """Get the index for the given TreeItem :param item: the treeitem to query :type item: :class:`TreeItem` :returns: the index of the item :rtype: :class:`QtCore.QModelIndex` :raises: ValueError """ # root has an invalid index if item == self._root: return QtCore.QModelIndex() # find all parents to get their index parents = [item] i = item while True: parent = i.parent() # break if parent is root because we got all parents we need if parent == self._root: break if parent is None: # No new parent but last parent wasn't root! # This means that the item was not in the model! return QtCore.QModelIndex() # a new parent was found and we are still not at root # search further until we get to root i = parent parents.append(parent) # get the parent indexes until index = QtCore.QModelIndex() for treeitem in reversed(parents): parent = treeitem.parent() row = parent.childItems.index(treeitem) index = self.index(row, 0, index) return index
[ "def", "index_of_item", "(", "self", ",", "item", ")", ":", "# root has an invalid index", "if", "item", "==", "self", ".", "_root", ":", "return", "QtCore", ".", "QModelIndex", "(", ")", "# find all parents to get their index", "parents", "=", "[", "item", "]", "i", "=", "item", "while", "True", ":", "parent", "=", "i", ".", "parent", "(", ")", "# break if parent is root because we got all parents we need", "if", "parent", "==", "self", ".", "_root", ":", "break", "if", "parent", "is", "None", ":", "# No new parent but last parent wasn't root!", "# This means that the item was not in the model!", "return", "QtCore", ".", "QModelIndex", "(", ")", "# a new parent was found and we are still not at root", "# search further until we get to root", "i", "=", "parent", "parents", ".", "append", "(", "parent", ")", "# get the parent indexes until", "index", "=", "QtCore", ".", "QModelIndex", "(", ")", "for", "treeitem", "in", "reversed", "(", "parents", ")", ":", "parent", "=", "treeitem", ".", "parent", "(", ")", "row", "=", "parent", ".", "childItems", ".", "index", "(", "treeitem", ")", "index", "=", "self", ".", "index", "(", "row", ",", "0", ",", "index", ")", "return", "index" ]
Get the index for the given TreeItem :param item: the treeitem to query :type item: :class:`TreeItem` :returns: the index of the item :rtype: :class:`QtCore.QModelIndex` :raises: ValueError
[ "Get", "the", "index", "for", "the", "given", "TreeItem" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/treemodel.py#L671-L706
239,559
miped/django-envy
envy.py
Environment.dict
def dict(self, var, default=NOTSET, cast=None, force=True): """Convenience method for casting to a dict Note: Casting """ return self._get(var, default=default, cast={str: cast}, force=force)
python
def dict(self, var, default=NOTSET, cast=None, force=True): """Convenience method for casting to a dict Note: Casting """ return self._get(var, default=default, cast={str: cast}, force=force)
[ "def", "dict", "(", "self", ",", "var", ",", "default", "=", "NOTSET", ",", "cast", "=", "None", ",", "force", "=", "True", ")", ":", "return", "self", ".", "_get", "(", "var", ",", "default", "=", "default", ",", "cast", "=", "{", "str", ":", "cast", "}", ",", "force", "=", "force", ")" ]
Convenience method for casting to a dict Note: Casting
[ "Convenience", "method", "for", "casting", "to", "a", "dict" ]
d7fe3c5dcad09e024c502e0f0e3a7c668ba15631
https://github.com/miped/django-envy/blob/d7fe3c5dcad09e024c502e0f0e3a7c668ba15631/envy.py#L156-L162
239,560
miped/django-envy
envy.py
Environment.decimal
def decimal(self, var, default=NOTSET, force=True): """Convenience method for casting to a decimal.Decimal Note: Casting """ return self._get(var, default=default, cast=Decimal, force=force)
python
def decimal(self, var, default=NOTSET, force=True): """Convenience method for casting to a decimal.Decimal Note: Casting """ return self._get(var, default=default, cast=Decimal, force=force)
[ "def", "decimal", "(", "self", ",", "var", ",", "default", "=", "NOTSET", ",", "force", "=", "True", ")", ":", "return", "self", ".", "_get", "(", "var", ",", "default", "=", "default", ",", "cast", "=", "Decimal", ",", "force", "=", "force", ")" ]
Convenience method for casting to a decimal.Decimal Note: Casting
[ "Convenience", "method", "for", "casting", "to", "a", "decimal", ".", "Decimal" ]
d7fe3c5dcad09e024c502e0f0e3a7c668ba15631
https://github.com/miped/django-envy/blob/d7fe3c5dcad09e024c502e0f0e3a7c668ba15631/envy.py#L166-L172
239,561
miped/django-envy
envy.py
Environment.json
def json(self, var, default=NOTSET, force=True): """Get environment variable, parsed as a json string""" return self._get(var, default=default, cast=json.loads, force=force)
python
def json(self, var, default=NOTSET, force=True): """Get environment variable, parsed as a json string""" return self._get(var, default=default, cast=json.loads, force=force)
[ "def", "json", "(", "self", ",", "var", ",", "default", "=", "NOTSET", ",", "force", "=", "True", ")", ":", "return", "self", ".", "_get", "(", "var", ",", "default", "=", "default", ",", "cast", "=", "json", ".", "loads", ",", "force", "=", "force", ")" ]
Get environment variable, parsed as a json string
[ "Get", "environment", "variable", "parsed", "as", "a", "json", "string" ]
d7fe3c5dcad09e024c502e0f0e3a7c668ba15631
https://github.com/miped/django-envy/blob/d7fe3c5dcad09e024c502e0f0e3a7c668ba15631/envy.py#L174-L176
239,562
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/filebrowser.py
FileBrowser.init_selection
def init_selection(self): """Call selection changed in the beginning, so signals get emitted once Emit shot_taskfile_sel_changed signal and asset_taskfile_sel_changed. :returns: None :raises: None """ si = self.shotverbrws.selected_indexes(0) if si: self.shot_ver_sel_changed(si[0]) else: self.shot_ver_sel_changed(QtCore.QModelIndex()) ai = self.assetverbrws.selected_indexes(0) if ai: self.asset_ver_sel_changed(ai[0]) else: self.asset_ver_sel_changed(QtCore.QModelIndex())
python
def init_selection(self): """Call selection changed in the beginning, so signals get emitted once Emit shot_taskfile_sel_changed signal and asset_taskfile_sel_changed. :returns: None :raises: None """ si = self.shotverbrws.selected_indexes(0) if si: self.shot_ver_sel_changed(si[0]) else: self.shot_ver_sel_changed(QtCore.QModelIndex()) ai = self.assetverbrws.selected_indexes(0) if ai: self.asset_ver_sel_changed(ai[0]) else: self.asset_ver_sel_changed(QtCore.QModelIndex())
[ "def", "init_selection", "(", "self", ")", ":", "si", "=", "self", ".", "shotverbrws", ".", "selected_indexes", "(", "0", ")", "if", "si", ":", "self", ".", "shot_ver_sel_changed", "(", "si", "[", "0", "]", ")", "else", ":", "self", ".", "shot_ver_sel_changed", "(", "QtCore", ".", "QModelIndex", "(", ")", ")", "ai", "=", "self", ".", "assetverbrws", ".", "selected_indexes", "(", "0", ")", "if", "ai", ":", "self", ".", "asset_ver_sel_changed", "(", "ai", "[", "0", "]", ")", "else", ":", "self", ".", "asset_ver_sel_changed", "(", "QtCore", ".", "QModelIndex", "(", ")", ")" ]
Call selection changed in the beginning, so signals get emitted once Emit shot_taskfile_sel_changed signal and asset_taskfile_sel_changed. :returns: None :raises: None
[ "Call", "selection", "changed", "in", "the", "beginning", "so", "signals", "get", "emitted", "once" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/filebrowser.py#L58-L75
239,563
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/filebrowser.py
FileBrowser.setup_releasetype_buttons
def setup_releasetype_buttons(self, ): """Create a radio button for every releasetype :returns: None :rtype: None :raises: None """ # we insert the radiobuttons instead of adding them # because there is already a spacer in the layout to # keep the buttons to the left. To maintain the original order # we insert them all to position 0 but in reversed order for rt in reversed(self._releasetypes): rb = QtGui.QRadioButton(rt) self.releasetype_hbox.insertWidget(0, rb) self._releasetype_button_mapping[rt] = rb # set first radiobutton checked if self._releasetypes: rt = self._releasetypes[0] rb = self._releasetype_button_mapping[rt] rb.setChecked(True) # if there is only one releasetype hide the buttons if len(self._releasetypes) == 1: self.releasetype_widget.setVisible(False)
python
def setup_releasetype_buttons(self, ): """Create a radio button for every releasetype :returns: None :rtype: None :raises: None """ # we insert the radiobuttons instead of adding them # because there is already a spacer in the layout to # keep the buttons to the left. To maintain the original order # we insert them all to position 0 but in reversed order for rt in reversed(self._releasetypes): rb = QtGui.QRadioButton(rt) self.releasetype_hbox.insertWidget(0, rb) self._releasetype_button_mapping[rt] = rb # set first radiobutton checked if self._releasetypes: rt = self._releasetypes[0] rb = self._releasetype_button_mapping[rt] rb.setChecked(True) # if there is only one releasetype hide the buttons if len(self._releasetypes) == 1: self.releasetype_widget.setVisible(False)
[ "def", "setup_releasetype_buttons", "(", "self", ",", ")", ":", "# we insert the radiobuttons instead of adding them", "# because there is already a spacer in the layout to", "# keep the buttons to the left. To maintain the original order", "# we insert them all to position 0 but in reversed order", "for", "rt", "in", "reversed", "(", "self", ".", "_releasetypes", ")", ":", "rb", "=", "QtGui", ".", "QRadioButton", "(", "rt", ")", "self", ".", "releasetype_hbox", ".", "insertWidget", "(", "0", ",", "rb", ")", "self", ".", "_releasetype_button_mapping", "[", "rt", "]", "=", "rb", "# set first radiobutton checked", "if", "self", ".", "_releasetypes", ":", "rt", "=", "self", ".", "_releasetypes", "[", "0", "]", "rb", "=", "self", ".", "_releasetype_button_mapping", "[", "rt", "]", "rb", ".", "setChecked", "(", "True", ")", "# if there is only one releasetype hide the buttons", "if", "len", "(", "self", ".", "_releasetypes", ")", "==", "1", ":", "self", ".", "releasetype_widget", ".", "setVisible", "(", "False", ")" ]
Create a radio button for every releasetype :returns: None :rtype: None :raises: None
[ "Create", "a", "radio", "button", "for", "every", "releasetype" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/filebrowser.py#L98-L120
239,564
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/filebrowser.py
FileBrowser.create_prj_browser
def create_prj_browser(self, ): """Create the project browser This creates a combobox brower for projects and adds it to the ui :returns: the created combo box browser :rtype: :class:`jukeboxcore.gui.widgets.browser.ComboBoxBrowser` :raises: None """ prjbrws = ComboBoxBrowser(1, headers=['Project:']) self.central_vbox.insertWidget(0, prjbrws) return prjbrws
python
def create_prj_browser(self, ): """Create the project browser This creates a combobox brower for projects and adds it to the ui :returns: the created combo box browser :rtype: :class:`jukeboxcore.gui.widgets.browser.ComboBoxBrowser` :raises: None """ prjbrws = ComboBoxBrowser(1, headers=['Project:']) self.central_vbox.insertWidget(0, prjbrws) return prjbrws
[ "def", "create_prj_browser", "(", "self", ",", ")", ":", "prjbrws", "=", "ComboBoxBrowser", "(", "1", ",", "headers", "=", "[", "'Project:'", "]", ")", "self", ".", "central_vbox", ".", "insertWidget", "(", "0", ",", "prjbrws", ")", "return", "prjbrws" ]
Create the project browser This creates a combobox brower for projects and adds it to the ui :returns: the created combo box browser :rtype: :class:`jukeboxcore.gui.widgets.browser.ComboBoxBrowser` :raises: None
[ "Create", "the", "project", "browser" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/filebrowser.py#L182-L194
239,565
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/filebrowser.py
FileBrowser.create_shot_browser
def create_shot_browser(self, ): """Create the shot browser This creates a list browser for shots and adds it to the ui :returns: the created borwser :rtype: :class:`jukeboxcore.gui.widgets.browser.ListBrowser` :raises: None """ shotbrws = ListBrowser(4, headers=['Sequence', 'Shot', 'Task', 'Descriptor']) self.shot_browser_vbox.insertWidget(0, shotbrws) return shotbrws
python
def create_shot_browser(self, ): """Create the shot browser This creates a list browser for shots and adds it to the ui :returns: the created borwser :rtype: :class:`jukeboxcore.gui.widgets.browser.ListBrowser` :raises: None """ shotbrws = ListBrowser(4, headers=['Sequence', 'Shot', 'Task', 'Descriptor']) self.shot_browser_vbox.insertWidget(0, shotbrws) return shotbrws
[ "def", "create_shot_browser", "(", "self", ",", ")", ":", "shotbrws", "=", "ListBrowser", "(", "4", ",", "headers", "=", "[", "'Sequence'", ",", "'Shot'", ",", "'Task'", ",", "'Descriptor'", "]", ")", "self", ".", "shot_browser_vbox", ".", "insertWidget", "(", "0", ",", "shotbrws", ")", "return", "shotbrws" ]
Create the shot browser This creates a list browser for shots and adds it to the ui :returns: the created borwser :rtype: :class:`jukeboxcore.gui.widgets.browser.ListBrowser` :raises: None
[ "Create", "the", "shot", "browser" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/filebrowser.py#L196-L208
239,566
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/filebrowser.py
FileBrowser.create_asset_browser
def create_asset_browser(self, ): """Create the asset browser This creates a list browser for assets and adds it to the ui :returns: the created borwser :rtype: :class:`jukeboxcore.gui.widgets.browser.ListBrowser` :raises: None """ assetbrws = ListBrowser(4, headers=['Assettype', 'Asset', 'Task', 'Descriptor']) self.asset_browser_vbox.insertWidget(0, assetbrws) return assetbrws
python
def create_asset_browser(self, ): """Create the asset browser This creates a list browser for assets and adds it to the ui :returns: the created borwser :rtype: :class:`jukeboxcore.gui.widgets.browser.ListBrowser` :raises: None """ assetbrws = ListBrowser(4, headers=['Assettype', 'Asset', 'Task', 'Descriptor']) self.asset_browser_vbox.insertWidget(0, assetbrws) return assetbrws
[ "def", "create_asset_browser", "(", "self", ",", ")", ":", "assetbrws", "=", "ListBrowser", "(", "4", ",", "headers", "=", "[", "'Assettype'", ",", "'Asset'", ",", "'Task'", ",", "'Descriptor'", "]", ")", "self", ".", "asset_browser_vbox", ".", "insertWidget", "(", "0", ",", "assetbrws", ")", "return", "assetbrws" ]
Create the asset browser This creates a list browser for assets and adds it to the ui :returns: the created borwser :rtype: :class:`jukeboxcore.gui.widgets.browser.ListBrowser` :raises: None
[ "Create", "the", "asset", "browser" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/filebrowser.py#L210-L222
239,567
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/filebrowser.py
FileBrowser.create_ver_browser
def create_ver_browser(self, layout): """Create a version browser and insert it into the given layout :param layout: the layout to insert the browser into :type layout: QLayout :returns: the created browser :rtype: :class:`jukeboxcore.gui.widgets.browser.ComboBoxBrowser` :raises: None """ brws = ComboBoxBrowser(1, headers=['Version:']) layout.insertWidget(1, brws) return brws
python
def create_ver_browser(self, layout): """Create a version browser and insert it into the given layout :param layout: the layout to insert the browser into :type layout: QLayout :returns: the created browser :rtype: :class:`jukeboxcore.gui.widgets.browser.ComboBoxBrowser` :raises: None """ brws = ComboBoxBrowser(1, headers=['Version:']) layout.insertWidget(1, brws) return brws
[ "def", "create_ver_browser", "(", "self", ",", "layout", ")", ":", "brws", "=", "ComboBoxBrowser", "(", "1", ",", "headers", "=", "[", "'Version:'", "]", ")", "layout", ".", "insertWidget", "(", "1", ",", "brws", ")", "return", "brws" ]
Create a version browser and insert it into the given layout :param layout: the layout to insert the browser into :type layout: QLayout :returns: the created browser :rtype: :class:`jukeboxcore.gui.widgets.browser.ComboBoxBrowser` :raises: None
[ "Create", "a", "version", "browser", "and", "insert", "it", "into", "the", "given", "layout" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/filebrowser.py#L224-L235
239,568
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/filebrowser.py
FileBrowser.create_comment_browser
def create_comment_browser(self, layout): """Create a comment browser and insert it into the given layout :param layout: the layout to insert the browser into :type layout: QLayout :returns: the created browser :rtype: :class:`jukeboxcore.gui.widgets.browser.ListBrowser` :raises: None """ brws = CommentBrowser(1, headers=['Comments:']) layout.insertWidget(1, brws) return brws
python
def create_comment_browser(self, layout): """Create a comment browser and insert it into the given layout :param layout: the layout to insert the browser into :type layout: QLayout :returns: the created browser :rtype: :class:`jukeboxcore.gui.widgets.browser.ListBrowser` :raises: None """ brws = CommentBrowser(1, headers=['Comments:']) layout.insertWidget(1, brws) return brws
[ "def", "create_comment_browser", "(", "self", ",", "layout", ")", ":", "brws", "=", "CommentBrowser", "(", "1", ",", "headers", "=", "[", "'Comments:'", "]", ")", "layout", ".", "insertWidget", "(", "1", ",", "brws", ")", "return", "brws" ]
Create a comment browser and insert it into the given layout :param layout: the layout to insert the browser into :type layout: QLayout :returns: the created browser :rtype: :class:`jukeboxcore.gui.widgets.browser.ListBrowser` :raises: None
[ "Create", "a", "comment", "browser", "and", "insert", "it", "into", "the", "given", "layout" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/filebrowser.py#L237-L248
239,569
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/filebrowser.py
FileBrowser.create_current_pb
def create_current_pb(self, ): """Create a push button and place it in the corner of the tabwidget :returns: the created button :rtype: :class:`QtGui.QPushButton` :raises: None """ pb = QtGui.QPushButton("Select current") self.selection_tabw.setCornerWidget(pb) return pb
python
def create_current_pb(self, ): """Create a push button and place it in the corner of the tabwidget :returns: the created button :rtype: :class:`QtGui.QPushButton` :raises: None """ pb = QtGui.QPushButton("Select current") self.selection_tabw.setCornerWidget(pb) return pb
[ "def", "create_current_pb", "(", "self", ",", ")", ":", "pb", "=", "QtGui", ".", "QPushButton", "(", "\"Select current\"", ")", "self", ".", "selection_tabw", ".", "setCornerWidget", "(", "pb", ")", "return", "pb" ]
Create a push button and place it in the corner of the tabwidget :returns: the created button :rtype: :class:`QtGui.QPushButton` :raises: None
[ "Create", "a", "push", "button", "and", "place", "it", "in", "the", "corner", "of", "the", "tabwidget" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/filebrowser.py#L250-L259
239,570
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/filebrowser.py
FileBrowser.create_prj_model
def create_prj_model(self, ): """Create and return a tree model that represents a list of projects :returns: the creeated model :rtype: :class:`jukeboxcore.gui.treemodel.TreeModel` :raises: None """ prjs = djadapter.projects.all() rootdata = treemodel.ListItemData(['Name', 'Short', 'Rootpath']) prjroot = treemodel.TreeItem(rootdata) for prj in prjs: prjdata = djitemdata.ProjectItemData(prj) treemodel.TreeItem(prjdata, prjroot) prjmodel = treemodel.TreeModel(prjroot) return prjmodel
python
def create_prj_model(self, ): """Create and return a tree model that represents a list of projects :returns: the creeated model :rtype: :class:`jukeboxcore.gui.treemodel.TreeModel` :raises: None """ prjs = djadapter.projects.all() rootdata = treemodel.ListItemData(['Name', 'Short', 'Rootpath']) prjroot = treemodel.TreeItem(rootdata) for prj in prjs: prjdata = djitemdata.ProjectItemData(prj) treemodel.TreeItem(prjdata, prjroot) prjmodel = treemodel.TreeModel(prjroot) return prjmodel
[ "def", "create_prj_model", "(", "self", ",", ")", ":", "prjs", "=", "djadapter", ".", "projects", ".", "all", "(", ")", "rootdata", "=", "treemodel", ".", "ListItemData", "(", "[", "'Name'", ",", "'Short'", ",", "'Rootpath'", "]", ")", "prjroot", "=", "treemodel", ".", "TreeItem", "(", "rootdata", ")", "for", "prj", "in", "prjs", ":", "prjdata", "=", "djitemdata", ".", "ProjectItemData", "(", "prj", ")", "treemodel", ".", "TreeItem", "(", "prjdata", ",", "prjroot", ")", "prjmodel", "=", "treemodel", ".", "TreeModel", "(", "prjroot", ")", "return", "prjmodel" ]
Create and return a tree model that represents a list of projects :returns: the creeated model :rtype: :class:`jukeboxcore.gui.treemodel.TreeModel` :raises: None
[ "Create", "and", "return", "a", "tree", "model", "that", "represents", "a", "list", "of", "projects" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/filebrowser.py#L261-L275
239,571
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/filebrowser.py
FileBrowser.create_shot_model
def create_shot_model(self, project, releasetype): """Create and return a new tree model that represents shots til descriptors The tree will include sequences, shots, tasks and descriptors of the given releaetype. :param releasetype: the releasetype for the model :type releasetype: :data:`djadapter.RELEASETYPES` :param project: the project of the shots :type project: :class:`djadapter.models.Project` :returns: the created tree model :rtype: :class:`jukeboxcore.gui.treemodel.TreeModel` :raises: None """ rootdata = treemodel.ListItemData(['Name']) rootitem = treemodel.TreeItem(rootdata) for seq in project.sequence_set.all(): seqdata = djitemdata.SequenceItemData(seq) seqitem = treemodel.TreeItem(seqdata, rootitem) for shot in seq.shot_set.all(): shotdata = djitemdata.ShotItemData(shot) shotitem = treemodel.TreeItem(shotdata, seqitem) for task in shot.tasks.all(): taskdata = djitemdata.TaskItemData(task) taskitem = treemodel.TreeItem(taskdata, shotitem) #get all mayafiles taskfiles = task.taskfile_set.filter(releasetype=releasetype, typ=self._filetype) # get all descriptor values as a list. disctinct eliminates duplicates. for d in taskfiles.order_by('descriptor').values_list('descriptor', flat=True).distinct(): ddata = treemodel.ListItemData([d,]) treemodel.TreeItem(ddata, taskitem) shotmodel = treemodel.TreeModel(rootitem) return shotmodel
python
def create_shot_model(self, project, releasetype): """Create and return a new tree model that represents shots til descriptors The tree will include sequences, shots, tasks and descriptors of the given releaetype. :param releasetype: the releasetype for the model :type releasetype: :data:`djadapter.RELEASETYPES` :param project: the project of the shots :type project: :class:`djadapter.models.Project` :returns: the created tree model :rtype: :class:`jukeboxcore.gui.treemodel.TreeModel` :raises: None """ rootdata = treemodel.ListItemData(['Name']) rootitem = treemodel.TreeItem(rootdata) for seq in project.sequence_set.all(): seqdata = djitemdata.SequenceItemData(seq) seqitem = treemodel.TreeItem(seqdata, rootitem) for shot in seq.shot_set.all(): shotdata = djitemdata.ShotItemData(shot) shotitem = treemodel.TreeItem(shotdata, seqitem) for task in shot.tasks.all(): taskdata = djitemdata.TaskItemData(task) taskitem = treemodel.TreeItem(taskdata, shotitem) #get all mayafiles taskfiles = task.taskfile_set.filter(releasetype=releasetype, typ=self._filetype) # get all descriptor values as a list. disctinct eliminates duplicates. for d in taskfiles.order_by('descriptor').values_list('descriptor', flat=True).distinct(): ddata = treemodel.ListItemData([d,]) treemodel.TreeItem(ddata, taskitem) shotmodel = treemodel.TreeModel(rootitem) return shotmodel
[ "def", "create_shot_model", "(", "self", ",", "project", ",", "releasetype", ")", ":", "rootdata", "=", "treemodel", ".", "ListItemData", "(", "[", "'Name'", "]", ")", "rootitem", "=", "treemodel", ".", "TreeItem", "(", "rootdata", ")", "for", "seq", "in", "project", ".", "sequence_set", ".", "all", "(", ")", ":", "seqdata", "=", "djitemdata", ".", "SequenceItemData", "(", "seq", ")", "seqitem", "=", "treemodel", ".", "TreeItem", "(", "seqdata", ",", "rootitem", ")", "for", "shot", "in", "seq", ".", "shot_set", ".", "all", "(", ")", ":", "shotdata", "=", "djitemdata", ".", "ShotItemData", "(", "shot", ")", "shotitem", "=", "treemodel", ".", "TreeItem", "(", "shotdata", ",", "seqitem", ")", "for", "task", "in", "shot", ".", "tasks", ".", "all", "(", ")", ":", "taskdata", "=", "djitemdata", ".", "TaskItemData", "(", "task", ")", "taskitem", "=", "treemodel", ".", "TreeItem", "(", "taskdata", ",", "shotitem", ")", "#get all mayafiles", "taskfiles", "=", "task", ".", "taskfile_set", ".", "filter", "(", "releasetype", "=", "releasetype", ",", "typ", "=", "self", ".", "_filetype", ")", "# get all descriptor values as a list. disctinct eliminates duplicates.", "for", "d", "in", "taskfiles", ".", "order_by", "(", "'descriptor'", ")", ".", "values_list", "(", "'descriptor'", ",", "flat", "=", "True", ")", ".", "distinct", "(", ")", ":", "ddata", "=", "treemodel", ".", "ListItemData", "(", "[", "d", ",", "]", ")", "treemodel", ".", "TreeItem", "(", "ddata", ",", "taskitem", ")", "shotmodel", "=", "treemodel", ".", "TreeModel", "(", "rootitem", ")", "return", "shotmodel" ]
Create and return a new tree model that represents shots til descriptors The tree will include sequences, shots, tasks and descriptors of the given releaetype. :param releasetype: the releasetype for the model :type releasetype: :data:`djadapter.RELEASETYPES` :param project: the project of the shots :type project: :class:`djadapter.models.Project` :returns: the created tree model :rtype: :class:`jukeboxcore.gui.treemodel.TreeModel` :raises: None
[ "Create", "and", "return", "a", "new", "tree", "model", "that", "represents", "shots", "til", "descriptors" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/filebrowser.py#L277-L308
239,572
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/filebrowser.py
FileBrowser.create_asset_model
def create_asset_model(self, project, releasetype): """Create and return a new tree model that represents assets til descriptors The tree will include assettypes, assets, tasks and descriptors of the given releaetype. :param releasetype: the releasetype for the model :type releasetype: :data:`djadapter.RELEASETYPES` :param project: the project of the assets :type project: :class:`djadapter.models.Project` :returns: the created tree model :rtype: :class:`jukeboxcore.gui.treemodel.TreeModel` :raises: None """ rootdata = treemodel.ListItemData(['Name']) rootitem = treemodel.TreeItem(rootdata) for atype in project.atype_set.all(): atypedata = djitemdata.AtypeItemData(atype) atypeitem = treemodel.TreeItem(atypedata, rootitem) for asset in atype.asset_set.filter(project=project): assetdata = djitemdata.AssetItemData(asset) assetitem = treemodel.TreeItem(assetdata, atypeitem) for task in asset.tasks.all(): taskdata = djitemdata.TaskItemData(task) taskitem = treemodel.TreeItem(taskdata, assetitem) taskfiles = task.taskfile_set.filter(releasetype=releasetype, typ=self._filetype) # get all descriptor values as a list. disctinct eliminates duplicates. for d in taskfiles.order_by('descriptor').values_list('descriptor', flat=True).distinct(): ddata = treemodel.ListItemData([d,]) treemodel.TreeItem(ddata, taskitem) assetmodel = treemodel.TreeModel(rootitem) return assetmodel
python
def create_asset_model(self, project, releasetype): """Create and return a new tree model that represents assets til descriptors The tree will include assettypes, assets, tasks and descriptors of the given releaetype. :param releasetype: the releasetype for the model :type releasetype: :data:`djadapter.RELEASETYPES` :param project: the project of the assets :type project: :class:`djadapter.models.Project` :returns: the created tree model :rtype: :class:`jukeboxcore.gui.treemodel.TreeModel` :raises: None """ rootdata = treemodel.ListItemData(['Name']) rootitem = treemodel.TreeItem(rootdata) for atype in project.atype_set.all(): atypedata = djitemdata.AtypeItemData(atype) atypeitem = treemodel.TreeItem(atypedata, rootitem) for asset in atype.asset_set.filter(project=project): assetdata = djitemdata.AssetItemData(asset) assetitem = treemodel.TreeItem(assetdata, atypeitem) for task in asset.tasks.all(): taskdata = djitemdata.TaskItemData(task) taskitem = treemodel.TreeItem(taskdata, assetitem) taskfiles = task.taskfile_set.filter(releasetype=releasetype, typ=self._filetype) # get all descriptor values as a list. disctinct eliminates duplicates. for d in taskfiles.order_by('descriptor').values_list('descriptor', flat=True).distinct(): ddata = treemodel.ListItemData([d,]) treemodel.TreeItem(ddata, taskitem) assetmodel = treemodel.TreeModel(rootitem) return assetmodel
[ "def", "create_asset_model", "(", "self", ",", "project", ",", "releasetype", ")", ":", "rootdata", "=", "treemodel", ".", "ListItemData", "(", "[", "'Name'", "]", ")", "rootitem", "=", "treemodel", ".", "TreeItem", "(", "rootdata", ")", "for", "atype", "in", "project", ".", "atype_set", ".", "all", "(", ")", ":", "atypedata", "=", "djitemdata", ".", "AtypeItemData", "(", "atype", ")", "atypeitem", "=", "treemodel", ".", "TreeItem", "(", "atypedata", ",", "rootitem", ")", "for", "asset", "in", "atype", ".", "asset_set", ".", "filter", "(", "project", "=", "project", ")", ":", "assetdata", "=", "djitemdata", ".", "AssetItemData", "(", "asset", ")", "assetitem", "=", "treemodel", ".", "TreeItem", "(", "assetdata", ",", "atypeitem", ")", "for", "task", "in", "asset", ".", "tasks", ".", "all", "(", ")", ":", "taskdata", "=", "djitemdata", ".", "TaskItemData", "(", "task", ")", "taskitem", "=", "treemodel", ".", "TreeItem", "(", "taskdata", ",", "assetitem", ")", "taskfiles", "=", "task", ".", "taskfile_set", ".", "filter", "(", "releasetype", "=", "releasetype", ",", "typ", "=", "self", ".", "_filetype", ")", "# get all descriptor values as a list. disctinct eliminates duplicates.", "for", "d", "in", "taskfiles", ".", "order_by", "(", "'descriptor'", ")", ".", "values_list", "(", "'descriptor'", ",", "flat", "=", "True", ")", ".", "distinct", "(", ")", ":", "ddata", "=", "treemodel", ".", "ListItemData", "(", "[", "d", ",", "]", ")", "treemodel", ".", "TreeItem", "(", "ddata", ",", "taskitem", ")", "assetmodel", "=", "treemodel", ".", "TreeModel", "(", "rootitem", ")", "return", "assetmodel" ]
Create and return a new tree model that represents assets til descriptors The tree will include assettypes, assets, tasks and descriptors of the given releaetype. :param releasetype: the releasetype for the model :type releasetype: :data:`djadapter.RELEASETYPES` :param project: the project of the assets :type project: :class:`djadapter.models.Project` :returns: the created tree model :rtype: :class:`jukeboxcore.gui.treemodel.TreeModel` :raises: None
[ "Create", "and", "return", "a", "new", "tree", "model", "that", "represents", "assets", "til", "descriptors" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/filebrowser.py#L310-L340
239,573
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/filebrowser.py
FileBrowser.create_version_model
def create_version_model(self, task, releasetype, descriptor): """Create and return a new model that represents taskfiles for the given task, releasetpye and descriptor :param task: the task of the taskfiles :type task: :class:`djadapter.models.Task` :param releasetype: the releasetype :type releasetype: str :param descriptor: the descirptor :type descriptor: str|None :returns: the created tree model :rtype: :class:`jukeboxcore.gui.treemodel.TreeModel` :raises: None """ rootdata = treemodel.ListItemData(['Version', 'Releasetype', 'Path']) rootitem = treemodel.TreeItem(rootdata) for tf in task.taskfile_set.filter(releasetype=releasetype, descriptor=descriptor).order_by('-version'): tfdata = djitemdata.TaskFileItemData(tf) tfitem = treemodel.TreeItem(tfdata, rootitem) for note in tf.notes.all(): notedata = djitemdata.NoteItemData(note) treemodel.TreeItem(notedata, tfitem) versionmodel = treemodel.TreeModel(rootitem) return versionmodel
python
def create_version_model(self, task, releasetype, descriptor): """Create and return a new model that represents taskfiles for the given task, releasetpye and descriptor :param task: the task of the taskfiles :type task: :class:`djadapter.models.Task` :param releasetype: the releasetype :type releasetype: str :param descriptor: the descirptor :type descriptor: str|None :returns: the created tree model :rtype: :class:`jukeboxcore.gui.treemodel.TreeModel` :raises: None """ rootdata = treemodel.ListItemData(['Version', 'Releasetype', 'Path']) rootitem = treemodel.TreeItem(rootdata) for tf in task.taskfile_set.filter(releasetype=releasetype, descriptor=descriptor).order_by('-version'): tfdata = djitemdata.TaskFileItemData(tf) tfitem = treemodel.TreeItem(tfdata, rootitem) for note in tf.notes.all(): notedata = djitemdata.NoteItemData(note) treemodel.TreeItem(notedata, tfitem) versionmodel = treemodel.TreeModel(rootitem) return versionmodel
[ "def", "create_version_model", "(", "self", ",", "task", ",", "releasetype", ",", "descriptor", ")", ":", "rootdata", "=", "treemodel", ".", "ListItemData", "(", "[", "'Version'", ",", "'Releasetype'", ",", "'Path'", "]", ")", "rootitem", "=", "treemodel", ".", "TreeItem", "(", "rootdata", ")", "for", "tf", "in", "task", ".", "taskfile_set", ".", "filter", "(", "releasetype", "=", "releasetype", ",", "descriptor", "=", "descriptor", ")", ".", "order_by", "(", "'-version'", ")", ":", "tfdata", "=", "djitemdata", ".", "TaskFileItemData", "(", "tf", ")", "tfitem", "=", "treemodel", ".", "TreeItem", "(", "tfdata", ",", "rootitem", ")", "for", "note", "in", "tf", ".", "notes", ".", "all", "(", ")", ":", "notedata", "=", "djitemdata", ".", "NoteItemData", "(", "note", ")", "treemodel", ".", "TreeItem", "(", "notedata", ",", "tfitem", ")", "versionmodel", "=", "treemodel", ".", "TreeModel", "(", "rootitem", ")", "return", "versionmodel" ]
Create and return a new model that represents taskfiles for the given task, releasetpye and descriptor :param task: the task of the taskfiles :type task: :class:`djadapter.models.Task` :param releasetype: the releasetype :type releasetype: str :param descriptor: the descirptor :type descriptor: str|None :returns: the created tree model :rtype: :class:`jukeboxcore.gui.treemodel.TreeModel` :raises: None
[ "Create", "and", "return", "a", "new", "model", "that", "represents", "taskfiles", "for", "the", "given", "task", "releasetpye", "and", "descriptor" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/filebrowser.py#L342-L364
239,574
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/filebrowser.py
FileBrowser.update_shot_browser
def update_shot_browser(self, project, releasetype): """Update the shot browser to the given project :param releasetype: the releasetype for the model :type releasetype: :data:`djadapter.RELEASETYPES` :param project: the project of the shots :type project: :class:`djadapter.models.Project` :returns: None :rtype: None :raises: None """ if project is None: self.shotbrws.set_model(None) return shotmodel = self.create_shot_model(project, releasetype) self.shotbrws.set_model(shotmodel)
python
def update_shot_browser(self, project, releasetype): """Update the shot browser to the given project :param releasetype: the releasetype for the model :type releasetype: :data:`djadapter.RELEASETYPES` :param project: the project of the shots :type project: :class:`djadapter.models.Project` :returns: None :rtype: None :raises: None """ if project is None: self.shotbrws.set_model(None) return shotmodel = self.create_shot_model(project, releasetype) self.shotbrws.set_model(shotmodel)
[ "def", "update_shot_browser", "(", "self", ",", "project", ",", "releasetype", ")", ":", "if", "project", "is", "None", ":", "self", ".", "shotbrws", ".", "set_model", "(", "None", ")", "return", "shotmodel", "=", "self", ".", "create_shot_model", "(", "project", ",", "releasetype", ")", "self", ".", "shotbrws", ".", "set_model", "(", "shotmodel", ")" ]
Update the shot browser to the given project :param releasetype: the releasetype for the model :type releasetype: :data:`djadapter.RELEASETYPES` :param project: the project of the shots :type project: :class:`djadapter.models.Project` :returns: None :rtype: None :raises: None
[ "Update", "the", "shot", "browser", "to", "the", "given", "project" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/filebrowser.py#L380-L395
239,575
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/filebrowser.py
FileBrowser.update_asset_browser
def update_asset_browser(self, project, releasetype): """update the assetbrowser to the given project :param releasetype: the releasetype for the model :type releasetype: :data:`djadapter.RELEASETYPES` :param project: the project of the assets :type project: :class:`djadapter.models.Project` :returns: None :rtype: None :raises: None """ if project is None: self.assetbrws.set_model(None) return assetmodel = self.create_asset_model(project, releasetype) self.assetbrws.set_model(assetmodel)
python
def update_asset_browser(self, project, releasetype): """update the assetbrowser to the given project :param releasetype: the releasetype for the model :type releasetype: :data:`djadapter.RELEASETYPES` :param project: the project of the assets :type project: :class:`djadapter.models.Project` :returns: None :rtype: None :raises: None """ if project is None: self.assetbrws.set_model(None) return assetmodel = self.create_asset_model(project, releasetype) self.assetbrws.set_model(assetmodel)
[ "def", "update_asset_browser", "(", "self", ",", "project", ",", "releasetype", ")", ":", "if", "project", "is", "None", ":", "self", ".", "assetbrws", ".", "set_model", "(", "None", ")", "return", "assetmodel", "=", "self", ".", "create_asset_model", "(", "project", ",", "releasetype", ")", "self", ".", "assetbrws", ".", "set_model", "(", "assetmodel", ")" ]
update the assetbrowser to the given project :param releasetype: the releasetype for the model :type releasetype: :data:`djadapter.RELEASETYPES` :param project: the project of the assets :type project: :class:`djadapter.models.Project` :returns: None :rtype: None :raises: None
[ "update", "the", "assetbrowser", "to", "the", "given", "project" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/filebrowser.py#L397-L412
239,576
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/filebrowser.py
FileBrowser.update_browsers
def update_browsers(self, *args, **kwargs): """Update the shot and the assetbrowsers :returns: None :rtype: None :raises: None """ sel = self.prjbrws.selected_indexes(0) if not sel: return prjindex = sel[0] if not prjindex.isValid(): prj = None else: prjitem = prjindex.internalPointer() prj = prjitem.internal_data() self.set_project_banner(prj) releasetype = self.get_releasetype() self.update_shot_browser(prj, releasetype) self.update_asset_browser(prj, releasetype)
python
def update_browsers(self, *args, **kwargs): """Update the shot and the assetbrowsers :returns: None :rtype: None :raises: None """ sel = self.prjbrws.selected_indexes(0) if not sel: return prjindex = sel[0] if not prjindex.isValid(): prj = None else: prjitem = prjindex.internalPointer() prj = prjitem.internal_data() self.set_project_banner(prj) releasetype = self.get_releasetype() self.update_shot_browser(prj, releasetype) self.update_asset_browser(prj, releasetype)
[ "def", "update_browsers", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "sel", "=", "self", ".", "prjbrws", ".", "selected_indexes", "(", "0", ")", "if", "not", "sel", ":", "return", "prjindex", "=", "sel", "[", "0", "]", "if", "not", "prjindex", ".", "isValid", "(", ")", ":", "prj", "=", "None", "else", ":", "prjitem", "=", "prjindex", ".", "internalPointer", "(", ")", "prj", "=", "prjitem", ".", "internal_data", "(", ")", "self", ".", "set_project_banner", "(", "prj", ")", "releasetype", "=", "self", ".", "get_releasetype", "(", ")", "self", ".", "update_shot_browser", "(", "prj", ",", "releasetype", ")", "self", ".", "update_asset_browser", "(", "prj", ",", "releasetype", ")" ]
Update the shot and the assetbrowsers :returns: None :rtype: None :raises: None
[ "Update", "the", "shot", "and", "the", "assetbrowsers" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/filebrowser.py#L414-L433
239,577
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/filebrowser.py
FileBrowser.update_version_descriptor
def update_version_descriptor(self, task, releasetype, descriptor, verbrowser, commentbrowser): """Update the versions in the given browser :param task: the task of the taskfiles :type task: :class:`djadapter.models.Task` | None :param releasetype: the releasetype :type releasetype: str|None :param descriptor: the descirptor :type descriptor: str|None :param verbrowser: the browser to update (the version browser) :type verbrowser: :class:`jukeboxcore.gui.widgets.browser.AbstractTreeBrowser` :param commentbrowser: the comment browser to update :type commentbrowser: :class:`jukeboxcore.gui.widgets.browser.AbstractTreeBrowser` :returns: None :rtype: None :raises: None """ if task is None: null = treemodel.TreeItem(None) verbrowser.set_model(treemodel.TreeModel(null)) return m = self.create_version_model(task, releasetype, descriptor) verbrowser.set_model(m) commentbrowser.set_model(m)
python
def update_version_descriptor(self, task, releasetype, descriptor, verbrowser, commentbrowser): """Update the versions in the given browser :param task: the task of the taskfiles :type task: :class:`djadapter.models.Task` | None :param releasetype: the releasetype :type releasetype: str|None :param descriptor: the descirptor :type descriptor: str|None :param verbrowser: the browser to update (the version browser) :type verbrowser: :class:`jukeboxcore.gui.widgets.browser.AbstractTreeBrowser` :param commentbrowser: the comment browser to update :type commentbrowser: :class:`jukeboxcore.gui.widgets.browser.AbstractTreeBrowser` :returns: None :rtype: None :raises: None """ if task is None: null = treemodel.TreeItem(None) verbrowser.set_model(treemodel.TreeModel(null)) return m = self.create_version_model(task, releasetype, descriptor) verbrowser.set_model(m) commentbrowser.set_model(m)
[ "def", "update_version_descriptor", "(", "self", ",", "task", ",", "releasetype", ",", "descriptor", ",", "verbrowser", ",", "commentbrowser", ")", ":", "if", "task", "is", "None", ":", "null", "=", "treemodel", ".", "TreeItem", "(", "None", ")", "verbrowser", ".", "set_model", "(", "treemodel", ".", "TreeModel", "(", "null", ")", ")", "return", "m", "=", "self", ".", "create_version_model", "(", "task", ",", "releasetype", ",", "descriptor", ")", "verbrowser", ".", "set_model", "(", "m", ")", "commentbrowser", ".", "set_model", "(", "m", ")" ]
Update the versions in the given browser :param task: the task of the taskfiles :type task: :class:`djadapter.models.Task` | None :param releasetype: the releasetype :type releasetype: str|None :param descriptor: the descirptor :type descriptor: str|None :param verbrowser: the browser to update (the version browser) :type verbrowser: :class:`jukeboxcore.gui.widgets.browser.AbstractTreeBrowser` :param commentbrowser: the comment browser to update :type commentbrowser: :class:`jukeboxcore.gui.widgets.browser.AbstractTreeBrowser` :returns: None :rtype: None :raises: None
[ "Update", "the", "versions", "in", "the", "given", "browser" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/filebrowser.py#L435-L459
239,578
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/filebrowser.py
FileBrowser.selection_changed
def selection_changed(self, index, source, update, commentbrowser, mapper): """Callback for when the asset or shot browser changed its selection :param index: the modelindex with the descriptor tree item as internal data :type index: QtCore.QModelIndex :param source: the shot or asset browser to that changed its selection :type source: :class:`jukeboxcore.gui.widgets.browser.AbstractTreeBrowser` :param update: the browser to update :type update: :class:`jukeboxcore.gui.widgets.browser.AbstractTreeBrowser` :param browser: the comment browser to update :type browser: :class:`jukeboxcore.gui.widgets.browser.AbstractTreeBrowser` :param mapper: the data widget mapper to update :type mapper: :class:`QtGui.QDataWidgetMapper` :returns: None :rtype: None :raises: None """ if not index.isValid(): # no descriptor selected self.update_version_descriptor(None, None, None, update, commentbrowser) self.set_info_mapper_model(mapper, None) return descitem = index.internalPointer() descriptor = descitem.internal_data()[0] taskdata = source.selected_indexes(2)[0].internalPointer() task = taskdata.internal_data() releasetype = self.get_releasetype() self.update_version_descriptor(task, releasetype, descriptor, update, commentbrowser) self.set_info_mapper_model(mapper, update.model) sel = update.selected_indexes(0) if sel: self.set_mapper_index(sel[0], mapper)
python
def selection_changed(self, index, source, update, commentbrowser, mapper): """Callback for when the asset or shot browser changed its selection :param index: the modelindex with the descriptor tree item as internal data :type index: QtCore.QModelIndex :param source: the shot or asset browser to that changed its selection :type source: :class:`jukeboxcore.gui.widgets.browser.AbstractTreeBrowser` :param update: the browser to update :type update: :class:`jukeboxcore.gui.widgets.browser.AbstractTreeBrowser` :param browser: the comment browser to update :type browser: :class:`jukeboxcore.gui.widgets.browser.AbstractTreeBrowser` :param mapper: the data widget mapper to update :type mapper: :class:`QtGui.QDataWidgetMapper` :returns: None :rtype: None :raises: None """ if not index.isValid(): # no descriptor selected self.update_version_descriptor(None, None, None, update, commentbrowser) self.set_info_mapper_model(mapper, None) return descitem = index.internalPointer() descriptor = descitem.internal_data()[0] taskdata = source.selected_indexes(2)[0].internalPointer() task = taskdata.internal_data() releasetype = self.get_releasetype() self.update_version_descriptor(task, releasetype, descriptor, update, commentbrowser) self.set_info_mapper_model(mapper, update.model) sel = update.selected_indexes(0) if sel: self.set_mapper_index(sel[0], mapper)
[ "def", "selection_changed", "(", "self", ",", "index", ",", "source", ",", "update", ",", "commentbrowser", ",", "mapper", ")", ":", "if", "not", "index", ".", "isValid", "(", ")", ":", "# no descriptor selected", "self", ".", "update_version_descriptor", "(", "None", ",", "None", ",", "None", ",", "update", ",", "commentbrowser", ")", "self", ".", "set_info_mapper_model", "(", "mapper", ",", "None", ")", "return", "descitem", "=", "index", ".", "internalPointer", "(", ")", "descriptor", "=", "descitem", ".", "internal_data", "(", ")", "[", "0", "]", "taskdata", "=", "source", ".", "selected_indexes", "(", "2", ")", "[", "0", "]", ".", "internalPointer", "(", ")", "task", "=", "taskdata", ".", "internal_data", "(", ")", "releasetype", "=", "self", ".", "get_releasetype", "(", ")", "self", ".", "update_version_descriptor", "(", "task", ",", "releasetype", ",", "descriptor", ",", "update", ",", "commentbrowser", ")", "self", ".", "set_info_mapper_model", "(", "mapper", ",", "update", ".", "model", ")", "sel", "=", "update", ".", "selected_indexes", "(", "0", ")", "if", "sel", ":", "self", ".", "set_mapper_index", "(", "sel", "[", "0", "]", ",", "mapper", ")" ]
Callback for when the asset or shot browser changed its selection :param index: the modelindex with the descriptor tree item as internal data :type index: QtCore.QModelIndex :param source: the shot or asset browser to that changed its selection :type source: :class:`jukeboxcore.gui.widgets.browser.AbstractTreeBrowser` :param update: the browser to update :type update: :class:`jukeboxcore.gui.widgets.browser.AbstractTreeBrowser` :param browser: the comment browser to update :type browser: :class:`jukeboxcore.gui.widgets.browser.AbstractTreeBrowser` :param mapper: the data widget mapper to update :type mapper: :class:`QtGui.QDataWidgetMapper` :returns: None :rtype: None :raises: None
[ "Callback", "for", "when", "the", "asset", "or", "shot", "browser", "changed", "its", "selection" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/filebrowser.py#L461-L493
239,579
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/filebrowser.py
FileBrowser.set_info_mapper_model
def set_info_mapper_model(self, mapper, model): """Set the model for the info mapper :param mapper: the mapper to update :type mapper: QtGui.QDataWidgetMapper :param model: The model to set :type model: QtGui.QAbstractItemModel | None :returns: None :rtype: None :raises: None """ # nothing changed. we can return. # I noticed that when you set the model the very first time to None # it printed a message: # QObject::connect: Cannot connect (null)::dataChanged(QModelIndex,QModelIndex) to # QDataWidgetMapper::_q_dataChanged(QModelIndex,QModelIndex) # QObject::connect: Cannot connect (null)::destroyed() to # QDataWidgetMapper::_q_modelDestroyed() # I don't know exactly why. But these two lines get rid of the message and outcome is the same if not mapper.model() and not model: return mapper.setModel(model) if mapper is self.asset_info_mapper: if model is None: self.asset_path_le.setText("") self.asset_created_by_le.setText("") self.asset_created_dte.findChild(QtGui.QLineEdit).setText('') self.asset_updated_dte.findChild(QtGui.QLineEdit).setText('') else: mapper.addMapping(self.asset_path_le, 2) mapper.addMapping(self.asset_created_by_le, 3) mapper.addMapping(self.asset_created_dte, 4) mapper.addMapping(self.asset_updated_dte, 5) else: if model is None: self.shot_path_le.setText("") self.shot_created_by_le.setText("") self.shot_created_dte.findChild(QtGui.QLineEdit).setText('') self.shot_updated_dte.findChild(QtGui.QLineEdit).setText('') else: mapper.addMapping(self.shot_path_le, 2) mapper.addMapping(self.shot_created_by_le, 3) mapper.addMapping(self.shot_created_dte, 4) mapper.addMapping(self.shot_updated_dte, 5)
python
def set_info_mapper_model(self, mapper, model): """Set the model for the info mapper :param mapper: the mapper to update :type mapper: QtGui.QDataWidgetMapper :param model: The model to set :type model: QtGui.QAbstractItemModel | None :returns: None :rtype: None :raises: None """ # nothing changed. we can return. # I noticed that when you set the model the very first time to None # it printed a message: # QObject::connect: Cannot connect (null)::dataChanged(QModelIndex,QModelIndex) to # QDataWidgetMapper::_q_dataChanged(QModelIndex,QModelIndex) # QObject::connect: Cannot connect (null)::destroyed() to # QDataWidgetMapper::_q_modelDestroyed() # I don't know exactly why. But these two lines get rid of the message and outcome is the same if not mapper.model() and not model: return mapper.setModel(model) if mapper is self.asset_info_mapper: if model is None: self.asset_path_le.setText("") self.asset_created_by_le.setText("") self.asset_created_dte.findChild(QtGui.QLineEdit).setText('') self.asset_updated_dte.findChild(QtGui.QLineEdit).setText('') else: mapper.addMapping(self.asset_path_le, 2) mapper.addMapping(self.asset_created_by_le, 3) mapper.addMapping(self.asset_created_dte, 4) mapper.addMapping(self.asset_updated_dte, 5) else: if model is None: self.shot_path_le.setText("") self.shot_created_by_le.setText("") self.shot_created_dte.findChild(QtGui.QLineEdit).setText('') self.shot_updated_dte.findChild(QtGui.QLineEdit).setText('') else: mapper.addMapping(self.shot_path_le, 2) mapper.addMapping(self.shot_created_by_le, 3) mapper.addMapping(self.shot_created_dte, 4) mapper.addMapping(self.shot_updated_dte, 5)
[ "def", "set_info_mapper_model", "(", "self", ",", "mapper", ",", "model", ")", ":", "# nothing changed. we can return.", "# I noticed that when you set the model the very first time to None", "# it printed a message:", "# QObject::connect: Cannot connect (null)::dataChanged(QModelIndex,QModelIndex) to", "# QDataWidgetMapper::_q_dataChanged(QModelIndex,QModelIndex)", "# QObject::connect: Cannot connect (null)::destroyed() to", "# QDataWidgetMapper::_q_modelDestroyed()", "# I don't know exactly why. But these two lines get rid of the message and outcome is the same", "if", "not", "mapper", ".", "model", "(", ")", "and", "not", "model", ":", "return", "mapper", ".", "setModel", "(", "model", ")", "if", "mapper", "is", "self", ".", "asset_info_mapper", ":", "if", "model", "is", "None", ":", "self", ".", "asset_path_le", ".", "setText", "(", "\"\"", ")", "self", ".", "asset_created_by_le", ".", "setText", "(", "\"\"", ")", "self", ".", "asset_created_dte", ".", "findChild", "(", "QtGui", ".", "QLineEdit", ")", ".", "setText", "(", "''", ")", "self", ".", "asset_updated_dte", ".", "findChild", "(", "QtGui", ".", "QLineEdit", ")", ".", "setText", "(", "''", ")", "else", ":", "mapper", ".", "addMapping", "(", "self", ".", "asset_path_le", ",", "2", ")", "mapper", ".", "addMapping", "(", "self", ".", "asset_created_by_le", ",", "3", ")", "mapper", ".", "addMapping", "(", "self", ".", "asset_created_dte", ",", "4", ")", "mapper", ".", "addMapping", "(", "self", ".", "asset_updated_dte", ",", "5", ")", "else", ":", "if", "model", "is", "None", ":", "self", ".", "shot_path_le", ".", "setText", "(", "\"\"", ")", "self", ".", "shot_created_by_le", ".", "setText", "(", "\"\"", ")", "self", ".", "shot_created_dte", ".", "findChild", "(", "QtGui", ".", "QLineEdit", ")", ".", "setText", "(", "''", ")", "self", ".", "shot_updated_dte", ".", "findChild", "(", "QtGui", ".", "QLineEdit", ")", ".", "setText", "(", "''", ")", "else", ":", "mapper", ".", "addMapping", "(", "self", ".", "shot_path_le", ",", "2", ")", "mapper", ".", "addMapping", "(", "self", ".", "shot_created_by_le", ",", "3", ")", "mapper", ".", "addMapping", "(", "self", ".", "shot_created_dte", ",", "4", ")", "mapper", ".", "addMapping", "(", "self", ".", "shot_updated_dte", ",", "5", ")" ]
Set the model for the info mapper :param mapper: the mapper to update :type mapper: QtGui.QDataWidgetMapper :param model: The model to set :type model: QtGui.QAbstractItemModel | None :returns: None :rtype: None :raises: None
[ "Set", "the", "model", "for", "the", "info", "mapper" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/filebrowser.py#L495-L539
239,580
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/filebrowser.py
FileBrowser.set_mapper_index
def set_mapper_index(self, index, mapper): """Set the mapper to the given index :param index: the index to set :type index: QtCore.QModelIndex :param mapper: the mapper to set :type mapper: QtGui.QDataWidgetMapper :returns: None :rtype: None :raises: None """ parent = index.parent() mapper.setRootIndex(parent) mapper.setCurrentModelIndex(index)
python
def set_mapper_index(self, index, mapper): """Set the mapper to the given index :param index: the index to set :type index: QtCore.QModelIndex :param mapper: the mapper to set :type mapper: QtGui.QDataWidgetMapper :returns: None :rtype: None :raises: None """ parent = index.parent() mapper.setRootIndex(parent) mapper.setCurrentModelIndex(index)
[ "def", "set_mapper_index", "(", "self", ",", "index", ",", "mapper", ")", ":", "parent", "=", "index", ".", "parent", "(", ")", "mapper", ".", "setRootIndex", "(", "parent", ")", "mapper", ".", "setCurrentModelIndex", "(", "index", ")" ]
Set the mapper to the given index :param index: the index to set :type index: QtCore.QModelIndex :param mapper: the mapper to set :type mapper: QtGui.QDataWidgetMapper :returns: None :rtype: None :raises: None
[ "Set", "the", "mapper", "to", "the", "given", "index" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/filebrowser.py#L541-L554
239,581
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/filebrowser.py
FileBrowser.get_releasetype
def get_releasetype(self, ): """Return the currently selected releasetype :returns: the selected releasetype :rtype: str :raises: None """ for rt, rb in self._releasetype_button_mapping.items(): if rb.isChecked(): return rt
python
def get_releasetype(self, ): """Return the currently selected releasetype :returns: the selected releasetype :rtype: str :raises: None """ for rt, rb in self._releasetype_button_mapping.items(): if rb.isChecked(): return rt
[ "def", "get_releasetype", "(", "self", ",", ")", ":", "for", "rt", ",", "rb", "in", "self", ".", "_releasetype_button_mapping", ".", "items", "(", ")", ":", "if", "rb", ".", "isChecked", "(", ")", ":", "return", "rt" ]
Return the currently selected releasetype :returns: the selected releasetype :rtype: str :raises: None
[ "Return", "the", "currently", "selected", "releasetype" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/filebrowser.py#L556-L565
239,582
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/filebrowser.py
FileBrowser.set_to_current
def set_to_current(self, ): """Set the selection to the currently open one :returns: None :rtype: None :raises: None """ cur = self.get_current_file() if cur is not None: self.set_selection(cur) else: self.init_selection()
python
def set_to_current(self, ): """Set the selection to the currently open one :returns: None :rtype: None :raises: None """ cur = self.get_current_file() if cur is not None: self.set_selection(cur) else: self.init_selection()
[ "def", "set_to_current", "(", "self", ",", ")", ":", "cur", "=", "self", ".", "get_current_file", "(", ")", "if", "cur", "is", "not", "None", ":", "self", ".", "set_selection", "(", "cur", ")", "else", ":", "self", ".", "init_selection", "(", ")" ]
Set the selection to the currently open one :returns: None :rtype: None :raises: None
[ "Set", "the", "selection", "to", "the", "currently", "open", "one" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/filebrowser.py#L601-L612
239,583
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/filebrowser.py
FileBrowser.set_selection
def set_selection(self, taskfile): """Set the selection to the given taskfile :param taskfile: the taskfile to set the selection to :type taskfile: :class:`djadapter.models.TaskFile` :returns: None :rtype: None :raises: None """ self.set_project(taskfile.task.project) self.set_releasetype(taskfile.releasetype) if taskfile.task.department.assetflag: browser = self.assetbrws verbrowser = self.assetverbrws tabi = 0 rootobj = taskfile.task.element.atype else: browser = self.shotbrws verbrowser = self.shotverbrws tabi = 1 rootobj = taskfile.task.element.sequence self.set_level(browser, 0, rootobj) self.set_level(browser, 1, taskfile.task.element) self.set_level(browser, 2, taskfile.task) self.set_level(browser, 3, [taskfile.descriptor]) self.set_level(verbrowser, 0, taskfile) self.selection_tabw.setCurrentIndex(tabi)
python
def set_selection(self, taskfile): """Set the selection to the given taskfile :param taskfile: the taskfile to set the selection to :type taskfile: :class:`djadapter.models.TaskFile` :returns: None :rtype: None :raises: None """ self.set_project(taskfile.task.project) self.set_releasetype(taskfile.releasetype) if taskfile.task.department.assetflag: browser = self.assetbrws verbrowser = self.assetverbrws tabi = 0 rootobj = taskfile.task.element.atype else: browser = self.shotbrws verbrowser = self.shotverbrws tabi = 1 rootobj = taskfile.task.element.sequence self.set_level(browser, 0, rootobj) self.set_level(browser, 1, taskfile.task.element) self.set_level(browser, 2, taskfile.task) self.set_level(browser, 3, [taskfile.descriptor]) self.set_level(verbrowser, 0, taskfile) self.selection_tabw.setCurrentIndex(tabi)
[ "def", "set_selection", "(", "self", ",", "taskfile", ")", ":", "self", ".", "set_project", "(", "taskfile", ".", "task", ".", "project", ")", "self", ".", "set_releasetype", "(", "taskfile", ".", "releasetype", ")", "if", "taskfile", ".", "task", ".", "department", ".", "assetflag", ":", "browser", "=", "self", ".", "assetbrws", "verbrowser", "=", "self", ".", "assetverbrws", "tabi", "=", "0", "rootobj", "=", "taskfile", ".", "task", ".", "element", ".", "atype", "else", ":", "browser", "=", "self", ".", "shotbrws", "verbrowser", "=", "self", ".", "shotverbrws", "tabi", "=", "1", "rootobj", "=", "taskfile", ".", "task", ".", "element", ".", "sequence", "self", ".", "set_level", "(", "browser", ",", "0", ",", "rootobj", ")", "self", ".", "set_level", "(", "browser", ",", "1", ",", "taskfile", ".", "task", ".", "element", ")", "self", ".", "set_level", "(", "browser", ",", "2", ",", "taskfile", ".", "task", ")", "self", ".", "set_level", "(", "browser", ",", "3", ",", "[", "taskfile", ".", "descriptor", "]", ")", "self", ".", "set_level", "(", "verbrowser", ",", "0", ",", "taskfile", ")", "self", ".", "selection_tabw", ".", "setCurrentIndex", "(", "tabi", ")" ]
Set the selection to the given taskfile :param taskfile: the taskfile to set the selection to :type taskfile: :class:`djadapter.models.TaskFile` :returns: None :rtype: None :raises: None
[ "Set", "the", "selection", "to", "the", "given", "taskfile" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/filebrowser.py#L614-L642
239,584
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/filebrowser.py
FileBrowser.set_project
def set_project(self, project): """Set the project selection to the given project :param project: the project to select :type project: :class:`djadapter.models.Project` :returns: None :rtype: None :raises: ValueError """ prjroot = self.prjbrws.model.root prjitems = prjroot.childItems for row, item in enumerate(prjitems): prj = item.internal_data() if prj == project: prjindex = self.prjbrws.model.index(row, 0) break else: raise ValueError("Could not select the given taskfile. No project %s found." % project.name) self.prjbrws.set_index(0, prjindex)
python
def set_project(self, project): """Set the project selection to the given project :param project: the project to select :type project: :class:`djadapter.models.Project` :returns: None :rtype: None :raises: ValueError """ prjroot = self.prjbrws.model.root prjitems = prjroot.childItems for row, item in enumerate(prjitems): prj = item.internal_data() if prj == project: prjindex = self.prjbrws.model.index(row, 0) break else: raise ValueError("Could not select the given taskfile. No project %s found." % project.name) self.prjbrws.set_index(0, prjindex)
[ "def", "set_project", "(", "self", ",", "project", ")", ":", "prjroot", "=", "self", ".", "prjbrws", ".", "model", ".", "root", "prjitems", "=", "prjroot", ".", "childItems", "for", "row", ",", "item", "in", "enumerate", "(", "prjitems", ")", ":", "prj", "=", "item", ".", "internal_data", "(", ")", "if", "prj", "==", "project", ":", "prjindex", "=", "self", ".", "prjbrws", ".", "model", ".", "index", "(", "row", ",", "0", ")", "break", "else", ":", "raise", "ValueError", "(", "\"Could not select the given taskfile. No project %s found.\"", "%", "project", ".", "name", ")", "self", ".", "prjbrws", ".", "set_index", "(", "0", ",", "prjindex", ")" ]
Set the project selection to the given project :param project: the project to select :type project: :class:`djadapter.models.Project` :returns: None :rtype: None :raises: ValueError
[ "Set", "the", "project", "selection", "to", "the", "given", "project" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/filebrowser.py#L644-L662
239,585
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/filebrowser.py
FileBrowser.set_level
def set_level(self, browser, lvl, obj): """Set the given browser level selection to the one that matches with obj This is going to compare the internal_data of the model with the obj :param browser: :type browser: :param lvl: the depth level to set :type lvl: int :param obj: the object to compare the indexes with :type obj: object :returns: None :rtype: None :raises: None """ if lvl == 0: index = QtCore.QModelIndex() root = browser.model.root items = root.childItems else: index = browser.selected_indexes(lvl-1)[0] item = index.internalPointer() items = item.childItems for row, item in enumerate(items): data = item.internal_data() if data == obj: newindex = browser.model.index(row, 0, index) break else: raise ValueError("Could not select the given object in the browser. %s not found." % obj) browser.set_index(lvl, newindex)
python
def set_level(self, browser, lvl, obj): """Set the given browser level selection to the one that matches with obj This is going to compare the internal_data of the model with the obj :param browser: :type browser: :param lvl: the depth level to set :type lvl: int :param obj: the object to compare the indexes with :type obj: object :returns: None :rtype: None :raises: None """ if lvl == 0: index = QtCore.QModelIndex() root = browser.model.root items = root.childItems else: index = browser.selected_indexes(lvl-1)[0] item = index.internalPointer() items = item.childItems for row, item in enumerate(items): data = item.internal_data() if data == obj: newindex = browser.model.index(row, 0, index) break else: raise ValueError("Could not select the given object in the browser. %s not found." % obj) browser.set_index(lvl, newindex)
[ "def", "set_level", "(", "self", ",", "browser", ",", "lvl", ",", "obj", ")", ":", "if", "lvl", "==", "0", ":", "index", "=", "QtCore", ".", "QModelIndex", "(", ")", "root", "=", "browser", ".", "model", ".", "root", "items", "=", "root", ".", "childItems", "else", ":", "index", "=", "browser", ".", "selected_indexes", "(", "lvl", "-", "1", ")", "[", "0", "]", "item", "=", "index", ".", "internalPointer", "(", ")", "items", "=", "item", ".", "childItems", "for", "row", ",", "item", "in", "enumerate", "(", "items", ")", ":", "data", "=", "item", ".", "internal_data", "(", ")", "if", "data", "==", "obj", ":", "newindex", "=", "browser", ".", "model", ".", "index", "(", "row", ",", "0", ",", "index", ")", "break", "else", ":", "raise", "ValueError", "(", "\"Could not select the given object in the browser. %s not found.\"", "%", "obj", ")", "browser", ".", "set_index", "(", "lvl", ",", "newindex", ")" ]
Set the given browser level selection to the one that matches with obj This is going to compare the internal_data of the model with the obj :param browser: :type browser: :param lvl: the depth level to set :type lvl: int :param obj: the object to compare the indexes with :type obj: object :returns: None :rtype: None :raises: None
[ "Set", "the", "given", "browser", "level", "selection", "to", "the", "one", "that", "matches", "with", "obj" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/filebrowser.py#L675-L705
239,586
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/filebrowser.py
FileBrowser.update_model
def update_model(self, tfi): """Update the model for the given tfi :param tfi: taskfile info :type tfi: :class:`TaskFileInfo` :returns: None :rtype: None :raises: None """ if tfi.task.department.assetflag: browser = self.assetbrws else: browser = self.shotbrws if tfi.version == 1: # add descriptor parent = browser.selected_indexes(2)[0] ddata = treemodel.ListItemData([tfi.descriptor]) ditem = treemodel.TreeItem(ddata) browser.model.insertRow(0, ditem, parent) self.set_level(browser, 3, [tfi.descriptor])
python
def update_model(self, tfi): """Update the model for the given tfi :param tfi: taskfile info :type tfi: :class:`TaskFileInfo` :returns: None :rtype: None :raises: None """ if tfi.task.department.assetflag: browser = self.assetbrws else: browser = self.shotbrws if tfi.version == 1: # add descriptor parent = browser.selected_indexes(2)[0] ddata = treemodel.ListItemData([tfi.descriptor]) ditem = treemodel.TreeItem(ddata) browser.model.insertRow(0, ditem, parent) self.set_level(browser, 3, [tfi.descriptor])
[ "def", "update_model", "(", "self", ",", "tfi", ")", ":", "if", "tfi", ".", "task", ".", "department", ".", "assetflag", ":", "browser", "=", "self", ".", "assetbrws", "else", ":", "browser", "=", "self", ".", "shotbrws", "if", "tfi", ".", "version", "==", "1", ":", "# add descriptor", "parent", "=", "browser", ".", "selected_indexes", "(", "2", ")", "[", "0", "]", "ddata", "=", "treemodel", ".", "ListItemData", "(", "[", "tfi", ".", "descriptor", "]", ")", "ditem", "=", "treemodel", ".", "TreeItem", "(", "ddata", ")", "browser", ".", "model", ".", "insertRow", "(", "0", ",", "ditem", ",", "parent", ")", "self", ".", "set_level", "(", "browser", ",", "3", ",", "[", "tfi", ".", "descriptor", "]", ")" ]
Update the model for the given tfi :param tfi: taskfile info :type tfi: :class:`TaskFileInfo` :returns: None :rtype: None :raises: None
[ "Update", "the", "model", "for", "the", "given", "tfi" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/filebrowser.py#L722-L741
239,587
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/filebrowser.py
FileBrowser.open_asset_path
def open_asset_path(self, *args, **kwargs): """Open the currently selected asset in the filebrowser :returns: None :rtype: None :raises: None """ f = self.asset_path_le.text() d = os.path.dirname(f) osinter = get_interface() osinter.open_path(d)
python
def open_asset_path(self, *args, **kwargs): """Open the currently selected asset in the filebrowser :returns: None :rtype: None :raises: None """ f = self.asset_path_le.text() d = os.path.dirname(f) osinter = get_interface() osinter.open_path(d)
[ "def", "open_asset_path", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "f", "=", "self", ".", "asset_path_le", ".", "text", "(", ")", "d", "=", "os", ".", "path", ".", "dirname", "(", "f", ")", "osinter", "=", "get_interface", "(", ")", "osinter", ".", "open_path", "(", "d", ")" ]
Open the currently selected asset in the filebrowser :returns: None :rtype: None :raises: None
[ "Open", "the", "currently", "selected", "asset", "in", "the", "filebrowser" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/filebrowser.py#L743-L753
239,588
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/filebrowser.py
FileBrowser.open_shot_path
def open_shot_path(self, *args, **kwargs): """Open the currently selected shot in the filebrowser :returns: None :rtype: None :raises: None """ f = self.shot_path_le.text() d = os.path.dirname(f) osinter = get_interface() osinter.open_path(d)
python
def open_shot_path(self, *args, **kwargs): """Open the currently selected shot in the filebrowser :returns: None :rtype: None :raises: None """ f = self.shot_path_le.text() d = os.path.dirname(f) osinter = get_interface() osinter.open_path(d)
[ "def", "open_shot_path", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "f", "=", "self", ".", "shot_path_le", ".", "text", "(", ")", "d", "=", "os", ".", "path", ".", "dirname", "(", "f", ")", "osinter", "=", "get_interface", "(", ")", "osinter", ".", "open_path", "(", "d", ")" ]
Open the currently selected shot in the filebrowser :returns: None :rtype: None :raises: None
[ "Open", "the", "currently", "selected", "shot", "in", "the", "filebrowser" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/filebrowser.py#L755-L765
239,589
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/filebrowser.py
FileBrowser.refresh
def refresh(self, *args, **kwargs): """Refresh the model :returns: None :rtype: None :raises: None """ self.prjbrws.set_model(self.create_prj_model()) if self.get_current_file(): self.set_to_current() else: self.init_selection()
python
def refresh(self, *args, **kwargs): """Refresh the model :returns: None :rtype: None :raises: None """ self.prjbrws.set_model(self.create_prj_model()) if self.get_current_file(): self.set_to_current() else: self.init_selection()
[ "def", "refresh", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "prjbrws", ".", "set_model", "(", "self", ".", "create_prj_model", "(", ")", ")", "if", "self", ".", "get_current_file", "(", ")", ":", "self", ".", "set_to_current", "(", ")", "else", ":", "self", ".", "init_selection", "(", ")" ]
Refresh the model :returns: None :rtype: None :raises: None
[ "Refresh", "the", "model" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/filebrowser.py#L789-L800
239,590
zkbt/the-friendly-stars
thefriendlystars/talker.py
Talker.report
def report(self, string='', level=0, prelude='', progress=False, abbreviate=True): '''If verbose=True, this will print to terminal. Otherwise, it won't.''' if self._mute == False: self._prefix = prelude + '{spacing}[{name}] '.format(name = self.nametag, spacing = ' '*level) self._prefix = "{0:>16}".format(self._prefix) equalspaces = ' '*len(self._prefix) toprint = string + '' if abbreviate: if shortcuts is not None: for k in shortcuts.keys(): toprint = toprint.replace(k, shortcuts[k]) if progress: print('\r' + self._prefix + toprint.replace('\n', '\n' + equalspaces),) else: print(self._prefix + toprint.replace('\n', '\n' + equalspaces))
python
def report(self, string='', level=0, prelude='', progress=False, abbreviate=True): '''If verbose=True, this will print to terminal. Otherwise, it won't.''' if self._mute == False: self._prefix = prelude + '{spacing}[{name}] '.format(name = self.nametag, spacing = ' '*level) self._prefix = "{0:>16}".format(self._prefix) equalspaces = ' '*len(self._prefix) toprint = string + '' if abbreviate: if shortcuts is not None: for k in shortcuts.keys(): toprint = toprint.replace(k, shortcuts[k]) if progress: print('\r' + self._prefix + toprint.replace('\n', '\n' + equalspaces),) else: print(self._prefix + toprint.replace('\n', '\n' + equalspaces))
[ "def", "report", "(", "self", ",", "string", "=", "''", ",", "level", "=", "0", ",", "prelude", "=", "''", ",", "progress", "=", "False", ",", "abbreviate", "=", "True", ")", ":", "if", "self", ".", "_mute", "==", "False", ":", "self", ".", "_prefix", "=", "prelude", "+", "'{spacing}[{name}] '", ".", "format", "(", "name", "=", "self", ".", "nametag", ",", "spacing", "=", "' '", "*", "level", ")", "self", ".", "_prefix", "=", "\"{0:>16}\"", ".", "format", "(", "self", ".", "_prefix", ")", "equalspaces", "=", "' '", "*", "len", "(", "self", ".", "_prefix", ")", "toprint", "=", "string", "+", "''", "if", "abbreviate", ":", "if", "shortcuts", "is", "not", "None", ":", "for", "k", "in", "shortcuts", ".", "keys", "(", ")", ":", "toprint", "=", "toprint", ".", "replace", "(", "k", ",", "shortcuts", "[", "k", "]", ")", "if", "progress", ":", "print", "(", "'\\r'", "+", "self", ".", "_prefix", "+", "toprint", ".", "replace", "(", "'\\n'", ",", "'\\n'", "+", "equalspaces", ")", ",", ")", "else", ":", "print", "(", "self", ".", "_prefix", "+", "toprint", ".", "replace", "(", "'\\n'", ",", "'\\n'", "+", "equalspaces", ")", ")" ]
If verbose=True, this will print to terminal. Otherwise, it won't.
[ "If", "verbose", "=", "True", "this", "will", "print", "to", "terminal", ".", "Otherwise", "it", "won", "t", "." ]
50d3f979e79e63c66629065c75595696dc79802e
https://github.com/zkbt/the-friendly-stars/blob/50d3f979e79e63c66629065c75595696dc79802e/thefriendlystars/talker.py#L43-L58
239,591
zkbt/the-friendly-stars
thefriendlystars/talker.py
Talker.summarize
def summarize(self): '''Print a summary of the contents of this object.''' self.speak('Here is a brief summary of {}.'.format(self.nametag)) s = '\n'+pprint.pformat(self.__dict__) print(s.replace('\n', '\n'+' '*(len(self._prefix)+1)) + '\n')
python
def summarize(self): '''Print a summary of the contents of this object.''' self.speak('Here is a brief summary of {}.'.format(self.nametag)) s = '\n'+pprint.pformat(self.__dict__) print(s.replace('\n', '\n'+' '*(len(self._prefix)+1)) + '\n')
[ "def", "summarize", "(", "self", ")", ":", "self", ".", "speak", "(", "'Here is a brief summary of {}.'", ".", "format", "(", "self", ".", "nametag", ")", ")", "s", "=", "'\\n'", "+", "pprint", ".", "pformat", "(", "self", ".", "__dict__", ")", "print", "(", "s", ".", "replace", "(", "'\\n'", ",", "'\\n'", "+", "' '", "*", "(", "len", "(", "self", ".", "_prefix", ")", "+", "1", ")", ")", "+", "'\\n'", ")" ]
Print a summary of the contents of this object.
[ "Print", "a", "summary", "of", "the", "contents", "of", "this", "object", "." ]
50d3f979e79e63c66629065c75595696dc79802e
https://github.com/zkbt/the-friendly-stars/blob/50d3f979e79e63c66629065c75595696dc79802e/thefriendlystars/talker.py#L62-L67
239,592
roboogle/gtkmvc3
gtkmvco/examples/converter/main1.py
setup_path
def setup_path(): """Sets up the python include paths to include src""" import os.path; import sys if sys.argv[0]: top_dir = os.path.dirname(os.path.abspath(sys.argv[0])) sys.path = [os.path.join(top_dir, "src")] + sys.path pass return
python
def setup_path(): """Sets up the python include paths to include src""" import os.path; import sys if sys.argv[0]: top_dir = os.path.dirname(os.path.abspath(sys.argv[0])) sys.path = [os.path.join(top_dir, "src")] + sys.path pass return
[ "def", "setup_path", "(", ")", ":", "import", "os", ".", "path", "import", "sys", "if", "sys", ".", "argv", "[", "0", "]", ":", "top_dir", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "sys", ".", "argv", "[", "0", "]", ")", ")", "sys", ".", "path", "=", "[", "os", ".", "path", ".", "join", "(", "top_dir", ",", "\"src\"", ")", "]", "+", "sys", ".", "path", "pass", "return" ]
Sets up the python include paths to include src
[ "Sets", "up", "the", "python", "include", "paths", "to", "include", "src" ]
63405fd8d2056be26af49103b13a8d5e57fe4dff
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/examples/converter/main1.py#L26-L34
239,593
Brazelton-Lab/bio_utils
bio_utils/verifiers/verify_entries.py
entry_verifier
def entry_verifier(entries, regex, delimiter): """Checks each entry against regex for validity, If an entry does not match the regex, the entry and regex are broken down by the delimiter and each segment is analyzed to produce an accurate error message. Args: entries (list): List of entries to check with regex regex (str): Regular expression to compare entries with delimiter (str): Character to split entry and regex by, used to check parts of entry and regex to narrow in on the error Raises: FormatError: Class containing regex match error data Example: >>> regex = r'^>.+\\n[ACGTU]+\\n$' >>> entry = [r'>entry1\\nAGGGACTA\\n'] >>> entry_verifier(entry, regex, '\\n') """ cregex = re.compile(regex) # Compiling saves time if many entries given # Encode raw delimiter in order to split a bad entry python_version = int(sys.version.split('.')[0]) decoder = 'unicode-escape' if python_version == 3 else 'string-escape' dedelimiter = codecs.decode(delimiter, decoder) for entry in entries: match = re.match(cregex, entry) # Match failed, check regex and entry parts for error if not match: split_regex = regex.split(delimiter) split_entry = entry.split(dedelimiter) part = 0 # "Enumerate" zipped iter for regex_segment, entry_segment in zip(split_regex, split_entry): # Ensure regex_segment only matches entire entry_segment if not regex_segment[0] == '^': regex_segment = '^' + regex_segment if not regex_segment[-1] == '$': regex_segment += '$' # If segment fails, raise error and store info on failure if not re.match(regex_segment, entry_segment): raise FormatError(template=regex_segment, subject=entry_segment, part=part) part += 1
python
def entry_verifier(entries, regex, delimiter): """Checks each entry against regex for validity, If an entry does not match the regex, the entry and regex are broken down by the delimiter and each segment is analyzed to produce an accurate error message. Args: entries (list): List of entries to check with regex regex (str): Regular expression to compare entries with delimiter (str): Character to split entry and regex by, used to check parts of entry and regex to narrow in on the error Raises: FormatError: Class containing regex match error data Example: >>> regex = r'^>.+\\n[ACGTU]+\\n$' >>> entry = [r'>entry1\\nAGGGACTA\\n'] >>> entry_verifier(entry, regex, '\\n') """ cregex = re.compile(regex) # Compiling saves time if many entries given # Encode raw delimiter in order to split a bad entry python_version = int(sys.version.split('.')[0]) decoder = 'unicode-escape' if python_version == 3 else 'string-escape' dedelimiter = codecs.decode(delimiter, decoder) for entry in entries: match = re.match(cregex, entry) # Match failed, check regex and entry parts for error if not match: split_regex = regex.split(delimiter) split_entry = entry.split(dedelimiter) part = 0 # "Enumerate" zipped iter for regex_segment, entry_segment in zip(split_regex, split_entry): # Ensure regex_segment only matches entire entry_segment if not regex_segment[0] == '^': regex_segment = '^' + regex_segment if not regex_segment[-1] == '$': regex_segment += '$' # If segment fails, raise error and store info on failure if not re.match(regex_segment, entry_segment): raise FormatError(template=regex_segment, subject=entry_segment, part=part) part += 1
[ "def", "entry_verifier", "(", "entries", ",", "regex", ",", "delimiter", ")", ":", "cregex", "=", "re", ".", "compile", "(", "regex", ")", "# Compiling saves time if many entries given", "# Encode raw delimiter in order to split a bad entry", "python_version", "=", "int", "(", "sys", ".", "version", ".", "split", "(", "'.'", ")", "[", "0", "]", ")", "decoder", "=", "'unicode-escape'", "if", "python_version", "==", "3", "else", "'string-escape'", "dedelimiter", "=", "codecs", ".", "decode", "(", "delimiter", ",", "decoder", ")", "for", "entry", "in", "entries", ":", "match", "=", "re", ".", "match", "(", "cregex", ",", "entry", ")", "# Match failed, check regex and entry parts for error", "if", "not", "match", ":", "split_regex", "=", "regex", ".", "split", "(", "delimiter", ")", "split_entry", "=", "entry", ".", "split", "(", "dedelimiter", ")", "part", "=", "0", "# \"Enumerate\" zipped iter", "for", "regex_segment", ",", "entry_segment", "in", "zip", "(", "split_regex", ",", "split_entry", ")", ":", "# Ensure regex_segment only matches entire entry_segment", "if", "not", "regex_segment", "[", "0", "]", "==", "'^'", ":", "regex_segment", "=", "'^'", "+", "regex_segment", "if", "not", "regex_segment", "[", "-", "1", "]", "==", "'$'", ":", "regex_segment", "+=", "'$'", "# If segment fails, raise error and store info on failure", "if", "not", "re", ".", "match", "(", "regex_segment", ",", "entry_segment", ")", ":", "raise", "FormatError", "(", "template", "=", "regex_segment", ",", "subject", "=", "entry_segment", ",", "part", "=", "part", ")", "part", "+=", "1" ]
Checks each entry against regex for validity, If an entry does not match the regex, the entry and regex are broken down by the delimiter and each segment is analyzed to produce an accurate error message. Args: entries (list): List of entries to check with regex regex (str): Regular expression to compare entries with delimiter (str): Character to split entry and regex by, used to check parts of entry and regex to narrow in on the error Raises: FormatError: Class containing regex match error data Example: >>> regex = r'^>.+\\n[ACGTU]+\\n$' >>> entry = [r'>entry1\\nAGGGACTA\\n'] >>> entry_verifier(entry, regex, '\\n')
[ "Checks", "each", "entry", "against", "regex", "for", "validity" ]
5a7ddf13ee0bf4baaaeb6b2b99e01bf74aa132b7
https://github.com/Brazelton-Lab/bio_utils/blob/5a7ddf13ee0bf4baaaeb6b2b99e01bf74aa132b7/bio_utils/verifiers/verify_entries.py#L78-L130
239,594
mapmyfitness/jtime
jtime/connection.py
jira_connection
def jira_connection(config): """ Gets a JIRA API connection. If a connection has already been created the existing connection will be returned. """ global _jira_connection if _jira_connection: return _jira_connection else: jira_options = {'server': config.get('jira').get('url')} cookies = configuration._get_cookies_as_dict() jira_connection = jira_ext.JIRA(options=jira_options) session = jira_connection._session reused_session = False if cookies: requests.utils.add_dict_to_cookiejar(session.cookies, cookies) try: jira_connection.session() reused_session = True except Exception: pass if not reused_session: session.auth = (config['jira']['username'], base64.b64decode(config['jira']['password'])) jira_connection.session() session.auth = None cookie_jar_hash = requests.utils.dict_from_cookiejar(session.cookies) for key, value in cookie_jar_hash.iteritems(): configuration._save_cookie(key, value) _jira_connection = jira_connection return _jira_connection
python
def jira_connection(config): """ Gets a JIRA API connection. If a connection has already been created the existing connection will be returned. """ global _jira_connection if _jira_connection: return _jira_connection else: jira_options = {'server': config.get('jira').get('url')} cookies = configuration._get_cookies_as_dict() jira_connection = jira_ext.JIRA(options=jira_options) session = jira_connection._session reused_session = False if cookies: requests.utils.add_dict_to_cookiejar(session.cookies, cookies) try: jira_connection.session() reused_session = True except Exception: pass if not reused_session: session.auth = (config['jira']['username'], base64.b64decode(config['jira']['password'])) jira_connection.session() session.auth = None cookie_jar_hash = requests.utils.dict_from_cookiejar(session.cookies) for key, value in cookie_jar_hash.iteritems(): configuration._save_cookie(key, value) _jira_connection = jira_connection return _jira_connection
[ "def", "jira_connection", "(", "config", ")", ":", "global", "_jira_connection", "if", "_jira_connection", ":", "return", "_jira_connection", "else", ":", "jira_options", "=", "{", "'server'", ":", "config", ".", "get", "(", "'jira'", ")", ".", "get", "(", "'url'", ")", "}", "cookies", "=", "configuration", ".", "_get_cookies_as_dict", "(", ")", "jira_connection", "=", "jira_ext", ".", "JIRA", "(", "options", "=", "jira_options", ")", "session", "=", "jira_connection", ".", "_session", "reused_session", "=", "False", "if", "cookies", ":", "requests", ".", "utils", ".", "add_dict_to_cookiejar", "(", "session", ".", "cookies", ",", "cookies", ")", "try", ":", "jira_connection", ".", "session", "(", ")", "reused_session", "=", "True", "except", "Exception", ":", "pass", "if", "not", "reused_session", ":", "session", ".", "auth", "=", "(", "config", "[", "'jira'", "]", "[", "'username'", "]", ",", "base64", ".", "b64decode", "(", "config", "[", "'jira'", "]", "[", "'password'", "]", ")", ")", "jira_connection", ".", "session", "(", ")", "session", ".", "auth", "=", "None", "cookie_jar_hash", "=", "requests", ".", "utils", ".", "dict_from_cookiejar", "(", "session", ".", "cookies", ")", "for", "key", ",", "value", "in", "cookie_jar_hash", ".", "iteritems", "(", ")", ":", "configuration", ".", "_save_cookie", "(", "key", ",", "value", ")", "_jira_connection", "=", "jira_connection", "return", "_jira_connection" ]
Gets a JIRA API connection. If a connection has already been created the existing connection will be returned.
[ "Gets", "a", "JIRA", "API", "connection", ".", "If", "a", "connection", "has", "already", "been", "created", "the", "existing", "connection", "will", "be", "returned", "." ]
402fb6b40ac7a78c23fd02fac50c6dbe49e5ebfd
https://github.com/mapmyfitness/jtime/blob/402fb6b40ac7a78c23fd02fac50c6dbe49e5ebfd/jtime/connection.py#L12-L47
239,595
rbarrois/django-batchform
batchform/views.py
BaseUploadView.form_upload_valid
def form_upload_valid(self, form): """Handle a valid upload form.""" self.current_step = self.STEP_LINES lines = form.cleaned_data['file'] initial_lines = [dict(zip(self.get_columns(), line)) for line in lines] inner_form = self.get_form(self.get_form_class(), data=None, files=None, initial=initial_lines, ) return self.render_to_response(self.get_context_data(form=inner_form))
python
def form_upload_valid(self, form): """Handle a valid upload form.""" self.current_step = self.STEP_LINES lines = form.cleaned_data['file'] initial_lines = [dict(zip(self.get_columns(), line)) for line in lines] inner_form = self.get_form(self.get_form_class(), data=None, files=None, initial=initial_lines, ) return self.render_to_response(self.get_context_data(form=inner_form))
[ "def", "form_upload_valid", "(", "self", ",", "form", ")", ":", "self", ".", "current_step", "=", "self", ".", "STEP_LINES", "lines", "=", "form", ".", "cleaned_data", "[", "'file'", "]", "initial_lines", "=", "[", "dict", "(", "zip", "(", "self", ".", "get_columns", "(", ")", ",", "line", ")", ")", "for", "line", "in", "lines", "]", "inner_form", "=", "self", ".", "get_form", "(", "self", ".", "get_form_class", "(", ")", ",", "data", "=", "None", ",", "files", "=", "None", ",", "initial", "=", "initial_lines", ",", ")", "return", "self", ".", "render_to_response", "(", "self", ".", "get_context_data", "(", "form", "=", "inner_form", ")", ")" ]
Handle a valid upload form.
[ "Handle", "a", "valid", "upload", "form", "." ]
f6b659a6790750285af248ccd1d4d178ecbad129
https://github.com/rbarrois/django-batchform/blob/f6b659a6790750285af248ccd1d4d178ecbad129/batchform/views.py#L99-L110
239,596
rbarrois/django-batchform
batchform/views.py
BaseUploadView.form_lines_valid
def form_lines_valid(self, form): """Handle a valid LineFormSet.""" handled = 0 for inner_form in form: if not inner_form.cleaned_data.get(formsets.DELETION_FIELD_NAME): handled += 1 self.handle_inner_form(inner_form) self.log_and_notify_lines(handled) return http.HttpResponseRedirect(self.get_success_url())
python
def form_lines_valid(self, form): """Handle a valid LineFormSet.""" handled = 0 for inner_form in form: if not inner_form.cleaned_data.get(formsets.DELETION_FIELD_NAME): handled += 1 self.handle_inner_form(inner_form) self.log_and_notify_lines(handled) return http.HttpResponseRedirect(self.get_success_url())
[ "def", "form_lines_valid", "(", "self", ",", "form", ")", ":", "handled", "=", "0", "for", "inner_form", "in", "form", ":", "if", "not", "inner_form", ".", "cleaned_data", ".", "get", "(", "formsets", ".", "DELETION_FIELD_NAME", ")", ":", "handled", "+=", "1", "self", ".", "handle_inner_form", "(", "inner_form", ")", "self", ".", "log_and_notify_lines", "(", "handled", ")", "return", "http", ".", "HttpResponseRedirect", "(", "self", ".", "get_success_url", "(", ")", ")" ]
Handle a valid LineFormSet.
[ "Handle", "a", "valid", "LineFormSet", "." ]
f6b659a6790750285af248ccd1d4d178ecbad129
https://github.com/rbarrois/django-batchform/blob/f6b659a6790750285af248ccd1d4d178ecbad129/batchform/views.py#L119-L128
239,597
emilydolson/avida-spatial-tools
avidaspatial/transform_data.py
rank_clusters
def rank_clusters(cluster_dict): """ Helper function for clustering that takes a dictionary mapping cluster ids to lists of the binary strings that are part of that cluster and returns a dictionary mapping cluster ids to integers representing their "rank". Ranks provide an ordering for the clusters such that each cluster has its own rank, and clusters are ordered from simplest to most complex. """ # Figure out the relative rank of each cluster cluster_ranks = dict.fromkeys(cluster_dict.keys()) for key in cluster_dict: cluster_ranks[key] = eval(string_avg(cluster_dict[key], binary=True)) i = len(cluster_ranks) for key in sorted(cluster_ranks, key=cluster_ranks.get): cluster_ranks[key] = i i -= 1 return cluster_ranks
python
def rank_clusters(cluster_dict): """ Helper function for clustering that takes a dictionary mapping cluster ids to lists of the binary strings that are part of that cluster and returns a dictionary mapping cluster ids to integers representing their "rank". Ranks provide an ordering for the clusters such that each cluster has its own rank, and clusters are ordered from simplest to most complex. """ # Figure out the relative rank of each cluster cluster_ranks = dict.fromkeys(cluster_dict.keys()) for key in cluster_dict: cluster_ranks[key] = eval(string_avg(cluster_dict[key], binary=True)) i = len(cluster_ranks) for key in sorted(cluster_ranks, key=cluster_ranks.get): cluster_ranks[key] = i i -= 1 return cluster_ranks
[ "def", "rank_clusters", "(", "cluster_dict", ")", ":", "# Figure out the relative rank of each cluster", "cluster_ranks", "=", "dict", ".", "fromkeys", "(", "cluster_dict", ".", "keys", "(", ")", ")", "for", "key", "in", "cluster_dict", ":", "cluster_ranks", "[", "key", "]", "=", "eval", "(", "string_avg", "(", "cluster_dict", "[", "key", "]", ",", "binary", "=", "True", ")", ")", "i", "=", "len", "(", "cluster_ranks", ")", "for", "key", "in", "sorted", "(", "cluster_ranks", ",", "key", "=", "cluster_ranks", ".", "get", ")", ":", "cluster_ranks", "[", "key", "]", "=", "i", "i", "-=", "1", "return", "cluster_ranks" ]
Helper function for clustering that takes a dictionary mapping cluster ids to lists of the binary strings that are part of that cluster and returns a dictionary mapping cluster ids to integers representing their "rank". Ranks provide an ordering for the clusters such that each cluster has its own rank, and clusters are ordered from simplest to most complex.
[ "Helper", "function", "for", "clustering", "that", "takes", "a", "dictionary", "mapping", "cluster", "ids", "to", "lists", "of", "the", "binary", "strings", "that", "are", "part", "of", "that", "cluster", "and", "returns", "a", "dictionary", "mapping", "cluster", "ids", "to", "integers", "representing", "their", "rank", ".", "Ranks", "provide", "an", "ordering", "for", "the", "clusters", "such", "that", "each", "cluster", "has", "its", "own", "rank", "and", "clusters", "are", "ordered", "from", "simplest", "to", "most", "complex", "." ]
7beb0166ccefad5fa722215b030ac2a53d62b59e
https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/transform_data.py#L61-L80
239,598
emilydolson/avida-spatial-tools
avidaspatial/transform_data.py
generate_ranks
def generate_ranks(grid, n): """ Takes a grid of phenotypes or resource sets representing as strings representing binary numbers, and an integer indicating the maximum number of clusters to generated. Clusters the data in grid into a maximum of n groups, ranks each group by the complexity and length of its "average" member, and returns a dictionary mapping binary numbers to integers representing the rank of the cluster they're part of. """ phenotypes = deepcopy(grid) if type(phenotypes) is list and type(phenotypes[0]) is list: phenotypes = flatten_array(phenotypes) # Remove duplicates from types types = list(frozenset(phenotypes)) if len(types) < n: ranks = rank_types(types) else: ranks = cluster_types(types, n) return ranks
python
def generate_ranks(grid, n): """ Takes a grid of phenotypes or resource sets representing as strings representing binary numbers, and an integer indicating the maximum number of clusters to generated. Clusters the data in grid into a maximum of n groups, ranks each group by the complexity and length of its "average" member, and returns a dictionary mapping binary numbers to integers representing the rank of the cluster they're part of. """ phenotypes = deepcopy(grid) if type(phenotypes) is list and type(phenotypes[0]) is list: phenotypes = flatten_array(phenotypes) # Remove duplicates from types types = list(frozenset(phenotypes)) if len(types) < n: ranks = rank_types(types) else: ranks = cluster_types(types, n) return ranks
[ "def", "generate_ranks", "(", "grid", ",", "n", ")", ":", "phenotypes", "=", "deepcopy", "(", "grid", ")", "if", "type", "(", "phenotypes", ")", "is", "list", "and", "type", "(", "phenotypes", "[", "0", "]", ")", "is", "list", ":", "phenotypes", "=", "flatten_array", "(", "phenotypes", ")", "# Remove duplicates from types", "types", "=", "list", "(", "frozenset", "(", "phenotypes", ")", ")", "if", "len", "(", "types", ")", "<", "n", ":", "ranks", "=", "rank_types", "(", "types", ")", "else", ":", "ranks", "=", "cluster_types", "(", "types", ",", "n", ")", "return", "ranks" ]
Takes a grid of phenotypes or resource sets representing as strings representing binary numbers, and an integer indicating the maximum number of clusters to generated. Clusters the data in grid into a maximum of n groups, ranks each group by the complexity and length of its "average" member, and returns a dictionary mapping binary numbers to integers representing the rank of the cluster they're part of.
[ "Takes", "a", "grid", "of", "phenotypes", "or", "resource", "sets", "representing", "as", "strings", "representing", "binary", "numbers", "and", "an", "integer", "indicating", "the", "maximum", "number", "of", "clusters", "to", "generated", "." ]
7beb0166ccefad5fa722215b030ac2a53d62b59e
https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/transform_data.py#L131-L153
239,599
emilydolson/avida-spatial-tools
avidaspatial/transform_data.py
assign_ranks_to_grid
def assign_ranks_to_grid(grid, ranks): """ Takes a 2D array of binary numbers represented as strings and a dictionary mapping binary strings to integers representing the rank of the cluster they belong to, and returns a grid in which each binary number has been replaced with the rank of its cluster. """ assignments = deepcopy(grid) ranks["0b0"] = 0 ranks["-0b1"] = -1 for i in range(len(grid)): for j in range(len(grid[i])): if type(grid[i][j]) is list: for k in range(len(grid[i][j])): assignments[i][j][k] = ranks[grid[i][j][k]] else: assignments[i][j] = ranks[grid[i][j]] return assignments
python
def assign_ranks_to_grid(grid, ranks): """ Takes a 2D array of binary numbers represented as strings and a dictionary mapping binary strings to integers representing the rank of the cluster they belong to, and returns a grid in which each binary number has been replaced with the rank of its cluster. """ assignments = deepcopy(grid) ranks["0b0"] = 0 ranks["-0b1"] = -1 for i in range(len(grid)): for j in range(len(grid[i])): if type(grid[i][j]) is list: for k in range(len(grid[i][j])): assignments[i][j][k] = ranks[grid[i][j][k]] else: assignments[i][j] = ranks[grid[i][j]] return assignments
[ "def", "assign_ranks_to_grid", "(", "grid", ",", "ranks", ")", ":", "assignments", "=", "deepcopy", "(", "grid", ")", "ranks", "[", "\"0b0\"", "]", "=", "0", "ranks", "[", "\"-0b1\"", "]", "=", "-", "1", "for", "i", "in", "range", "(", "len", "(", "grid", ")", ")", ":", "for", "j", "in", "range", "(", "len", "(", "grid", "[", "i", "]", ")", ")", ":", "if", "type", "(", "grid", "[", "i", "]", "[", "j", "]", ")", "is", "list", ":", "for", "k", "in", "range", "(", "len", "(", "grid", "[", "i", "]", "[", "j", "]", ")", ")", ":", "assignments", "[", "i", "]", "[", "j", "]", "[", "k", "]", "=", "ranks", "[", "grid", "[", "i", "]", "[", "j", "]", "[", "k", "]", "]", "else", ":", "assignments", "[", "i", "]", "[", "j", "]", "=", "ranks", "[", "grid", "[", "i", "]", "[", "j", "]", "]", "return", "assignments" ]
Takes a 2D array of binary numbers represented as strings and a dictionary mapping binary strings to integers representing the rank of the cluster they belong to, and returns a grid in which each binary number has been replaced with the rank of its cluster.
[ "Takes", "a", "2D", "array", "of", "binary", "numbers", "represented", "as", "strings", "and", "a", "dictionary", "mapping", "binary", "strings", "to", "integers", "representing", "the", "rank", "of", "the", "cluster", "they", "belong", "to", "and", "returns", "a", "grid", "in", "which", "each", "binary", "number", "has", "been", "replaced", "with", "the", "rank", "of", "its", "cluster", "." ]
7beb0166ccefad5fa722215b030ac2a53d62b59e
https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/transform_data.py#L156-L175