id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
27,600
RusticiSoftware/TinCanPython
tincan/serializable_base.py
SerializableBase.as_version
def as_version(self, version=Version.latest): """Returns a dict that has been modified based on versioning in order to be represented in JSON properly A class should overload as_version(self, version) implementation in order to tailor a more specific representation :param version: the relevant version. This allows for variance between versions :type version: str | unicode """ if not isinstance(self, list): result = {} for k, v in self.iteritems() if isinstance(self, dict) else vars(self).iteritems(): k = self._props_corrected.get(k, k) if isinstance(v, SerializableBase): result[k] = v.as_version(version) elif isinstance(v, list): result[k] = [] for val in v: if isinstance(val, SerializableBase): result[k].append(val.as_version(version)) else: result[k].append(val) elif isinstance(v, uuid.UUID): result[k] = unicode(v) elif isinstance(v, datetime.timedelta): result[k] = jsonify_timedelta(v) elif isinstance(v, datetime.datetime): result[k] = jsonify_datetime(v) else: result[k] = v result = self._filter_none(result) else: result = [] for v in self: if isinstance(v, SerializableBase): result.append(v.as_version(version)) else: result.append(v) return result
python
def as_version(self, version=Version.latest): if not isinstance(self, list): result = {} for k, v in self.iteritems() if isinstance(self, dict) else vars(self).iteritems(): k = self._props_corrected.get(k, k) if isinstance(v, SerializableBase): result[k] = v.as_version(version) elif isinstance(v, list): result[k] = [] for val in v: if isinstance(val, SerializableBase): result[k].append(val.as_version(version)) else: result[k].append(val) elif isinstance(v, uuid.UUID): result[k] = unicode(v) elif isinstance(v, datetime.timedelta): result[k] = jsonify_timedelta(v) elif isinstance(v, datetime.datetime): result[k] = jsonify_datetime(v) else: result[k] = v result = self._filter_none(result) else: result = [] for v in self: if isinstance(v, SerializableBase): result.append(v.as_version(version)) else: result.append(v) return result
[ "def", "as_version", "(", "self", ",", "version", "=", "Version", ".", "latest", ")", ":", "if", "not", "isinstance", "(", "self", ",", "list", ")", ":", "result", "=", "{", "}", "for", "k", ",", "v", "in", "self", ".", "iteritems", "(", ")", "if...
Returns a dict that has been modified based on versioning in order to be represented in JSON properly A class should overload as_version(self, version) implementation in order to tailor a more specific representation :param version: the relevant version. This allows for variance between versions :type version: str | unicode
[ "Returns", "a", "dict", "that", "has", "been", "modified", "based", "on", "versioning", "in", "order", "to", "be", "represented", "in", "JSON", "properly" ]
424eedaa6d19221efb1108edb915fc332abbb317
https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/serializable_base.py#L107-L148
27,601
RusticiSoftware/TinCanPython
tincan/serializable_base.py
SerializableBase._filter_none
def _filter_none(obj): """Filters out attributes set to None prior to serialization, and returns a new object without those attributes. This saves the serializer from sending empty bytes over the network. This method also fixes the keys to look as expected by ignoring a leading '_' if it is present. :param obj: the dictionary representation of an object that may have None attributes :type obj: dict """ result = {} for k, v in obj.iteritems(): if v is not None: if k.startswith('_'): k = k[1:] result[k] = v return result
python
def _filter_none(obj): result = {} for k, v in obj.iteritems(): if v is not None: if k.startswith('_'): k = k[1:] result[k] = v return result
[ "def", "_filter_none", "(", "obj", ")", ":", "result", "=", "{", "}", "for", "k", ",", "v", "in", "obj", ".", "iteritems", "(", ")", ":", "if", "v", "is", "not", "None", ":", "if", "k", ".", "startswith", "(", "'_'", ")", ":", "k", "=", "k", ...
Filters out attributes set to None prior to serialization, and returns a new object without those attributes. This saves the serializer from sending empty bytes over the network. This method also fixes the keys to look as expected by ignoring a leading '_' if it is present. :param obj: the dictionary representation of an object that may have None attributes :type obj: dict
[ "Filters", "out", "attributes", "set", "to", "None", "prior", "to", "serialization", "and", "returns", "a", "new", "object", "without", "those", "attributes", ".", "This", "saves", "the", "serializer", "from", "sending", "empty", "bytes", "over", "the", "netwo...
424eedaa6d19221efb1108edb915fc332abbb317
https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/serializable_base.py#L151-L169
27,602
RusticiSoftware/TinCanPython
tincan/conversions/iso8601.py
jsonify_timedelta
def jsonify_timedelta(value): """Converts a `datetime.timedelta` to an ISO 8601 duration string for JSON-ification. :param value: something to convert :type value: datetime.timedelta :return: the value after conversion :rtype unicode """ assert isinstance(value, datetime.timedelta) # split seconds to larger units seconds = value.total_seconds() minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) days, hours, minutes = map(int, (days, hours, minutes)) seconds = round(seconds, 6) # build date date = '' if days: date = '%sD' % days # build time time = u'T' # hours bigger_exists = date or hours if bigger_exists: time += '{:02}H'.format(hours) # minutes bigger_exists = bigger_exists or minutes if bigger_exists: time += '{:02}M'.format(minutes) # seconds if seconds.is_integer(): seconds = '{:02}'.format(int(seconds)) else: # 9 chars long w/leading 0, 6 digits after decimal seconds = '%09.6f' % seconds # remove trailing zeros seconds = seconds.rstrip('0') time += '{}S'.format(seconds) return u'P' + date + time
python
def jsonify_timedelta(value): assert isinstance(value, datetime.timedelta) # split seconds to larger units seconds = value.total_seconds() minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) days, hours, minutes = map(int, (days, hours, minutes)) seconds = round(seconds, 6) # build date date = '' if days: date = '%sD' % days # build time time = u'T' # hours bigger_exists = date or hours if bigger_exists: time += '{:02}H'.format(hours) # minutes bigger_exists = bigger_exists or minutes if bigger_exists: time += '{:02}M'.format(minutes) # seconds if seconds.is_integer(): seconds = '{:02}'.format(int(seconds)) else: # 9 chars long w/leading 0, 6 digits after decimal seconds = '%09.6f' % seconds # remove trailing zeros seconds = seconds.rstrip('0') time += '{}S'.format(seconds) return u'P' + date + time
[ "def", "jsonify_timedelta", "(", "value", ")", ":", "assert", "isinstance", "(", "value", ",", "datetime", ".", "timedelta", ")", "# split seconds to larger units", "seconds", "=", "value", ".", "total_seconds", "(", ")", "minutes", ",", "seconds", "=", "divmod"...
Converts a `datetime.timedelta` to an ISO 8601 duration string for JSON-ification. :param value: something to convert :type value: datetime.timedelta :return: the value after conversion :rtype unicode
[ "Converts", "a", "datetime", ".", "timedelta", "to", "an", "ISO", "8601", "duration", "string", "for", "JSON", "-", "ification", "." ]
424eedaa6d19221efb1108edb915fc332abbb317
https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/conversions/iso8601.py#L84-L135
27,603
globality-corp/microcosm
microcosm/config/validation.py
zip_dicts
def zip_dicts(left, right, prefix=()): """ Modified zip through two dictionaries. Iterate through all keys of left dictionary, returning: - A nested path - A value and parent for both dictionaries """ for key, left_value in left.items(): path = prefix + (key, ) right_value = right.get(key) if isinstance(left_value, dict): yield from zip_dicts(left_value, right_value or {}, path) else: yield path, left, left_value, right, right_value
python
def zip_dicts(left, right, prefix=()): for key, left_value in left.items(): path = prefix + (key, ) right_value = right.get(key) if isinstance(left_value, dict): yield from zip_dicts(left_value, right_value or {}, path) else: yield path, left, left_value, right, right_value
[ "def", "zip_dicts", "(", "left", ",", "right", ",", "prefix", "=", "(", ")", ")", ":", "for", "key", ",", "left_value", "in", "left", ".", "items", "(", ")", ":", "path", "=", "prefix", "+", "(", "key", ",", ")", "right_value", "=", "right", ".",...
Modified zip through two dictionaries. Iterate through all keys of left dictionary, returning: - A nested path - A value and parent for both dictionaries
[ "Modified", "zip", "through", "two", "dictionaries", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/config/validation.py#L35-L52
27,604
globality-corp/microcosm
microcosm/config/api.py
configure
def configure(defaults, metadata, loader): """ Build a fresh configuration. :params defaults: a nested dictionary of keys and their default values :params metadata: the graph metadata :params loader: a configuration loader """ config = Configuration(defaults) config.merge(loader(metadata)) validate(defaults, metadata, config) return config
python
def configure(defaults, metadata, loader): config = Configuration(defaults) config.merge(loader(metadata)) validate(defaults, metadata, config) return config
[ "def", "configure", "(", "defaults", ",", "metadata", ",", "loader", ")", ":", "config", "=", "Configuration", "(", "defaults", ")", "config", ".", "merge", "(", "loader", "(", "metadata", ")", ")", "validate", "(", "defaults", ",", "metadata", ",", "con...
Build a fresh configuration. :params defaults: a nested dictionary of keys and their default values :params metadata: the graph metadata :params loader: a configuration loader
[ "Build", "a", "fresh", "configuration", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/config/api.py#L9-L21
27,605
globality-corp/microcosm
microcosm/config/types.py
boolean
def boolean(value): """ Configuration-friendly boolean type converter. Supports both boolean-valued and string-valued inputs (e.g. from env vars). """ if isinstance(value, bool): return value if value == "": return False return strtobool(value)
python
def boolean(value): if isinstance(value, bool): return value if value == "": return False return strtobool(value)
[ "def", "boolean", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "bool", ")", ":", "return", "value", "if", "value", "==", "\"\"", ":", "return", "False", "return", "strtobool", "(", "value", ")" ]
Configuration-friendly boolean type converter. Supports both boolean-valued and string-valued inputs (e.g. from env vars).
[ "Configuration", "-", "friendly", "boolean", "type", "converter", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/config/types.py#L8-L21
27,606
globality-corp/microcosm
microcosm/loaders/environment.py
_load_from_environ
def _load_from_environ(metadata, value_func=None): """ Load configuration from environment variables. Any environment variable prefixed with the metadata's name will be used to recursively set dictionary keys, splitting on '__'. :param value_func: a mutator for the envvar's value (if any) """ # We'll match the ennvar name against the metadata's name. The ennvar # name must be uppercase and hyphens in names converted to underscores. # # | envar | name | matches? | # +-------------+---------+----------+ # | FOO_BAR | foo | yes | # | FOO_BAR | bar | no | # | foo_bar | bar | no | # | FOO_BAR_BAZ | foo_bar | yes | # | FOO_BAR_BAZ | foo-bar | yes | # +-------------+---------+----------+ prefix = metadata.name.upper().replace("-", "_") return expand_config( environ, separator="__", skip_to=1, key_parts_filter=lambda key_parts: len(key_parts) > 1 and key_parts[0] == prefix, value_func=lambda value: value_func(value) if value_func else value, )
python
def _load_from_environ(metadata, value_func=None): # We'll match the ennvar name against the metadata's name. The ennvar # name must be uppercase and hyphens in names converted to underscores. # # | envar | name | matches? | # +-------------+---------+----------+ # | FOO_BAR | foo | yes | # | FOO_BAR | bar | no | # | foo_bar | bar | no | # | FOO_BAR_BAZ | foo_bar | yes | # | FOO_BAR_BAZ | foo-bar | yes | # +-------------+---------+----------+ prefix = metadata.name.upper().replace("-", "_") return expand_config( environ, separator="__", skip_to=1, key_parts_filter=lambda key_parts: len(key_parts) > 1 and key_parts[0] == prefix, value_func=lambda value: value_func(value) if value_func else value, )
[ "def", "_load_from_environ", "(", "metadata", ",", "value_func", "=", "None", ")", ":", "# We'll match the ennvar name against the metadata's name. The ennvar", "# name must be uppercase and hyphens in names converted to underscores.", "#", "# | envar | name | matches? |", "# +-...
Load configuration from environment variables. Any environment variable prefixed with the metadata's name will be used to recursively set dictionary keys, splitting on '__'. :param value_func: a mutator for the envvar's value (if any)
[ "Load", "configuration", "from", "environment", "variables", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/loaders/environment.py#L13-L43
27,607
globality-corp/microcosm
microcosm/loaders/__init__.py
load_from_dict
def load_from_dict(dct=None, **kwargs): """ Load configuration from a dictionary. """ dct = dct or dict() dct.update(kwargs) def _load_from_dict(metadata): return dict(dct) return _load_from_dict
python
def load_from_dict(dct=None, **kwargs): dct = dct or dict() dct.update(kwargs) def _load_from_dict(metadata): return dict(dct) return _load_from_dict
[ "def", "load_from_dict", "(", "dct", "=", "None", ",", "*", "*", "kwargs", ")", ":", "dct", "=", "dct", "or", "dict", "(", ")", "dct", ".", "update", "(", "kwargs", ")", "def", "_load_from_dict", "(", "metadata", ")", ":", "return", "dict", "(", "d...
Load configuration from a dictionary.
[ "Load", "configuration", "from", "a", "dictionary", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/loaders/__init__.py#L26-L36
27,608
globality-corp/microcosm
microcosm/decorators.py
binding
def binding(key, registry=None): """ Creates a decorator that binds a factory function to a key. :param key: the binding key :param: registry: the registry to bind to; defaults to the global registry """ if registry is None: registry = _registry def decorator(func): registry.bind(key, func) return func return decorator
python
def binding(key, registry=None): if registry is None: registry = _registry def decorator(func): registry.bind(key, func) return func return decorator
[ "def", "binding", "(", "key", ",", "registry", "=", "None", ")", ":", "if", "registry", "is", "None", ":", "registry", "=", "_registry", "def", "decorator", "(", "func", ")", ":", "registry", ".", "bind", "(", "key", ",", "func", ")", "return", "func...
Creates a decorator that binds a factory function to a key. :param key: the binding key :param: registry: the registry to bind to; defaults to the global registry
[ "Creates", "a", "decorator", "that", "binds", "a", "factory", "function", "to", "a", "key", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/decorators.py#L9-L23
27,609
globality-corp/microcosm
microcosm/decorators.py
defaults
def defaults(**kwargs): """ Creates a decorator that saves the provided kwargs as defaults for a factory function. """ def decorator(func): setattr(func, DEFAULTS, kwargs) return func return decorator
python
def defaults(**kwargs): def decorator(func): setattr(func, DEFAULTS, kwargs) return func return decorator
[ "def", "defaults", "(", "*", "*", "kwargs", ")", ":", "def", "decorator", "(", "func", ")", ":", "setattr", "(", "func", ",", "DEFAULTS", ",", "kwargs", ")", "return", "func", "return", "decorator" ]
Creates a decorator that saves the provided kwargs as defaults for a factory function.
[ "Creates", "a", "decorator", "that", "saves", "the", "provided", "kwargs", "as", "defaults", "for", "a", "factory", "function", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/decorators.py#L26-L34
27,610
globality-corp/microcosm
microcosm/hooks.py
_invoke_hook
def _invoke_hook(hook_name, target): """ Generic hook invocation. """ try: for value in getattr(target, hook_name): func, args, kwargs = value func(target, *args, **kwargs) except AttributeError: # no hook defined pass except (TypeError, ValueError): # hook not properly defined (might be a mock) pass
python
def _invoke_hook(hook_name, target): try: for value in getattr(target, hook_name): func, args, kwargs = value func(target, *args, **kwargs) except AttributeError: # no hook defined pass except (TypeError, ValueError): # hook not properly defined (might be a mock) pass
[ "def", "_invoke_hook", "(", "hook_name", ",", "target", ")", ":", "try", ":", "for", "value", "in", "getattr", "(", "target", ",", "hook_name", ")", ":", "func", ",", "args", ",", "kwargs", "=", "value", "func", "(", "target", ",", "*", "args", ",", ...
Generic hook invocation.
[ "Generic", "hook", "invocation", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/hooks.py#L45-L59
27,611
globality-corp/microcosm
microcosm/hooks.py
_register_hook
def _register_hook(hook_name, target, func, *args, **kwargs): """ Generic hook registration. """ call = (func, args, kwargs) try: getattr(target, hook_name).append(call) except AttributeError: setattr(target, hook_name, [call])
python
def _register_hook(hook_name, target, func, *args, **kwargs): call = (func, args, kwargs) try: getattr(target, hook_name).append(call) except AttributeError: setattr(target, hook_name, [call])
[ "def", "_register_hook", "(", "hook_name", ",", "target", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "call", "=", "(", "func", ",", "args", ",", "kwargs", ")", "try", ":", "getattr", "(", "target", ",", "hook_name", ")", ".",...
Generic hook registration.
[ "Generic", "hook", "registration", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/hooks.py#L62-L71
27,612
globality-corp/microcosm
microcosm/hooks.py
on_resolve
def on_resolve(target, func, *args, **kwargs): """ Register a resolution hook. """ return _register_hook(ON_RESOLVE, target, func, *args, **kwargs)
python
def on_resolve(target, func, *args, **kwargs): return _register_hook(ON_RESOLVE, target, func, *args, **kwargs)
[ "def", "on_resolve", "(", "target", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_register_hook", "(", "ON_RESOLVE", ",", "target", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Register a resolution hook.
[ "Register", "a", "resolution", "hook", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/hooks.py#L82-L87
27,613
globality-corp/microcosm
microcosm/caching.py
create_cache
def create_cache(name): """ Create a cache by name. Defaults to `NaiveCache` """ caches = { subclass.name(): subclass for subclass in Cache.__subclasses__() } return caches.get(name, NaiveCache)()
python
def create_cache(name): caches = { subclass.name(): subclass for subclass in Cache.__subclasses__() } return caches.get(name, NaiveCache)()
[ "def", "create_cache", "(", "name", ")", ":", "caches", "=", "{", "subclass", ".", "name", "(", ")", ":", "subclass", "for", "subclass", "in", "Cache", ".", "__subclasses__", "(", ")", "}", "return", "caches", ".", "get", "(", "name", ",", "NaiveCache"...
Create a cache by name. Defaults to `NaiveCache`
[ "Create", "a", "cache", "by", "name", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/caching.py#L92-L103
27,614
globality-corp/microcosm
microcosm/loaders/settings.py
get_config_filename
def get_config_filename(metadata): """ Derive a configuration file name from the FOO_SETTINGS environment variable. """ envvar = "{}__SETTINGS".format(underscore(metadata.name).upper()) try: return environ[envvar] except KeyError: return None
python
def get_config_filename(metadata): envvar = "{}__SETTINGS".format(underscore(metadata.name).upper()) try: return environ[envvar] except KeyError: return None
[ "def", "get_config_filename", "(", "metadata", ")", ":", "envvar", "=", "\"{}__SETTINGS\"", ".", "format", "(", "underscore", "(", "metadata", ".", "name", ")", ".", "upper", "(", ")", ")", "try", ":", "return", "environ", "[", "envvar", "]", "except", "...
Derive a configuration file name from the FOO_SETTINGS environment variable.
[ "Derive", "a", "configuration", "file", "name", "from", "the", "FOO_SETTINGS", "environment", "variable", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/loaders/settings.py#L14-L24
27,615
globality-corp/microcosm
microcosm/loaders/settings.py
_load_from_file
def _load_from_file(metadata, load_func): """ Load configuration from a file. The file path is derived from an environment variable named after the service of the form FOO_SETTINGS. """ config_filename = get_config_filename(metadata) if config_filename is None: return dict() with open(config_filename, "r") as file_: data = load_func(file_.read()) return dict(data)
python
def _load_from_file(metadata, load_func): config_filename = get_config_filename(metadata) if config_filename is None: return dict() with open(config_filename, "r") as file_: data = load_func(file_.read()) return dict(data)
[ "def", "_load_from_file", "(", "metadata", ",", "load_func", ")", ":", "config_filename", "=", "get_config_filename", "(", "metadata", ")", "if", "config_filename", "is", "None", ":", "return", "dict", "(", ")", "with", "open", "(", "config_filename", ",", "\"...
Load configuration from a file. The file path is derived from an environment variable named after the service of the form FOO_SETTINGS.
[ "Load", "configuration", "from", "a", "file", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/loaders/settings.py#L27-L41
27,616
globality-corp/microcosm
microcosm/scoping/factories.py
ScopedFactory.get_scoped_config
def get_scoped_config(self, graph): """ Compute a configuration using the current scope. """ def loader(metadata): if not self.current_scope: target = graph.config else: target = graph.config.get(self.current_scope, {}) return { self.key: target.get(self.key, {}), } defaults = { self.key: get_defaults(self.func), } return configure(defaults, graph.metadata, loader)
python
def get_scoped_config(self, graph): def loader(metadata): if not self.current_scope: target = graph.config else: target = graph.config.get(self.current_scope, {}) return { self.key: target.get(self.key, {}), } defaults = { self.key: get_defaults(self.func), } return configure(defaults, graph.metadata, loader)
[ "def", "get_scoped_config", "(", "self", ",", "graph", ")", ":", "def", "loader", "(", "metadata", ")", ":", "if", "not", "self", ".", "current_scope", ":", "target", "=", "graph", ".", "config", "else", ":", "target", "=", "graph", ".", "config", ".",...
Compute a configuration using the current scope.
[ "Compute", "a", "configuration", "using", "the", "current", "scope", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/scoping/factories.py#L46-L63
27,617
globality-corp/microcosm
microcosm/scoping/factories.py
ScopedFactory.resolve
def resolve(self, graph): """ Resolve a scoped component, respecting the graph cache. """ cached = graph.get(self.scoped_key) if cached: return cached component = self.create(graph) graph.assign(self.scoped_key, component) return component
python
def resolve(self, graph): cached = graph.get(self.scoped_key) if cached: return cached component = self.create(graph) graph.assign(self.scoped_key, component) return component
[ "def", "resolve", "(", "self", ",", "graph", ")", ":", "cached", "=", "graph", ".", "get", "(", "self", ".", "scoped_key", ")", "if", "cached", ":", "return", "cached", "component", "=", "self", ".", "create", "(", "graph", ")", "graph", ".", "assign...
Resolve a scoped component, respecting the graph cache.
[ "Resolve", "a", "scoped", "component", "respecting", "the", "graph", "cache", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/scoping/factories.py#L73-L84
27,618
globality-corp/microcosm
microcosm/scoping/factories.py
ScopedFactory.create
def create(self, graph): """ Create a new scoped component. """ scoped_config = self.get_scoped_config(graph) scoped_graph = ScopedGraph(graph, scoped_config) return self.func(scoped_graph)
python
def create(self, graph): scoped_config = self.get_scoped_config(graph) scoped_graph = ScopedGraph(graph, scoped_config) return self.func(scoped_graph)
[ "def", "create", "(", "self", ",", "graph", ")", ":", "scoped_config", "=", "self", ".", "get_scoped_config", "(", "graph", ")", "scoped_graph", "=", "ScopedGraph", "(", "graph", ",", "scoped_config", ")", "return", "self", ".", "func", "(", "scoped_graph", ...
Create a new scoped component.
[ "Create", "a", "new", "scoped", "component", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/scoping/factories.py#L86-L93
27,619
globality-corp/microcosm
microcosm/scoping/factories.py
ScopedFactory.infect
def infect(cls, graph, key, default_scope=None): """ Forcibly convert an entry-point based factory to a ScopedFactory. Must be invoked before resolving the entry point. :raises AlreadyBoundError: for non entry-points; these should be declared with @scoped_binding """ func = graph.factory_for(key) if isinstance(func, cls): func = func.func factory = cls(key, func, default_scope) graph._registry.factories[key] = factory return factory
python
def infect(cls, graph, key, default_scope=None): func = graph.factory_for(key) if isinstance(func, cls): func = func.func factory = cls(key, func, default_scope) graph._registry.factories[key] = factory return factory
[ "def", "infect", "(", "cls", ",", "graph", ",", "key", ",", "default_scope", "=", "None", ")", ":", "func", "=", "graph", ".", "factory_for", "(", "key", ")", "if", "isinstance", "(", "func", ",", "cls", ")", ":", "func", "=", "func", ".", "func", ...
Forcibly convert an entry-point based factory to a ScopedFactory. Must be invoked before resolving the entry point. :raises AlreadyBoundError: for non entry-points; these should be declared with @scoped_binding
[ "Forcibly", "convert", "an", "entry", "-", "point", "based", "factory", "to", "a", "ScopedFactory", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/scoping/factories.py#L96-L110
27,620
globality-corp/microcosm
microcosm/loaders/compose.py
load_each
def load_each(*loaders): """ Loader factory that combines a series of loaders. """ def _load_each(metadata): return merge( loader(metadata) for loader in loaders ) return _load_each
python
def load_each(*loaders): def _load_each(metadata): return merge( loader(metadata) for loader in loaders ) return _load_each
[ "def", "load_each", "(", "*", "loaders", ")", ":", "def", "_load_each", "(", "metadata", ")", ":", "return", "merge", "(", "loader", "(", "metadata", ")", "for", "loader", "in", "loaders", ")", "return", "_load_each" ]
Loader factory that combines a series of loaders.
[ "Loader", "factory", "that", "combines", "a", "series", "of", "loaders", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/loaders/compose.py#L17-L27
27,621
globality-corp/microcosm
microcosm/registry.py
Registry.all
def all(self): """ Return a synthetic dictionary of all factories. """ return { key: value for key, value in chain(self.entry_points.items(), self.factories.items()) }
python
def all(self): return { key: value for key, value in chain(self.entry_points.items(), self.factories.items()) }
[ "def", "all", "(", "self", ")", ":", "return", "{", "key", ":", "value", "for", "key", ",", "value", "in", "chain", "(", "self", ".", "entry_points", ".", "items", "(", ")", ",", "self", ".", "factories", ".", "items", "(", ")", ")", "}" ]
Return a synthetic dictionary of all factories.
[ "Return", "a", "synthetic", "dictionary", "of", "all", "factories", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/registry.py#L43-L51
27,622
globality-corp/microcosm
microcosm/registry.py
Registry.defaults
def defaults(self): """ Return a nested dicionary of all registered factory defaults. """ return { key: get_defaults(value) for key, value in self.all.items() }
python
def defaults(self): return { key: get_defaults(value) for key, value in self.all.items() }
[ "def", "defaults", "(", "self", ")", ":", "return", "{", "key", ":", "get_defaults", "(", "value", ")", "for", "key", ",", "value", "in", "self", ".", "all", ".", "items", "(", ")", "}" ]
Return a nested dicionary of all registered factory defaults.
[ "Return", "a", "nested", "dicionary", "of", "all", "registered", "factory", "defaults", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/registry.py#L54-L62
27,623
globality-corp/microcosm
microcosm/registry.py
Registry.bind
def bind(self, key, factory): """ Bind a factory to a key. :raises AlreadyBoundError: if the key is alrady bound """ if key in self.factories: raise AlreadyBoundError(key) else: self.factories[key] = factory
python
def bind(self, key, factory): if key in self.factories: raise AlreadyBoundError(key) else: self.factories[key] = factory
[ "def", "bind", "(", "self", ",", "key", ",", "factory", ")", ":", "if", "key", "in", "self", ".", "factories", ":", "raise", "AlreadyBoundError", "(", "key", ")", "else", ":", "self", ".", "factories", "[", "key", "]", "=", "factory" ]
Bind a factory to a key. :raises AlreadyBoundError: if the key is alrady bound
[ "Bind", "a", "factory", "to", "a", "key", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/registry.py#L64-L74
27,624
globality-corp/microcosm
microcosm/registry.py
Registry.resolve
def resolve(self, key): """ Resolve a key to a factory. Attempts to resolve explicit bindings and entry points, preferring explicit bindings. :raises NotBoundError: if the key cannot be resolved """ try: return self._resolve_from_binding(key) except NotBoundError: return self._resolve_from_entry_point(key)
python
def resolve(self, key): try: return self._resolve_from_binding(key) except NotBoundError: return self._resolve_from_entry_point(key)
[ "def", "resolve", "(", "self", ",", "key", ")", ":", "try", ":", "return", "self", ".", "_resolve_from_binding", "(", "key", ")", "except", "NotBoundError", ":", "return", "self", ".", "_resolve_from_entry_point", "(", "key", ")" ]
Resolve a key to a factory. Attempts to resolve explicit bindings and entry points, preferring explicit bindings. :raises NotBoundError: if the key cannot be resolved
[ "Resolve", "a", "key", "to", "a", "factory", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/registry.py#L76-L89
27,625
globality-corp/microcosm
microcosm/loaders/keys.py
expand_config
def expand_config(dct, separator='.', skip_to=0, key_func=lambda key: key.lower(), key_parts_filter=lambda key_parts: True, value_func=lambda value: value): """ Expand a dictionary recursively by splitting keys along the separator. :param dct: a non-recursive dictionary :param separator: a separator charactor for splitting dictionary keys :param skip_to: index to start splitting keys on; can be used to skip over a key prefix :param key_func: a key mapping function :param key_parts_filter: a filter function for excluding keys :param value_func: a value mapping func """ config = {} for key, value in dct.items(): key_separator = separator(key) if callable(separator) else separator key_parts = key.split(key_separator) if not key_parts_filter(key_parts): continue key_config = config # skip prefix for key_part in key_parts[skip_to:-1]: key_config = key_config.setdefault(key_func(key_part), dict()) key_config[key_func(key_parts[-1])] = value_func(value) return config
python
def expand_config(dct, separator='.', skip_to=0, key_func=lambda key: key.lower(), key_parts_filter=lambda key_parts: True, value_func=lambda value: value): config = {} for key, value in dct.items(): key_separator = separator(key) if callable(separator) else separator key_parts = key.split(key_separator) if not key_parts_filter(key_parts): continue key_config = config # skip prefix for key_part in key_parts[skip_to:-1]: key_config = key_config.setdefault(key_func(key_part), dict()) key_config[key_func(key_parts[-1])] = value_func(value) return config
[ "def", "expand_config", "(", "dct", ",", "separator", "=", "'.'", ",", "skip_to", "=", "0", ",", "key_func", "=", "lambda", "key", ":", "key", ".", "lower", "(", ")", ",", "key_parts_filter", "=", "lambda", "key_parts", ":", "True", ",", "value_func", ...
Expand a dictionary recursively by splitting keys along the separator. :param dct: a non-recursive dictionary :param separator: a separator charactor for splitting dictionary keys :param skip_to: index to start splitting keys on; can be used to skip over a key prefix :param key_func: a key mapping function :param key_parts_filter: a filter function for excluding keys :param value_func: a value mapping func
[ "Expand", "a", "dictionary", "recursively", "by", "splitting", "keys", "along", "the", "separator", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/loaders/keys.py#L7-L37
27,626
globality-corp/microcosm
microcosm/object_graph.py
create_object_graph
def create_object_graph(name, debug=False, testing=False, import_name=None, root_path=None, loader=load_from_environ, registry=_registry, profiler=None, cache=None): """ Create a new object graph. :param name: the name of the microservice :param debug: is development debugging enabled? :param testing: is unit testing enabled? :param loader: the configuration loader to use :param registry: the registry to use (defaults to the global) """ metadata = Metadata( name=name, debug=debug, testing=testing, import_name=import_name, root_path=root_path, ) defaults = registry.defaults config = configure(defaults, metadata, loader) if profiler is None: profiler = NoopProfiler() if cache is None or isinstance(cache, str): cache = create_cache(cache) return ObjectGraph( metadata=metadata, config=config, registry=registry, profiler=profiler, cache=cache, loader=loader, )
python
def create_object_graph(name, debug=False, testing=False, import_name=None, root_path=None, loader=load_from_environ, registry=_registry, profiler=None, cache=None): metadata = Metadata( name=name, debug=debug, testing=testing, import_name=import_name, root_path=root_path, ) defaults = registry.defaults config = configure(defaults, metadata, loader) if profiler is None: profiler = NoopProfiler() if cache is None or isinstance(cache, str): cache = create_cache(cache) return ObjectGraph( metadata=metadata, config=config, registry=registry, profiler=profiler, cache=cache, loader=loader, )
[ "def", "create_object_graph", "(", "name", ",", "debug", "=", "False", ",", "testing", "=", "False", ",", "import_name", "=", "None", ",", "root_path", "=", "None", ",", "loader", "=", "load_from_environ", ",", "registry", "=", "_registry", ",", "profiler", ...
Create a new object graph. :param name: the name of the microservice :param debug: is development debugging enabled? :param testing: is unit testing enabled? :param loader: the configuration loader to use :param registry: the registry to use (defaults to the global)
[ "Create", "a", "new", "object", "graph", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/object_graph.py#L143-L186
27,627
globality-corp/microcosm
microcosm/object_graph.py
ObjectGraph._reserve
def _reserve(self, key): """ Reserve a component's binding temporarily. Protects against cycles. """ self.assign(key, RESERVED) try: yield finally: del self._cache[key]
python
def _reserve(self, key): self.assign(key, RESERVED) try: yield finally: del self._cache[key]
[ "def", "_reserve", "(", "self", ",", "key", ")", ":", "self", ".", "assign", "(", "key", ",", "RESERVED", ")", "try", ":", "yield", "finally", ":", "del", "self", ".", "_cache", "[", "key", "]" ]
Reserve a component's binding temporarily. Protects against cycles.
[ "Reserve", "a", "component", "s", "binding", "temporarily", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/object_graph.py#L111-L122
27,628
globality-corp/microcosm
microcosm/object_graph.py
ObjectGraph._resolve_key
def _resolve_key(self, key): """ Attempt to lazily create a component. :raises NotBoundError: if the component does not have a bound factory :raises CyclicGraphError: if the factory function requires a cycle :raises LockedGraphError: if the graph is locked """ with self._reserve(key): factory = self.factory_for(key) with self._profiler(key): component = factory(self) invoke_resolve_hook(component) return self.assign(key, component)
python
def _resolve_key(self, key): with self._reserve(key): factory = self.factory_for(key) with self._profiler(key): component = factory(self) invoke_resolve_hook(component) return self.assign(key, component)
[ "def", "_resolve_key", "(", "self", ",", "key", ")", ":", "with", "self", ".", "_reserve", "(", "key", ")", ":", "factory", "=", "self", ".", "factory_for", "(", "key", ")", "with", "self", ".", "_profiler", "(", "key", ")", ":", "component", "=", ...
Attempt to lazily create a component. :raises NotBoundError: if the component does not have a bound factory :raises CyclicGraphError: if the factory function requires a cycle :raises LockedGraphError: if the graph is locked
[ "Attempt", "to", "lazily", "create", "a", "component", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/object_graph.py#L124-L138
27,629
globality-corp/microcosm
microcosm/scoping/proxies.py
ScopedProxy.scoped_to
def scoped_to(self, scope): """ Context manager to switch scopes. """ previous_scope = self.__factory__.current_scope try: self.__factory__.current_scope = scope yield finally: self.__factory__.current_scope = previous_scope
python
def scoped_to(self, scope): previous_scope = self.__factory__.current_scope try: self.__factory__.current_scope = scope yield finally: self.__factory__.current_scope = previous_scope
[ "def", "scoped_to", "(", "self", ",", "scope", ")", ":", "previous_scope", "=", "self", ".", "__factory__", ".", "current_scope", "try", ":", "self", ".", "__factory__", ".", "current_scope", "=", "scope", "yield", "finally", ":", "self", ".", "__factory__",...
Context manager to switch scopes.
[ "Context", "manager", "to", "switch", "scopes", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/scoping/proxies.py#L62-L72
27,630
globality-corp/microcosm
microcosm/scoping/proxies.py
ScopedProxy.scoped
def scoped(self, func): """ Decorator to switch scopes. """ @wraps(func) def wrapper(*args, **kwargs): scope = kwargs.get("scope", self.__factory__.default_scope) with self.scoped_to(scope): return func(*args, **kwargs) return wrapper
python
def scoped(self, func): @wraps(func) def wrapper(*args, **kwargs): scope = kwargs.get("scope", self.__factory__.default_scope) with self.scoped_to(scope): return func(*args, **kwargs) return wrapper
[ "def", "scoped", "(", "self", ",", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "scope", "=", "kwargs", ".", "get", "(", "\"scope\"", ",", "self", ".", "__factory__", "."...
Decorator to switch scopes.
[ "Decorator", "to", "switch", "scopes", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/scoping/proxies.py#L74-L84
27,631
globality-corp/microcosm
microcosm/config/model.py
Configuration.merge
def merge(self, dct=None, **kwargs): """ Recursively merge a dictionary or kwargs into the current dict. """ if dct is None: dct = {} if kwargs: dct.update(**kwargs) for key, value in dct.items(): if all(( isinstance(value, dict), isinstance(self.get(key), Configuration), getattr(self.get(key), "__merge__", True), )): # recursively merge self[key].merge(value) elif isinstance(value, list) and isinstance(self.get(key), list): # append self[key] += value else: # set the new value self[key] = value
python
def merge(self, dct=None, **kwargs): if dct is None: dct = {} if kwargs: dct.update(**kwargs) for key, value in dct.items(): if all(( isinstance(value, dict), isinstance(self.get(key), Configuration), getattr(self.get(key), "__merge__", True), )): # recursively merge self[key].merge(value) elif isinstance(value, list) and isinstance(self.get(key), list): # append self[key] += value else: # set the new value self[key] = value
[ "def", "merge", "(", "self", ",", "dct", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "dct", "is", "None", ":", "dct", "=", "{", "}", "if", "kwargs", ":", "dct", ".", "update", "(", "*", "*", "kwargs", ")", "for", "key", ",", "value"...
Recursively merge a dictionary or kwargs into the current dict.
[ "Recursively", "merge", "a", "dictionary", "or", "kwargs", "into", "the", "current", "dict", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/config/model.py#L44-L67
27,632
globality-corp/microcosm
microcosm/config/model.py
Requirement.validate
def validate(self, metadata, path, value): """ Validate this requirement. """ if isinstance(value, Requirement): # if the RHS is still a Requirement object, it was not set if metadata.testing and self.mock_value is not None: value = self.mock_value elif self.default_value is not None: value = self.default_value elif not value.required: return None else: raise ValidationError(f"Missing required configuration for: {'.'.join(path)}") try: return self.type(value) except ValueError: raise ValidationError(f"Missing required configuration for: {'.'.join(path)}: {value}")
python
def validate(self, metadata, path, value): if isinstance(value, Requirement): # if the RHS is still a Requirement object, it was not set if metadata.testing and self.mock_value is not None: value = self.mock_value elif self.default_value is not None: value = self.default_value elif not value.required: return None else: raise ValidationError(f"Missing required configuration for: {'.'.join(path)}") try: return self.type(value) except ValueError: raise ValidationError(f"Missing required configuration for: {'.'.join(path)}: {value}")
[ "def", "validate", "(", "self", ",", "metadata", ",", "path", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "Requirement", ")", ":", "# if the RHS is still a Requirement object, it was not set", "if", "metadata", ".", "testing", "and", "self", "...
Validate this requirement.
[ "Validate", "this", "requirement", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/config/model.py#L88-L107
27,633
palantir/conjure-python-client
conjure_python_client/_serde/decoder.py
ConjureDecoder.decode_conjure_union_type
def decode_conjure_union_type(cls, obj, conjure_type): """Decodes json into a conjure union type. Args: obj: the json object to decode conjure_type: a class object which is the union type we're decoding into Returns: An instance of type conjure_type. """ type_of_union = obj["type"] # type: str for attr, conjure_field in conjure_type._options().items(): if conjure_field.identifier == type_of_union: attribute = attr conjure_field_definition = conjure_field break else: raise ValueError( "unknown union type {0} for {1}".format( type_of_union, conjure_type ) ) deserialized = {} # type: Dict[str, Any] if type_of_union not in obj or obj[type_of_union] is None: cls.check_null_field(obj, deserialized, conjure_field_definition) else: value = obj[type_of_union] field_type = conjure_field_definition.field_type deserialized[attribute] = cls.do_decode(value, field_type) return conjure_type(**deserialized)
python
def decode_conjure_union_type(cls, obj, conjure_type): type_of_union = obj["type"] # type: str for attr, conjure_field in conjure_type._options().items(): if conjure_field.identifier == type_of_union: attribute = attr conjure_field_definition = conjure_field break else: raise ValueError( "unknown union type {0} for {1}".format( type_of_union, conjure_type ) ) deserialized = {} # type: Dict[str, Any] if type_of_union not in obj or obj[type_of_union] is None: cls.check_null_field(obj, deserialized, conjure_field_definition) else: value = obj[type_of_union] field_type = conjure_field_definition.field_type deserialized[attribute] = cls.do_decode(value, field_type) return conjure_type(**deserialized)
[ "def", "decode_conjure_union_type", "(", "cls", ",", "obj", ",", "conjure_type", ")", ":", "type_of_union", "=", "obj", "[", "\"type\"", "]", "# type: str", "for", "attr", ",", "conjure_field", "in", "conjure_type", ".", "_options", "(", ")", ".", "items", "...
Decodes json into a conjure union type. Args: obj: the json object to decode conjure_type: a class object which is the union type we're decoding into Returns: An instance of type conjure_type.
[ "Decodes", "json", "into", "a", "conjure", "union", "type", "." ]
e6814a80bae3ec01fa147d5fd445538a677b1349
https://github.com/palantir/conjure-python-client/blob/e6814a80bae3ec01fa147d5fd445538a677b1349/conjure_python_client/_serde/decoder.py#L77-L107
27,634
palantir/conjure-python-client
conjure_python_client/_serde/decoder.py
ConjureDecoder.decode_conjure_enum_type
def decode_conjure_enum_type(cls, obj, conjure_type): """Decodes json into a conjure enum type. Args: obj: the json object to decode conjure_type: a class object which is the enum type we're decoding into. Returns: An instance of enum of type conjure_type. """ if not (isinstance(obj, str) or str(type(obj)) == "<type 'unicode'>"): raise Exception( 'Expected to find str type but found {} instead'.format( type(obj))) if obj in conjure_type.__members__: return conjure_type[obj] else: return conjure_type["UNKNOWN"]
python
def decode_conjure_enum_type(cls, obj, conjure_type): if not (isinstance(obj, str) or str(type(obj)) == "<type 'unicode'>"): raise Exception( 'Expected to find str type but found {} instead'.format( type(obj))) if obj in conjure_type.__members__: return conjure_type[obj] else: return conjure_type["UNKNOWN"]
[ "def", "decode_conjure_enum_type", "(", "cls", ",", "obj", ",", "conjure_type", ")", ":", "if", "not", "(", "isinstance", "(", "obj", ",", "str", ")", "or", "str", "(", "type", "(", "obj", ")", ")", "==", "\"<type 'unicode'>\"", ")", ":", "raise", "Exc...
Decodes json into a conjure enum type. Args: obj: the json object to decode conjure_type: a class object which is the enum type we're decoding into. Returns: An instance of enum of type conjure_type.
[ "Decodes", "json", "into", "a", "conjure", "enum", "type", "." ]
e6814a80bae3ec01fa147d5fd445538a677b1349
https://github.com/palantir/conjure-python-client/blob/e6814a80bae3ec01fa147d5fd445538a677b1349/conjure_python_client/_serde/decoder.py#L110-L129
27,635
palantir/conjure-python-client
conjure_python_client/_serde/decoder.py
ConjureDecoder.decode_list
def decode_list(cls, obj, element_type): # type: (List[Any], ConjureTypeType) -> List[Any] """Decodes json into a list, handling conversion of the elements. Args: obj: the json object to decode element_type: a class object which is the conjure type of the elements in this list. Returns: A python list where the elements are instances of type element_type. """ if not isinstance(obj, list): raise Exception("expected a python list") return list(map(lambda x: cls.do_decode(x, element_type), obj))
python
def decode_list(cls, obj, element_type): # type: (List[Any], ConjureTypeType) -> List[Any] if not isinstance(obj, list): raise Exception("expected a python list") return list(map(lambda x: cls.do_decode(x, element_type), obj))
[ "def", "decode_list", "(", "cls", ",", "obj", ",", "element_type", ")", ":", "# type: (List[Any], ConjureTypeType) -> List[Any]", "if", "not", "isinstance", "(", "obj", ",", "list", ")", ":", "raise", "Exception", "(", "\"expected a python list\"", ")", "return", ...
Decodes json into a list, handling conversion of the elements. Args: obj: the json object to decode element_type: a class object which is the conjure type of the elements in this list. Returns: A python list where the elements are instances of type element_type.
[ "Decodes", "json", "into", "a", "list", "handling", "conversion", "of", "the", "elements", "." ]
e6814a80bae3ec01fa147d5fd445538a677b1349
https://github.com/palantir/conjure-python-client/blob/e6814a80bae3ec01fa147d5fd445538a677b1349/conjure_python_client/_serde/decoder.py#L166-L181
27,636
palantir/conjure-python-client
conjure_python_client/_serde/decoder.py
ConjureDecoder.do_decode
def do_decode(cls, obj, obj_type): # type: (Any, ConjureTypeType) -> Any """Decodes json into the specified type Args: obj: the json object to decode element_type: a class object which is the type we're decoding into. """ if inspect.isclass(obj_type) and issubclass( # type: ignore obj_type, ConjureBeanType ): return cls.decode_conjure_bean_type(obj, obj_type) # type: ignore elif inspect.isclass(obj_type) and issubclass( # type: ignore obj_type, ConjureUnionType ): return cls.decode_conjure_union_type(obj, obj_type) elif inspect.isclass(obj_type) and issubclass( # type: ignore obj_type, ConjureEnumType ): return cls.decode_conjure_enum_type(obj, obj_type) elif isinstance(obj_type, DictType): return cls.decode_dict(obj, obj_type.key_type, obj_type.value_type) elif isinstance(obj_type, ListType): return cls.decode_list(obj, obj_type.item_type) elif isinstance(obj_type, OptionalType): return cls.decode_optional(obj, obj_type.item_type) return cls.decode_primitive(obj, obj_type)
python
def do_decode(cls, obj, obj_type): # type: (Any, ConjureTypeType) -> Any if inspect.isclass(obj_type) and issubclass( # type: ignore obj_type, ConjureBeanType ): return cls.decode_conjure_bean_type(obj, obj_type) # type: ignore elif inspect.isclass(obj_type) and issubclass( # type: ignore obj_type, ConjureUnionType ): return cls.decode_conjure_union_type(obj, obj_type) elif inspect.isclass(obj_type) and issubclass( # type: ignore obj_type, ConjureEnumType ): return cls.decode_conjure_enum_type(obj, obj_type) elif isinstance(obj_type, DictType): return cls.decode_dict(obj, obj_type.key_type, obj_type.value_type) elif isinstance(obj_type, ListType): return cls.decode_list(obj, obj_type.item_type) elif isinstance(obj_type, OptionalType): return cls.decode_optional(obj, obj_type.item_type) return cls.decode_primitive(obj, obj_type)
[ "def", "do_decode", "(", "cls", ",", "obj", ",", "obj_type", ")", ":", "# type: (Any, ConjureTypeType) -> Any", "if", "inspect", ".", "isclass", "(", "obj_type", ")", "and", "issubclass", "(", "# type: ignore", "obj_type", ",", "ConjureBeanType", ")", ":", "retu...
Decodes json into the specified type Args: obj: the json object to decode element_type: a class object which is the type we're decoding into.
[ "Decodes", "json", "into", "the", "specified", "type" ]
e6814a80bae3ec01fa147d5fd445538a677b1349
https://github.com/palantir/conjure-python-client/blob/e6814a80bae3ec01fa147d5fd445538a677b1349/conjure_python_client/_serde/decoder.py#L221-L253
27,637
palantir/conjure-python-client
conjure_python_client/_serde/encoder.py
ConjureEncoder.encode_conjure_bean_type
def encode_conjure_bean_type(cls, obj): # type: (ConjureBeanType) -> Any """Encodes a conjure bean into json""" encoded = {} # type: Dict[str, Any] for attribute_name, field_definition in obj._fields().items(): encoded[field_definition.identifier] = cls.do_encode( getattr(obj, attribute_name) ) return encoded
python
def encode_conjure_bean_type(cls, obj): # type: (ConjureBeanType) -> Any encoded = {} # type: Dict[str, Any] for attribute_name, field_definition in obj._fields().items(): encoded[field_definition.identifier] = cls.do_encode( getattr(obj, attribute_name) ) return encoded
[ "def", "encode_conjure_bean_type", "(", "cls", ",", "obj", ")", ":", "# type: (ConjureBeanType) -> Any", "encoded", "=", "{", "}", "# type: Dict[str, Any]", "for", "attribute_name", ",", "field_definition", "in", "obj", ".", "_fields", "(", ")", ".", "items", "(",...
Encodes a conjure bean into json
[ "Encodes", "a", "conjure", "bean", "into", "json" ]
e6814a80bae3ec01fa147d5fd445538a677b1349
https://github.com/palantir/conjure-python-client/blob/e6814a80bae3ec01fa147d5fd445538a677b1349/conjure_python_client/_serde/encoder.py#L25-L33
27,638
palantir/conjure-python-client
conjure_python_client/_serde/encoder.py
ConjureEncoder.encode_conjure_union_type
def encode_conjure_union_type(cls, obj): # type: (ConjureUnionType) -> Any """Encodes a conjure union into json""" encoded = {} # type: Dict[str, Any] encoded["type"] = obj.type for attr, field_definition in obj._options().items(): if field_definition.identifier == obj.type: attribute = attr break else: raise ValueError( "could not find attribute for union " + "member {0} of type {1}".format(obj.type, obj.__class__) ) defined_field_definition = obj._options()[attribute] encoded[defined_field_definition.identifier] = cls.do_encode( getattr(obj, attribute) ) return encoded
python
def encode_conjure_union_type(cls, obj): # type: (ConjureUnionType) -> Any encoded = {} # type: Dict[str, Any] encoded["type"] = obj.type for attr, field_definition in obj._options().items(): if field_definition.identifier == obj.type: attribute = attr break else: raise ValueError( "could not find attribute for union " + "member {0} of type {1}".format(obj.type, obj.__class__) ) defined_field_definition = obj._options()[attribute] encoded[defined_field_definition.identifier] = cls.do_encode( getattr(obj, attribute) ) return encoded
[ "def", "encode_conjure_union_type", "(", "cls", ",", "obj", ")", ":", "# type: (ConjureUnionType) -> Any", "encoded", "=", "{", "}", "# type: Dict[str, Any]", "encoded", "[", "\"type\"", "]", "=", "obj", ".", "type", "for", "attr", ",", "field_definition", "in", ...
Encodes a conjure union into json
[ "Encodes", "a", "conjure", "union", "into", "json" ]
e6814a80bae3ec01fa147d5fd445538a677b1349
https://github.com/palantir/conjure-python-client/blob/e6814a80bae3ec01fa147d5fd445538a677b1349/conjure_python_client/_serde/encoder.py#L36-L55
27,639
palantir/conjure-python-client
conjure_python_client/_serde/encoder.py
ConjureEncoder.do_encode
def do_encode(cls, obj): # type: (Any) -> Any """Encodes the passed object into json""" if isinstance(obj, ConjureBeanType): return cls.encode_conjure_bean_type(obj) elif isinstance(obj, ConjureUnionType): return cls.encode_conjure_union_type(obj) elif isinstance(obj, ConjureEnumType): return obj.value elif isinstance(obj, list): return list(map(cls.do_encode, obj)) elif isinstance(obj, dict): return {cls.do_encode(key): cls.do_encode(value) for key, value in obj.items()} else: return cls.encode_primitive(obj)
python
def do_encode(cls, obj): # type: (Any) -> Any if isinstance(obj, ConjureBeanType): return cls.encode_conjure_bean_type(obj) elif isinstance(obj, ConjureUnionType): return cls.encode_conjure_union_type(obj) elif isinstance(obj, ConjureEnumType): return obj.value elif isinstance(obj, list): return list(map(cls.do_encode, obj)) elif isinstance(obj, dict): return {cls.do_encode(key): cls.do_encode(value) for key, value in obj.items()} else: return cls.encode_primitive(obj)
[ "def", "do_encode", "(", "cls", ",", "obj", ")", ":", "# type: (Any) -> Any", "if", "isinstance", "(", "obj", ",", "ConjureBeanType", ")", ":", "return", "cls", ".", "encode_conjure_bean_type", "(", "obj", ")", "elif", "isinstance", "(", "obj", ",", "Conjure...
Encodes the passed object into json
[ "Encodes", "the", "passed", "object", "into", "json" ]
e6814a80bae3ec01fa147d5fd445538a677b1349
https://github.com/palantir/conjure-python-client/blob/e6814a80bae3ec01fa147d5fd445538a677b1349/conjure_python_client/_serde/encoder.py#L66-L86
27,640
leancloud/python-sdk
leancloud/geo_point.py
GeoPoint.radians_to
def radians_to(self, other): """ Returns the distance from this GeoPoint to another in radians. :param other: point the other GeoPoint :type other: GeoPoint :rtype: float """ d2r = math.pi / 180.0 lat1rad = self.latitude * d2r long1rad = self.longitude * d2r lat2rad = other.latitude * d2r long2rad = other.longitude * d2r delta_lat = lat1rad - lat2rad delta_long = long1rad - long2rad sin_delta_lat_div2 = math.sin(delta_lat / 2.0) sin_delta_long_div2 = math.sin(delta_long / 2.0) a = ((sin_delta_lat_div2 * sin_delta_lat_div2) + (math.cos(lat1rad) * math.cos(lat2rad) * sin_delta_long_div2 * sin_delta_long_div2)) a = min(1.0, a) return 2 * math.asin(math.sqrt(a))
python
def radians_to(self, other): d2r = math.pi / 180.0 lat1rad = self.latitude * d2r long1rad = self.longitude * d2r lat2rad = other.latitude * d2r long2rad = other.longitude * d2r delta_lat = lat1rad - lat2rad delta_long = long1rad - long2rad sin_delta_lat_div2 = math.sin(delta_lat / 2.0) sin_delta_long_div2 = math.sin(delta_long / 2.0) a = ((sin_delta_lat_div2 * sin_delta_lat_div2) + (math.cos(lat1rad) * math.cos(lat2rad) * sin_delta_long_div2 * sin_delta_long_div2)) a = min(1.0, a) return 2 * math.asin(math.sqrt(a))
[ "def", "radians_to", "(", "self", ",", "other", ")", ":", "d2r", "=", "math", ".", "pi", "/", "180.0", "lat1rad", "=", "self", ".", "latitude", "*", "d2r", "long1rad", "=", "self", ".", "longitude", "*", "d2r", "lat2rad", "=", "other", ".", "latitude...
Returns the distance from this GeoPoint to another in radians. :param other: point the other GeoPoint :type other: GeoPoint :rtype: float
[ "Returns", "the", "distance", "from", "this", "GeoPoint", "to", "another", "in", "radians", "." ]
fea3240257ce65e6a32c7312a5cee1f94a51a587
https://github.com/leancloud/python-sdk/blob/fea3240257ce65e6a32c7312a5cee1f94a51a587/leancloud/geo_point.py#L74-L99
27,641
pyblish/pyblish-lite
pyblish_lite/model.py
Abstract.append
def append(self, item): """Append item to end of model""" self.beginInsertRows(QtCore.QModelIndex(), self.rowCount(), self.rowCount()) self.items.append(item) self.endInsertRows()
python
def append(self, item): self.beginInsertRows(QtCore.QModelIndex(), self.rowCount(), self.rowCount()) self.items.append(item) self.endInsertRows()
[ "def", "append", "(", "self", ",", "item", ")", ":", "self", ".", "beginInsertRows", "(", "QtCore", ".", "QModelIndex", "(", ")", ",", "self", ".", "rowCount", "(", ")", ",", "self", ".", "rowCount", "(", ")", ")", "self", ".", "items", ".", "appen...
Append item to end of model
[ "Append", "item", "to", "end", "of", "model" ]
9172b81c7ae19a36e99c89dd16e102201992dc20
https://github.com/pyblish/pyblish-lite/blob/9172b81c7ae19a36e99c89dd16e102201992dc20/pyblish_lite/model.py#L101-L108
27,642
pyblish/pyblish-lite
pyblish_lite/window.py
Window.on_item_toggled
def on_item_toggled(self, index, state=None): """An item is requesting to be toggled""" if not index.data(model.IsIdle): return self.info("Cannot toggle") if not index.data(model.IsOptional): return self.info("This item is mandatory") if state is None: state = not index.data(model.IsChecked) index.model().setData(index, state, model.IsChecked) # Withdraw option to publish if no instances are toggled play = self.findChild(QtWidgets.QWidget, "Play") validate = self.findChild(QtWidgets.QWidget, "Validate") any_instances = any(index.data(model.IsChecked) for index in self.data["models"]["instances"]) play.setEnabled(any_instances) validate.setEnabled(any_instances) # Emit signals if index.data(model.Type) == "instance": instance = self.data["models"]["instances"].items[index.row()] util.defer( 100, lambda: self.controller.emit_( signal="instanceToggled", kwargs={"new_value": state, "old_value": not state, "instance": instance})) if index.data(model.Type) == "plugin": util.defer( 100, lambda: self.controller.emit_( signal="pluginToggled", kwargs={"new_value": state, "old_value": not state, "plugin": index.data(model.Object)}))
python
def on_item_toggled(self, index, state=None): if not index.data(model.IsIdle): return self.info("Cannot toggle") if not index.data(model.IsOptional): return self.info("This item is mandatory") if state is None: state = not index.data(model.IsChecked) index.model().setData(index, state, model.IsChecked) # Withdraw option to publish if no instances are toggled play = self.findChild(QtWidgets.QWidget, "Play") validate = self.findChild(QtWidgets.QWidget, "Validate") any_instances = any(index.data(model.IsChecked) for index in self.data["models"]["instances"]) play.setEnabled(any_instances) validate.setEnabled(any_instances) # Emit signals if index.data(model.Type) == "instance": instance = self.data["models"]["instances"].items[index.row()] util.defer( 100, lambda: self.controller.emit_( signal="instanceToggled", kwargs={"new_value": state, "old_value": not state, "instance": instance})) if index.data(model.Type) == "plugin": util.defer( 100, lambda: self.controller.emit_( signal="pluginToggled", kwargs={"new_value": state, "old_value": not state, "plugin": index.data(model.Object)}))
[ "def", "on_item_toggled", "(", "self", ",", "index", ",", "state", "=", "None", ")", ":", "if", "not", "index", ".", "data", "(", "model", ".", "IsIdle", ")", ":", "return", "self", ".", "info", "(", "\"Cannot toggle\"", ")", "if", "not", "index", "....
An item is requesting to be toggled
[ "An", "item", "is", "requesting", "to", "be", "toggled" ]
9172b81c7ae19a36e99c89dd16e102201992dc20
https://github.com/pyblish/pyblish-lite/blob/9172b81c7ae19a36e99c89dd16e102201992dc20/pyblish_lite/window.py#L622-L659
27,643
pyblish/pyblish-lite
pyblish_lite/window.py
Window.on_comment_entered
def on_comment_entered(self): """The user has typed a comment""" text_edit = self.findChild(QtWidgets.QWidget, "CommentBox") comment = text_edit.text() # Store within context context = self.controller.context context.data["comment"] = comment placeholder = self.findChild(QtWidgets.QLabel, "CommentPlaceholder") placeholder.setVisible(not comment)
python
def on_comment_entered(self): text_edit = self.findChild(QtWidgets.QWidget, "CommentBox") comment = text_edit.text() # Store within context context = self.controller.context context.data["comment"] = comment placeholder = self.findChild(QtWidgets.QLabel, "CommentPlaceholder") placeholder.setVisible(not comment)
[ "def", "on_comment_entered", "(", "self", ")", ":", "text_edit", "=", "self", ".", "findChild", "(", "QtWidgets", ".", "QWidget", ",", "\"CommentBox\"", ")", "comment", "=", "text_edit", ".", "text", "(", ")", "# Store within context", "context", "=", "self", ...
The user has typed a comment
[ "The", "user", "has", "typed", "a", "comment" ]
9172b81c7ae19a36e99c89dd16e102201992dc20
https://github.com/pyblish/pyblish-lite/blob/9172b81c7ae19a36e99c89dd16e102201992dc20/pyblish_lite/window.py#L697-L707
27,644
pyblish/pyblish-lite
pyblish_lite/window.py
Window.on_finished
def on_finished(self): """Finished signal handler""" self.controller.is_running = False error = self.controller.current_error if error is not None: self.info(self.tr("Stopped due to error(s), see Terminal.")) else: self.info(self.tr("Finished successfully!"))
python
def on_finished(self): self.controller.is_running = False error = self.controller.current_error if error is not None: self.info(self.tr("Stopped due to error(s), see Terminal.")) else: self.info(self.tr("Finished successfully!"))
[ "def", "on_finished", "(", "self", ")", ":", "self", ".", "controller", ".", "is_running", "=", "False", "error", "=", "self", ".", "controller", ".", "current_error", "if", "error", "is", "not", "None", ":", "self", ".", "info", "(", "self", ".", "tr"...
Finished signal handler
[ "Finished", "signal", "handler" ]
9172b81c7ae19a36e99c89dd16e102201992dc20
https://github.com/pyblish/pyblish-lite/blob/9172b81c7ae19a36e99c89dd16e102201992dc20/pyblish_lite/window.py#L871-L879
27,645
pyblish/pyblish-lite
pyblish_lite/window.py
Window.reset
def reset(self): """Prepare GUI for reset""" self.info(self.tr("About to reset..")) models = self.data["models"] models["instances"].store_checkstate() models["plugins"].store_checkstate() # Reset current ids to secure no previous instances get mixed in. models["instances"].ids = [] for m in models.values(): m.reset() for b in self.data["buttons"].values(): b.hide() comment_box = self.findChild(QtWidgets.QWidget, "CommentBox") comment_box.hide() util.defer(500, self.controller.reset)
python
def reset(self): self.info(self.tr("About to reset..")) models = self.data["models"] models["instances"].store_checkstate() models["plugins"].store_checkstate() # Reset current ids to secure no previous instances get mixed in. models["instances"].ids = [] for m in models.values(): m.reset() for b in self.data["buttons"].values(): b.hide() comment_box = self.findChild(QtWidgets.QWidget, "CommentBox") comment_box.hide() util.defer(500, self.controller.reset)
[ "def", "reset", "(", "self", ")", ":", "self", ".", "info", "(", "self", ".", "tr", "(", "\"About to reset..\"", ")", ")", "models", "=", "self", ".", "data", "[", "\"models\"", "]", "models", "[", "\"instances\"", "]", ".", "store_checkstate", "(", ")...
Prepare GUI for reset
[ "Prepare", "GUI", "for", "reset" ]
9172b81c7ae19a36e99c89dd16e102201992dc20
https://github.com/pyblish/pyblish-lite/blob/9172b81c7ae19a36e99c89dd16e102201992dc20/pyblish_lite/window.py#L887-L908
27,646
pyblish/pyblish-lite
pyblish_lite/window.py
Window.closeEvent
def closeEvent(self, event): """Perform post-flight checks before closing Make sure processing of any kind is wrapped up before closing """ # Make it snappy, but take care to clean it all up. # TODO(marcus): Enable GUI to return on problem, such # as asking whether or not the user really wants to quit # given there are things currently running. self.hide() if self.data["state"]["is_closing"]: # Explicitly clear potentially referenced data self.info(self.tr("Cleaning up models..")) for v in self.data["views"].values(): v.model().deleteLater() v.setModel(None) self.info(self.tr("Cleaning up terminal..")) for item in self.data["models"]["terminal"].items: del(item) self.info(self.tr("Cleaning up controller..")) self.controller.cleanup() self.info(self.tr("All clean!")) self.info(self.tr("Good bye")) return super(Window, self).closeEvent(event) self.info(self.tr("Closing..")) def on_problem(): self.heads_up("Warning", "Had trouble closing down. " "Please tell someone and try again.") self.show() if self.controller.is_running: self.info(self.tr("..as soon as processing is finished..")) self.controller.is_running = False self.finished.connect(self.close) util.defer(2000, on_problem) return event.ignore() self.data["state"]["is_closing"] = True util.defer(200, self.close) return event.ignore()
python
def closeEvent(self, event): # Make it snappy, but take care to clean it all up. # TODO(marcus): Enable GUI to return on problem, such # as asking whether or not the user really wants to quit # given there are things currently running. self.hide() if self.data["state"]["is_closing"]: # Explicitly clear potentially referenced data self.info(self.tr("Cleaning up models..")) for v in self.data["views"].values(): v.model().deleteLater() v.setModel(None) self.info(self.tr("Cleaning up terminal..")) for item in self.data["models"]["terminal"].items: del(item) self.info(self.tr("Cleaning up controller..")) self.controller.cleanup() self.info(self.tr("All clean!")) self.info(self.tr("Good bye")) return super(Window, self).closeEvent(event) self.info(self.tr("Closing..")) def on_problem(): self.heads_up("Warning", "Had trouble closing down. " "Please tell someone and try again.") self.show() if self.controller.is_running: self.info(self.tr("..as soon as processing is finished..")) self.controller.is_running = False self.finished.connect(self.close) util.defer(2000, on_problem) return event.ignore() self.data["state"]["is_closing"] = True util.defer(200, self.close) return event.ignore()
[ "def", "closeEvent", "(", "self", ",", "event", ")", ":", "# Make it snappy, but take care to clean it all up.", "# TODO(marcus): Enable GUI to return on problem, such", "# as asking whether or not the user really wants to quit", "# given there are things currently running.", "self", ".", ...
Perform post-flight checks before closing Make sure processing of any kind is wrapped up before closing
[ "Perform", "post", "-", "flight", "checks", "before", "closing" ]
9172b81c7ae19a36e99c89dd16e102201992dc20
https://github.com/pyblish/pyblish-lite/blob/9172b81c7ae19a36e99c89dd16e102201992dc20/pyblish_lite/window.py#L953-L1002
27,647
pyblish/pyblish-lite
pyblish_lite/window.py
Window.reject
def reject(self): """Handle ESC key""" if self.controller.is_running: self.info(self.tr("Stopping..")) self.controller.is_running = False
python
def reject(self): if self.controller.is_running: self.info(self.tr("Stopping..")) self.controller.is_running = False
[ "def", "reject", "(", "self", ")", ":", "if", "self", ".", "controller", ".", "is_running", ":", "self", ".", "info", "(", "self", ".", "tr", "(", "\"Stopping..\"", ")", ")", "self", ".", "controller", ".", "is_running", "=", "False" ]
Handle ESC key
[ "Handle", "ESC", "key" ]
9172b81c7ae19a36e99c89dd16e102201992dc20
https://github.com/pyblish/pyblish-lite/blob/9172b81c7ae19a36e99c89dd16e102201992dc20/pyblish_lite/window.py#L1004-L1009
27,648
pyblish/pyblish-lite
pyblish_lite/window.py
Window.info
def info(self, message): """Print user-facing information Arguments: message (str): Text message for the user """ info = self.findChild(QtWidgets.QLabel, "Info") info.setText(message) # Include message in terminal self.data["models"]["terminal"].append({ "label": message, "type": "info" }) animation = self.data["animation"]["display_info"] animation.stop() animation.start() # TODO(marcus): Should this be configurable? Do we want # the shell to fill up with these messages? util.u_print(message)
python
def info(self, message): info = self.findChild(QtWidgets.QLabel, "Info") info.setText(message) # Include message in terminal self.data["models"]["terminal"].append({ "label": message, "type": "info" }) animation = self.data["animation"]["display_info"] animation.stop() animation.start() # TODO(marcus): Should this be configurable? Do we want # the shell to fill up with these messages? util.u_print(message)
[ "def", "info", "(", "self", ",", "message", ")", ":", "info", "=", "self", ".", "findChild", "(", "QtWidgets", ".", "QLabel", ",", "\"Info\"", ")", "info", ".", "setText", "(", "message", ")", "# Include message in terminal", "self", ".", "data", "[", "\...
Print user-facing information Arguments: message (str): Text message for the user
[ "Print", "user", "-", "facing", "information" ]
9172b81c7ae19a36e99c89dd16e102201992dc20
https://github.com/pyblish/pyblish-lite/blob/9172b81c7ae19a36e99c89dd16e102201992dc20/pyblish_lite/window.py#L1017-L1040
27,649
pyblish/pyblish-lite
pyblish_lite/view.py
LogView.rowsInserted
def rowsInserted(self, parent, start, end): """Automatically scroll to bottom on each new item added Arguments: parent (QtCore.QModelIndex): The model itself, since this is a list start (int): Start index of item end (int): End index of item """ super(LogView, self).rowsInserted(parent, start, end) # IMPORTANT: This must be done *after* the superclass to get # an accurate value of the delegate's height. self.scrollToBottom()
python
def rowsInserted(self, parent, start, end): super(LogView, self).rowsInserted(parent, start, end) # IMPORTANT: This must be done *after* the superclass to get # an accurate value of the delegate's height. self.scrollToBottom()
[ "def", "rowsInserted", "(", "self", ",", "parent", ",", "start", ",", "end", ")", ":", "super", "(", "LogView", ",", "self", ")", ".", "rowsInserted", "(", "parent", ",", "start", ",", "end", ")", "# IMPORTANT: This must be done *after* the superclass to get", ...
Automatically scroll to bottom on each new item added Arguments: parent (QtCore.QModelIndex): The model itself, since this is a list start (int): Start index of item end (int): End index of item
[ "Automatically", "scroll", "to", "bottom", "on", "each", "new", "item", "added" ]
9172b81c7ae19a36e99c89dd16e102201992dc20
https://github.com/pyblish/pyblish-lite/blob/9172b81c7ae19a36e99c89dd16e102201992dc20/pyblish_lite/view.py#L90-L104
27,650
pyblish/pyblish-lite
pyblish_lite/control.py
Controller.reset
def reset(self): """Discover plug-ins and run collection""" self.context = pyblish.api.Context() self.plugins = pyblish.api.discover() self.was_discovered.emit() self.pair_generator = None self.current_pair = (None, None) self.current_error = None self.processing = { "nextOrder": None, "ordersWithError": set() } self._load() self._run(until=pyblish.api.CollectorOrder, on_finished=self.was_reset.emit)
python
def reset(self): self.context = pyblish.api.Context() self.plugins = pyblish.api.discover() self.was_discovered.emit() self.pair_generator = None self.current_pair = (None, None) self.current_error = None self.processing = { "nextOrder": None, "ordersWithError": set() } self._load() self._run(until=pyblish.api.CollectorOrder, on_finished=self.was_reset.emit)
[ "def", "reset", "(", "self", ")", ":", "self", ".", "context", "=", "pyblish", ".", "api", ".", "Context", "(", ")", "self", ".", "plugins", "=", "pyblish", ".", "api", ".", "discover", "(", ")", "self", ".", "was_discovered", ".", "emit", "(", ")"...
Discover plug-ins and run collection
[ "Discover", "plug", "-", "ins", "and", "run", "collection" ]
9172b81c7ae19a36e99c89dd16e102201992dc20
https://github.com/pyblish/pyblish-lite/blob/9172b81c7ae19a36e99c89dd16e102201992dc20/pyblish_lite/control.py#L61-L79
27,651
pyblish/pyblish-lite
pyblish_lite/control.py
Controller._load
def _load(self): """Initiate new generator and load first pair""" self.is_running = True self.pair_generator = self._iterator(self.plugins, self.context) self.current_pair = next(self.pair_generator, (None, None)) self.current_error = None self.is_running = False
python
def _load(self): self.is_running = True self.pair_generator = self._iterator(self.plugins, self.context) self.current_pair = next(self.pair_generator, (None, None)) self.current_error = None self.is_running = False
[ "def", "_load", "(", "self", ")", ":", "self", ".", "is_running", "=", "True", "self", ".", "pair_generator", "=", "self", ".", "_iterator", "(", "self", ".", "plugins", ",", "self", ".", "context", ")", "self", ".", "current_pair", "=", "next", "(", ...
Initiate new generator and load first pair
[ "Initiate", "new", "generator", "and", "load", "first", "pair" ]
9172b81c7ae19a36e99c89dd16e102201992dc20
https://github.com/pyblish/pyblish-lite/blob/9172b81c7ae19a36e99c89dd16e102201992dc20/pyblish_lite/control.py#L108-L115
27,652
pyblish/pyblish-lite
pyblish_lite/control.py
Controller._process
def _process(self, plugin, instance=None): """Produce `result` from `plugin` and `instance` :func:`process` shares state with :func:`_iterator` such that an instance/plugin pair can be fetched and processed in isolation. Arguments: plugin (pyblish.api.Plugin): Produce result using plug-in instance (optional, pyblish.api.Instance): Process this instance, if no instance is provided, context is processed. """ self.processing["nextOrder"] = plugin.order try: result = pyblish.plugin.process(plugin, self.context, instance) except Exception as e: raise Exception("Unknown error: %s" % e) else: # Make note of the order at which the # potential error error occured. has_error = result["error"] is not None if has_error: self.processing["ordersWithError"].add(plugin.order) return result
python
def _process(self, plugin, instance=None): self.processing["nextOrder"] = plugin.order try: result = pyblish.plugin.process(plugin, self.context, instance) except Exception as e: raise Exception("Unknown error: %s" % e) else: # Make note of the order at which the # potential error error occured. has_error = result["error"] is not None if has_error: self.processing["ordersWithError"].add(plugin.order) return result
[ "def", "_process", "(", "self", ",", "plugin", ",", "instance", "=", "None", ")", ":", "self", ".", "processing", "[", "\"nextOrder\"", "]", "=", "plugin", ".", "order", "try", ":", "result", "=", "pyblish", ".", "plugin", ".", "process", "(", "plugin"...
Produce `result` from `plugin` and `instance` :func:`process` shares state with :func:`_iterator` such that an instance/plugin pair can be fetched and processed in isolation. Arguments: plugin (pyblish.api.Plugin): Produce result using plug-in instance (optional, pyblish.api.Instance): Process this instance, if no instance is provided, context is processed.
[ "Produce", "result", "from", "plugin", "and", "instance" ]
9172b81c7ae19a36e99c89dd16e102201992dc20
https://github.com/pyblish/pyblish-lite/blob/9172b81c7ae19a36e99c89dd16e102201992dc20/pyblish_lite/control.py#L117-L145
27,653
pyblish/pyblish-lite
pyblish_lite/control.py
Controller._run
def _run(self, until=float("inf"), on_finished=lambda: None): """Process current pair and store next pair for next process Arguments: until (pyblish.api.Order, optional): Keep fetching next() until this order, default value is infinity. on_finished (callable, optional): What to do when finishing, defaults to doing nothing. """ def on_next(): if self.current_pair == (None, None): return util.defer(100, on_finished_) # The magic number 0.5 is the range between # the various CVEI processing stages; # e.g. # - Collection is 0 +- 0.5 (-0.5 - 0.5) # - Validation is 1 +- 0.5 (0.5 - 1.5) # # TODO(marcus): Make this less magical # order = self.current_pair[0].order if order > (until + 0.5): return util.defer(100, on_finished_) self.about_to_process.emit(*self.current_pair) util.defer(10, on_process) def on_process(): try: result = self._process(*self.current_pair) if result["error"] is not None: self.current_error = result["error"] self.was_processed.emit(result) except Exception as e: stack = traceback.format_exc(e) return util.defer( 500, lambda: on_unexpected_error(error=stack)) # Now that processing has completed, and context potentially # modified with new instances, produce the next pair. # # IMPORTANT: This *must* be done *after* processing of # the current pair, otherwise data generated at that point # will *not* be included. try: self.current_pair = next(self.pair_generator) except StopIteration: # All pairs were processed successfully! self.current_pair = (None, None) return util.defer(500, on_finished_) except Exception as e: # This is a bug stack = traceback.format_exc(e) self.current_pair = (None, None) return util.defer( 500, lambda: on_unexpected_error(error=stack)) util.defer(10, on_next) def on_unexpected_error(error): util.u_print(u"An unexpected error occurred:\n %s" % error) return util.defer(500, on_finished_) def on_finished_(): on_finished() self.was_finished.emit() self.is_running = True util.defer(10, on_next)
python
def _run(self, until=float("inf"), on_finished=lambda: None): def on_next(): if self.current_pair == (None, None): return util.defer(100, on_finished_) # The magic number 0.5 is the range between # the various CVEI processing stages; # e.g. # - Collection is 0 +- 0.5 (-0.5 - 0.5) # - Validation is 1 +- 0.5 (0.5 - 1.5) # # TODO(marcus): Make this less magical # order = self.current_pair[0].order if order > (until + 0.5): return util.defer(100, on_finished_) self.about_to_process.emit(*self.current_pair) util.defer(10, on_process) def on_process(): try: result = self._process(*self.current_pair) if result["error"] is not None: self.current_error = result["error"] self.was_processed.emit(result) except Exception as e: stack = traceback.format_exc(e) return util.defer( 500, lambda: on_unexpected_error(error=stack)) # Now that processing has completed, and context potentially # modified with new instances, produce the next pair. # # IMPORTANT: This *must* be done *after* processing of # the current pair, otherwise data generated at that point # will *not* be included. try: self.current_pair = next(self.pair_generator) except StopIteration: # All pairs were processed successfully! self.current_pair = (None, None) return util.defer(500, on_finished_) except Exception as e: # This is a bug stack = traceback.format_exc(e) self.current_pair = (None, None) return util.defer( 500, lambda: on_unexpected_error(error=stack)) util.defer(10, on_next) def on_unexpected_error(error): util.u_print(u"An unexpected error occurred:\n %s" % error) return util.defer(500, on_finished_) def on_finished_(): on_finished() self.was_finished.emit() self.is_running = True util.defer(10, on_next)
[ "def", "_run", "(", "self", ",", "until", "=", "float", "(", "\"inf\"", ")", ",", "on_finished", "=", "lambda", ":", "None", ")", ":", "def", "on_next", "(", ")", ":", "if", "self", ".", "current_pair", "==", "(", "None", ",", "None", ")", ":", "...
Process current pair and store next pair for next process Arguments: until (pyblish.api.Order, optional): Keep fetching next() until this order, default value is infinity. on_finished (callable, optional): What to do when finishing, defaults to doing nothing.
[ "Process", "current", "pair", "and", "store", "next", "pair", "for", "next", "process" ]
9172b81c7ae19a36e99c89dd16e102201992dc20
https://github.com/pyblish/pyblish-lite/blob/9172b81c7ae19a36e99c89dd16e102201992dc20/pyblish_lite/control.py#L147-L224
27,654
pyblish/pyblish-lite
pyblish_lite/control.py
Controller._iterator
def _iterator(self, plugins, context): """Yield next plug-in and instance to process. Arguments: plugins (list): Plug-ins to process context (pyblish.api.Context): Context to process """ test = pyblish.logic.registered_test() for plug, instance in pyblish.logic.Iterator(plugins, context): if not plug.active: continue if instance is not None and instance.data.get("publish") is False: continue self.processing["nextOrder"] = plug.order if not self.is_running: raise StopIteration("Stopped") if test(**self.processing): raise StopIteration("Stopped due to %s" % test( **self.processing)) yield plug, instance
python
def _iterator(self, plugins, context): test = pyblish.logic.registered_test() for plug, instance in pyblish.logic.Iterator(plugins, context): if not plug.active: continue if instance is not None and instance.data.get("publish") is False: continue self.processing["nextOrder"] = plug.order if not self.is_running: raise StopIteration("Stopped") if test(**self.processing): raise StopIteration("Stopped due to %s" % test( **self.processing)) yield plug, instance
[ "def", "_iterator", "(", "self", ",", "plugins", ",", "context", ")", ":", "test", "=", "pyblish", ".", "logic", ".", "registered_test", "(", ")", "for", "plug", ",", "instance", "in", "pyblish", ".", "logic", ".", "Iterator", "(", "plugins", ",", "con...
Yield next plug-in and instance to process. Arguments: plugins (list): Plug-ins to process context (pyblish.api.Context): Context to process
[ "Yield", "next", "plug", "-", "in", "and", "instance", "to", "process", "." ]
9172b81c7ae19a36e99c89dd16e102201992dc20
https://github.com/pyblish/pyblish-lite/blob/9172b81c7ae19a36e99c89dd16e102201992dc20/pyblish_lite/control.py#L226-L253
27,655
pyblish/pyblish-lite
pyblish_lite/control.py
Controller.cleanup
def cleanup(self): """Forcefully delete objects from memory In an ideal world, this shouldn't be necessary. Garbage collection guarantees that anything without reference is automatically removed. However, because this application is designed to be run multiple times from the same interpreter process, extra case must be taken to ensure there are no memory leaks. Explicitly deleting objects shines a light on where objects may still be referenced in the form of an error. No errors means this was uneccesary, but that's ok. """ for instance in self.context: del(instance) for plugin in self.plugins: del(plugin)
python
def cleanup(self): for instance in self.context: del(instance) for plugin in self.plugins: del(plugin)
[ "def", "cleanup", "(", "self", ")", ":", "for", "instance", "in", "self", ".", "context", ":", "del", "(", "instance", ")", "for", "plugin", "in", "self", ".", "plugins", ":", "del", "(", "plugin", ")" ]
Forcefully delete objects from memory In an ideal world, this shouldn't be necessary. Garbage collection guarantees that anything without reference is automatically removed. However, because this application is designed to be run multiple times from the same interpreter process, extra case must be taken to ensure there are no memory leaks. Explicitly deleting objects shines a light on where objects may still be referenced in the form of an error. No errors means this was uneccesary, but that's ok.
[ "Forcefully", "delete", "objects", "from", "memory" ]
9172b81c7ae19a36e99c89dd16e102201992dc20
https://github.com/pyblish/pyblish-lite/blob/9172b81c7ae19a36e99c89dd16e102201992dc20/pyblish_lite/control.py#L255-L276
27,656
adamalton/django-csp-reports
cspreports/summary.py
get_root_uri
def get_root_uri(uri): """Return root URI - strip query and fragment.""" chunks = urlsplit(uri) return urlunsplit((chunks.scheme, chunks.netloc, chunks.path, '', ''))
python
def get_root_uri(uri): chunks = urlsplit(uri) return urlunsplit((chunks.scheme, chunks.netloc, chunks.path, '', ''))
[ "def", "get_root_uri", "(", "uri", ")", ":", "chunks", "=", "urlsplit", "(", "uri", ")", "return", "urlunsplit", "(", "(", "chunks", ".", "scheme", ",", "chunks", ".", "netloc", ",", "chunks", ".", "path", ",", "''", ",", "''", ")", ")" ]
Return root URI - strip query and fragment.
[ "Return", "root", "URI", "-", "strip", "query", "and", "fragment", "." ]
867992c6f535cf6afbf911f92af7eea4c61e4b73
https://github.com/adamalton/django-csp-reports/blob/867992c6f535cf6afbf911f92af7eea4c61e4b73/cspreports/summary.py#L14-L17
27,657
adamalton/django-csp-reports
cspreports/summary.py
collect
def collect(since, to, top=DEFAULT_TOP): """Collect the CSP report. @returntype: CspReportSummary """ summary = CspReportSummary(since, to, top=top) queryset = CSPReport.objects.filter(created__range=(since, to)) valid_queryset = queryset.filter(is_valid=True) invalid_queryset = queryset.filter(is_valid=False) summary.total_count = queryset.count() summary.valid_count = valid_queryset.count() # Collect sources sources = {} for report in valid_queryset: root_uri = get_root_uri(report.document_uri) info = sources.setdefault(root_uri, ViolationInfo(root_uri)) info.append(report) summary.sources = sorted(sources.values(), key=attrgetter('count'), reverse=True)[:top] # Collect blocks blocks = {} for report in valid_queryset: root_uri = get_root_uri(report.blocked_uri) info = blocks.setdefault(root_uri, ViolationInfo(root_uri)) info.append(report) summary.blocks = sorted(blocks.values(), key=attrgetter('count'), reverse=True)[:top] # Collect invalid reports summary.invalid_count = invalid_queryset.count() summary.invalid_reports = tuple(invalid_queryset[:top]) return summary
python
def collect(since, to, top=DEFAULT_TOP): summary = CspReportSummary(since, to, top=top) queryset = CSPReport.objects.filter(created__range=(since, to)) valid_queryset = queryset.filter(is_valid=True) invalid_queryset = queryset.filter(is_valid=False) summary.total_count = queryset.count() summary.valid_count = valid_queryset.count() # Collect sources sources = {} for report in valid_queryset: root_uri = get_root_uri(report.document_uri) info = sources.setdefault(root_uri, ViolationInfo(root_uri)) info.append(report) summary.sources = sorted(sources.values(), key=attrgetter('count'), reverse=True)[:top] # Collect blocks blocks = {} for report in valid_queryset: root_uri = get_root_uri(report.blocked_uri) info = blocks.setdefault(root_uri, ViolationInfo(root_uri)) info.append(report) summary.blocks = sorted(blocks.values(), key=attrgetter('count'), reverse=True)[:top] # Collect invalid reports summary.invalid_count = invalid_queryset.count() summary.invalid_reports = tuple(invalid_queryset[:top]) return summary
[ "def", "collect", "(", "since", ",", "to", ",", "top", "=", "DEFAULT_TOP", ")", ":", "summary", "=", "CspReportSummary", "(", "since", ",", "to", ",", "top", "=", "top", ")", "queryset", "=", "CSPReport", ".", "objects", ".", "filter", "(", "created__r...
Collect the CSP report. @returntype: CspReportSummary
[ "Collect", "the", "CSP", "report", "." ]
867992c6f535cf6afbf911f92af7eea4c61e4b73
https://github.com/adamalton/django-csp-reports/blob/867992c6f535cf6afbf911f92af7eea4c61e4b73/cspreports/summary.py#L124-L157
27,658
adamalton/django-csp-reports
cspreports/summary.py
ViolationInfo.append
def append(self, report): """Append a new CSP report.""" assert report not in self.examples self.count += 1 if len(self.examples) < self.top: self.examples.append(report)
python
def append(self, report): assert report not in self.examples self.count += 1 if len(self.examples) < self.top: self.examples.append(report)
[ "def", "append", "(", "self", ",", "report", ")", ":", "assert", "report", "not", "in", "self", ".", "examples", "self", ".", "count", "+=", "1", "if", "len", "(", "self", ".", "examples", ")", "<", "self", ".", "top", ":", "self", ".", "examples",...
Append a new CSP report.
[ "Append", "a", "new", "CSP", "report", "." ]
867992c6f535cf6afbf911f92af7eea4c61e4b73
https://github.com/adamalton/django-csp-reports/blob/867992c6f535cf6afbf911f92af7eea4c61e4b73/cspreports/summary.py#L35-L40
27,659
adamalton/django-csp-reports
cspreports/summary.py
CspReportSummary.render
def render(self): """Render the summary.""" engine = Engine() return engine.from_string(SUMMARY_TEMPLATE).render(Context(self.__dict__))
python
def render(self): engine = Engine() return engine.from_string(SUMMARY_TEMPLATE).render(Context(self.__dict__))
[ "def", "render", "(", "self", ")", ":", "engine", "=", "Engine", "(", ")", "return", "engine", ".", "from_string", "(", "SUMMARY_TEMPLATE", ")", ".", "render", "(", "Context", "(", "self", ".", "__dict__", ")", ")" ]
Render the summary.
[ "Render", "the", "summary", "." ]
867992c6f535cf6afbf911f92af7eea4c61e4b73
https://github.com/adamalton/django-csp-reports/blob/867992c6f535cf6afbf911f92af7eea4c61e4b73/cspreports/summary.py#L118-L121
27,660
adamalton/django-csp-reports
cspreports/management/commands/make_csp_summary.py
_parse_date_input
def _parse_date_input(date_input, default_offset=0): """Parses a date input.""" if date_input: try: return parse_date_input(date_input) except ValueError as err: raise CommandError(force_text(err)) else: return get_midnight() - timedelta(days=default_offset)
python
def _parse_date_input(date_input, default_offset=0): if date_input: try: return parse_date_input(date_input) except ValueError as err: raise CommandError(force_text(err)) else: return get_midnight() - timedelta(days=default_offset)
[ "def", "_parse_date_input", "(", "date_input", ",", "default_offset", "=", "0", ")", ":", "if", "date_input", ":", "try", ":", "return", "parse_date_input", "(", "date_input", ")", "except", "ValueError", "as", "err", ":", "raise", "CommandError", "(", "force_...
Parses a date input.
[ "Parses", "a", "date", "input", "." ]
867992c6f535cf6afbf911f92af7eea4c61e4b73
https://github.com/adamalton/django-csp-reports/blob/867992c6f535cf6afbf911f92af7eea4c61e4b73/cspreports/management/commands/make_csp_summary.py#L13-L21
27,661
adamalton/django-csp-reports
cspreports/models.py
CSPReport.nice_report
def nice_report(self): """Return a nicely formatted original report.""" if not self.json: return '[no CSP report data]' try: data = json.loads(self.json) except ValueError: return "Invalid CSP report: '{}'".format(self.json) if 'csp-report' not in data: return 'Invalid CSP report: ' + json.dumps(data, indent=4, sort_keys=True, separators=(',', ': ')) return json.dumps(data['csp-report'], indent=4, sort_keys=True, separators=(',', ': '))
python
def nice_report(self): if not self.json: return '[no CSP report data]' try: data = json.loads(self.json) except ValueError: return "Invalid CSP report: '{}'".format(self.json) if 'csp-report' not in data: return 'Invalid CSP report: ' + json.dumps(data, indent=4, sort_keys=True, separators=(',', ': ')) return json.dumps(data['csp-report'], indent=4, sort_keys=True, separators=(',', ': '))
[ "def", "nice_report", "(", "self", ")", ":", "if", "not", "self", ".", "json", ":", "return", "'[no CSP report data]'", "try", ":", "data", "=", "json", ".", "loads", "(", "self", ".", "json", ")", "except", "ValueError", ":", "return", "\"Invalid CSP repo...
Return a nicely formatted original report.
[ "Return", "a", "nicely", "formatted", "original", "report", "." ]
867992c6f535cf6afbf911f92af7eea4c61e4b73
https://github.com/adamalton/django-csp-reports/blob/867992c6f535cf6afbf911f92af7eea4c61e4b73/cspreports/models.py#L87-L97
27,662
adamalton/django-csp-reports
cspreports/models.py
CSPReport.from_message
def from_message(cls, message): """Creates an instance from CSP report message. If the message is not valid, the result will still have as much fields set as possible. @param message: JSON encoded CSP report. @type message: text """ self = cls(json=message) try: decoded_data = json.loads(message) except ValueError: # Message is not a valid JSON. Return as invalid. return self try: report_data = decoded_data['csp-report'] except KeyError: # Message is not a valid CSP report. Return as invalid. return self # Extract individual fields for report_name, field_name in REQUIRED_FIELD_MAP + OPTIONAL_FIELD_MAP: setattr(self, field_name, report_data.get(report_name)) # Extract integer fields for report_name, field_name in INTEGER_FIELD_MAP: value = report_data.get(report_name) field = self._meta.get_field(field_name) min_value, max_value = connection.ops.integer_field_range(field.get_internal_type()) if min_value is None: min_value = 0 # All these fields are possitive. Value can't be negative. min_value = max(min_value, 0) if value is not None and min_value <= value and (max_value is None or value <= max_value): setattr(self, field_name, value) # Extract disposition disposition = report_data.get('disposition') if disposition in dict(DISPOSITIONS).keys(): self.disposition = disposition # Check if report is valid is_valid = True for field_name in dict(REQUIRED_FIELD_MAP).values(): if getattr(self, field_name) is None: is_valid = False break self.is_valid = is_valid return self
python
def from_message(cls, message): self = cls(json=message) try: decoded_data = json.loads(message) except ValueError: # Message is not a valid JSON. Return as invalid. return self try: report_data = decoded_data['csp-report'] except KeyError: # Message is not a valid CSP report. Return as invalid. return self # Extract individual fields for report_name, field_name in REQUIRED_FIELD_MAP + OPTIONAL_FIELD_MAP: setattr(self, field_name, report_data.get(report_name)) # Extract integer fields for report_name, field_name in INTEGER_FIELD_MAP: value = report_data.get(report_name) field = self._meta.get_field(field_name) min_value, max_value = connection.ops.integer_field_range(field.get_internal_type()) if min_value is None: min_value = 0 # All these fields are possitive. Value can't be negative. min_value = max(min_value, 0) if value is not None and min_value <= value and (max_value is None or value <= max_value): setattr(self, field_name, value) # Extract disposition disposition = report_data.get('disposition') if disposition in dict(DISPOSITIONS).keys(): self.disposition = disposition # Check if report is valid is_valid = True for field_name in dict(REQUIRED_FIELD_MAP).values(): if getattr(self, field_name) is None: is_valid = False break self.is_valid = is_valid return self
[ "def", "from_message", "(", "cls", ",", "message", ")", ":", "self", "=", "cls", "(", "json", "=", "message", ")", "try", ":", "decoded_data", "=", "json", ".", "loads", "(", "message", ")", "except", "ValueError", ":", "# Message is not a valid JSON. Return...
Creates an instance from CSP report message. If the message is not valid, the result will still have as much fields set as possible. @param message: JSON encoded CSP report. @type message: text
[ "Creates", "an", "instance", "from", "CSP", "report", "message", "." ]
867992c6f535cf6afbf911f92af7eea4c61e4b73
https://github.com/adamalton/django-csp-reports/blob/867992c6f535cf6afbf911f92af7eea4c61e4b73/cspreports/models.py#L103-L150
27,663
adamalton/django-csp-reports
cspreports/models.py
CSPReport.data
def data(self): """ Returns self.json loaded as a python object. """ try: data = self._data except AttributeError: data = self._data = json.loads(self.json) return data
python
def data(self): try: data = self._data except AttributeError: data = self._data = json.loads(self.json) return data
[ "def", "data", "(", "self", ")", ":", "try", ":", "data", "=", "self", ".", "_data", "except", "AttributeError", ":", "data", "=", "self", ".", "_data", "=", "json", ".", "loads", "(", "self", ".", "json", ")", "return", "data" ]
Returns self.json loaded as a python object.
[ "Returns", "self", ".", "json", "loaded", "as", "a", "python", "object", "." ]
867992c6f535cf6afbf911f92af7eea4c61e4b73
https://github.com/adamalton/django-csp-reports/blob/867992c6f535cf6afbf911f92af7eea4c61e4b73/cspreports/models.py#L153-L159
27,664
adamalton/django-csp-reports
cspreports/models.py
CSPReport.json_as_html
def json_as_html(self): """ Print out self.json in a nice way. """ # To avoid circular import from cspreports import utils formatted_json = utils.format_report(self.json) return mark_safe("<pre>\n%s</pre>" % escape(formatted_json))
python
def json_as_html(self): # To avoid circular import from cspreports import utils formatted_json = utils.format_report(self.json) return mark_safe("<pre>\n%s</pre>" % escape(formatted_json))
[ "def", "json_as_html", "(", "self", ")", ":", "# To avoid circular import", "from", "cspreports", "import", "utils", "formatted_json", "=", "utils", ".", "format_report", "(", "self", ".", "json", ")", "return", "mark_safe", "(", "\"<pre>\\n%s</pre>\"", "%", "esca...
Print out self.json in a nice way.
[ "Print", "out", "self", ".", "json", "in", "a", "nice", "way", "." ]
867992c6f535cf6afbf911f92af7eea4c61e4b73
https://github.com/adamalton/django-csp-reports/blob/867992c6f535cf6afbf911f92af7eea4c61e4b73/cspreports/models.py#L161-L168
27,665
adamalton/django-csp-reports
cspreports/utils.py
process_report
def process_report(request): """ Given the HTTP request of a CSP violation report, log it in the required ways. """ if config.EMAIL_ADMINS: email_admins(request) if config.LOG: log_report(request) if config.SAVE: save_report(request) if config.ADDITIONAL_HANDLERS: run_additional_handlers(request)
python
def process_report(request): if config.EMAIL_ADMINS: email_admins(request) if config.LOG: log_report(request) if config.SAVE: save_report(request) if config.ADDITIONAL_HANDLERS: run_additional_handlers(request)
[ "def", "process_report", "(", "request", ")", ":", "if", "config", ".", "EMAIL_ADMINS", ":", "email_admins", "(", "request", ")", "if", "config", ".", "LOG", ":", "log_report", "(", "request", ")", "if", "config", ".", "SAVE", ":", "save_report", "(", "r...
Given the HTTP request of a CSP violation report, log it in the required ways.
[ "Given", "the", "HTTP", "request", "of", "a", "CSP", "violation", "report", "log", "it", "in", "the", "required", "ways", "." ]
867992c6f535cf6afbf911f92af7eea4c61e4b73
https://github.com/adamalton/django-csp-reports/blob/867992c6f535cf6afbf911f92af7eea4c61e4b73/cspreports/utils.py#L18-L27
27,666
adamalton/django-csp-reports
cspreports/utils.py
get_additional_handlers
def get_additional_handlers(): """ Returns the actual functions from the dotted paths specified in ADDITIONAL_HANDLERS. """ global _additional_handlers if not isinstance(_additional_handlers, list): handlers = [] for name in config.ADDITIONAL_HANDLERS: module_name, function_name = name.rsplit('.', 1) function = getattr(import_module(module_name), function_name) handlers.append(function) _additional_handlers = handlers return _additional_handlers
python
def get_additional_handlers(): global _additional_handlers if not isinstance(_additional_handlers, list): handlers = [] for name in config.ADDITIONAL_HANDLERS: module_name, function_name = name.rsplit('.', 1) function = getattr(import_module(module_name), function_name) handlers.append(function) _additional_handlers = handlers return _additional_handlers
[ "def", "get_additional_handlers", "(", ")", ":", "global", "_additional_handlers", "if", "not", "isinstance", "(", "_additional_handlers", ",", "list", ")", ":", "handlers", "=", "[", "]", "for", "name", "in", "config", ".", "ADDITIONAL_HANDLERS", ":", "module_n...
Returns the actual functions from the dotted paths specified in ADDITIONAL_HANDLERS.
[ "Returns", "the", "actual", "functions", "from", "the", "dotted", "paths", "specified", "in", "ADDITIONAL_HANDLERS", "." ]
867992c6f535cf6afbf911f92af7eea4c61e4b73
https://github.com/adamalton/django-csp-reports/blob/867992c6f535cf6afbf911f92af7eea4c61e4b73/cspreports/utils.py#L88-L98
27,667
adamalton/django-csp-reports
cspreports/utils.py
parse_date_input
def parse_date_input(value): """Return datetime based on the user's input. @param value: User's input @type value: str @raise ValueError: If the input is not valid. @return: Datetime of the beginning of the user's date. """ try: limit = parse_date(value) except ValueError: limit = None if limit is None: raise ValueError("'{}' is not a valid date.".format(value)) limit = datetime(limit.year, limit.month, limit.day) if settings.USE_TZ: limit = make_aware(limit) return limit
python
def parse_date_input(value): try: limit = parse_date(value) except ValueError: limit = None if limit is None: raise ValueError("'{}' is not a valid date.".format(value)) limit = datetime(limit.year, limit.month, limit.day) if settings.USE_TZ: limit = make_aware(limit) return limit
[ "def", "parse_date_input", "(", "value", ")", ":", "try", ":", "limit", "=", "parse_date", "(", "value", ")", "except", "ValueError", ":", "limit", "=", "None", "if", "limit", "is", "None", ":", "raise", "ValueError", "(", "\"'{}' is not a valid date.\"", "....
Return datetime based on the user's input. @param value: User's input @type value: str @raise ValueError: If the input is not valid. @return: Datetime of the beginning of the user's date.
[ "Return", "datetime", "based", "on", "the", "user", "s", "input", "." ]
867992c6f535cf6afbf911f92af7eea4c61e4b73
https://github.com/adamalton/django-csp-reports/blob/867992c6f535cf6afbf911f92af7eea4c61e4b73/cspreports/utils.py#L101-L118
27,668
adamalton/django-csp-reports
cspreports/utils.py
get_midnight
def get_midnight(): """Return last midnight in localtime as datetime. @return: Midnight datetime """ limit = now() if settings.USE_TZ: limit = localtime(limit) return limit.replace(hour=0, minute=0, second=0, microsecond=0)
python
def get_midnight(): limit = now() if settings.USE_TZ: limit = localtime(limit) return limit.replace(hour=0, minute=0, second=0, microsecond=0)
[ "def", "get_midnight", "(", ")", ":", "limit", "=", "now", "(", ")", "if", "settings", ".", "USE_TZ", ":", "limit", "=", "localtime", "(", "limit", ")", "return", "limit", ".", "replace", "(", "hour", "=", "0", ",", "minute", "=", "0", ",", "second...
Return last midnight in localtime as datetime. @return: Midnight datetime
[ "Return", "last", "midnight", "in", "localtime", "as", "datetime", "." ]
867992c6f535cf6afbf911f92af7eea4c61e4b73
https://github.com/adamalton/django-csp-reports/blob/867992c6f535cf6afbf911f92af7eea4c61e4b73/cspreports/utils.py#L121-L129
27,669
SpheMakh/Stimela
stimela/recipe.py
StimelaJob.python_job
def python_job(self, function, parameters=None): """ Run python function function : Python callable to execute name : Name of function (if not given, will used function.__name__) parameters : Parameters to parse to function label : Function label; for logging purposes """ if not callable(function): raise utils.StimelaCabRuntimeError('Object given as function is not callable') if self.name is None: self.name = function.__name__ self.job = { 'function' : function, 'parameters': parameters, } return 0
python
def python_job(self, function, parameters=None): if not callable(function): raise utils.StimelaCabRuntimeError('Object given as function is not callable') if self.name is None: self.name = function.__name__ self.job = { 'function' : function, 'parameters': parameters, } return 0
[ "def", "python_job", "(", "self", ",", "function", ",", "parameters", "=", "None", ")", ":", "if", "not", "callable", "(", "function", ")", ":", "raise", "utils", ".", "StimelaCabRuntimeError", "(", "'Object given as function is not callable'", ")", "if", "self"...
Run python function function : Python callable to execute name : Name of function (if not given, will used function.__name__) parameters : Parameters to parse to function label : Function label; for logging purposes
[ "Run", "python", "function" ]
292e80461a0c3498da8e7e987e2891d3ae5981ad
https://github.com/SpheMakh/Stimela/blob/292e80461a0c3498da8e7e987e2891d3ae5981ad/stimela/recipe.py#L105-L126
27,670
SpheMakh/Stimela
stimela/singularity.py
pull
def pull(image, store_path, docker=True): """ pull an image """ if docker: fp = "docker://{0:s}".format(image) else: fp = image utils.xrun("singularity", ["pull", "--force", "--name", store_path, fp]) return 0
python
def pull(image, store_path, docker=True): if docker: fp = "docker://{0:s}".format(image) else: fp = image utils.xrun("singularity", ["pull", "--force", "--name", store_path, fp]) return 0
[ "def", "pull", "(", "image", ",", "store_path", ",", "docker", "=", "True", ")", ":", "if", "docker", ":", "fp", "=", "\"docker://{0:s}\"", ".", "format", "(", "image", ")", "else", ":", "fp", "=", "image", "utils", ".", "xrun", "(", "\"singularity\"",...
pull an image
[ "pull", "an", "image" ]
292e80461a0c3498da8e7e987e2891d3ae5981ad
https://github.com/SpheMakh/Stimela/blob/292e80461a0c3498da8e7e987e2891d3ae5981ad/stimela/singularity.py#L15-L26
27,671
SpheMakh/Stimela
stimela/singularity.py
Container.start
def start(self, *args): """ Create a singularity container instance """ if self.volumes: volumes = " --bind " + " --bind ".join(self.volumes) else: volumes = "" self._print("Instantiating container [{0:s}]. Timeout set to {1:d}. The container ID is printed below.".format(self.name, self.time_out)) utils.xrun("singularity instance.start", list(args) + [volumes, # "-c", self.image, self.name]) self.status = "created" return 0
python
def start(self, *args): if self.volumes: volumes = " --bind " + " --bind ".join(self.volumes) else: volumes = "" self._print("Instantiating container [{0:s}]. Timeout set to {1:d}. The container ID is printed below.".format(self.name, self.time_out)) utils.xrun("singularity instance.start", list(args) + [volumes, # "-c", self.image, self.name]) self.status = "created" return 0
[ "def", "start", "(", "self", ",", "*", "args", ")", ":", "if", "self", ".", "volumes", ":", "volumes", "=", "\" --bind \"", "+", "\" --bind \"", ".", "join", "(", "self", ".", "volumes", ")", "else", ":", "volumes", "=", "\"\"", "self", ".", "_print"...
Create a singularity container instance
[ "Create", "a", "singularity", "container", "instance" ]
292e80461a0c3498da8e7e987e2891d3ae5981ad
https://github.com/SpheMakh/Stimela/blob/292e80461a0c3498da8e7e987e2891d3ae5981ad/stimela/singularity.py#L66-L84
27,672
SpheMakh/Stimela
stimela/singularity.py
Container.run
def run(self, *args): """ Run a singularity container instance """ if self.volumes: volumes = " --bind " + " --bind ".join(self.volumes) else: volumes = "" self._print("Starting container [{0:s}]. Timeout set to {1:d}. The container ID is printed below.".format(self.name, self.time_out)) utils.xrun("singularity run", ["instance://{0:s} {1:s}".format(self.name, self.RUNSCRIPT)], timeout= self.time_out, kill_callback=self.stop) self.status = "running" return 0
python
def run(self, *args): if self.volumes: volumes = " --bind " + " --bind ".join(self.volumes) else: volumes = "" self._print("Starting container [{0:s}]. Timeout set to {1:d}. The container ID is printed below.".format(self.name, self.time_out)) utils.xrun("singularity run", ["instance://{0:s} {1:s}".format(self.name, self.RUNSCRIPT)], timeout= self.time_out, kill_callback=self.stop) self.status = "running" return 0
[ "def", "run", "(", "self", ",", "*", "args", ")", ":", "if", "self", ".", "volumes", ":", "volumes", "=", "\" --bind \"", "+", "\" --bind \"", ".", "join", "(", "self", ".", "volumes", ")", "else", ":", "volumes", "=", "\"\"", "self", ".", "_print", ...
Run a singularity container instance
[ "Run", "a", "singularity", "container", "instance" ]
292e80461a0c3498da8e7e987e2891d3ae5981ad
https://github.com/SpheMakh/Stimela/blob/292e80461a0c3498da8e7e987e2891d3ae5981ad/stimela/singularity.py#L87-L103
27,673
SpheMakh/Stimela
stimela/singularity.py
Container.stop
def stop(self, *args): """ Stop a singularity container instance """ if self.volumes: volumes = " --bind " + " --bind ".join(self.volumes) else: volumes = "" self._print("Stopping container [{}]. The container ID is printed below.".format(self.name)) utils.xrun("singularity", ["instance.stop {0:s}".format(self.name)]) self.status = "exited" return 0
python
def stop(self, *args): if self.volumes: volumes = " --bind " + " --bind ".join(self.volumes) else: volumes = "" self._print("Stopping container [{}]. The container ID is printed below.".format(self.name)) utils.xrun("singularity", ["instance.stop {0:s}".format(self.name)]) self.status = "exited" return 0
[ "def", "stop", "(", "self", ",", "*", "args", ")", ":", "if", "self", ".", "volumes", ":", "volumes", "=", "\" --bind \"", "+", "\" --bind \"", ".", "join", "(", "self", ".", "volumes", ")", "else", ":", "volumes", "=", "\"\"", "self", ".", "_print",...
Stop a singularity container instance
[ "Stop", "a", "singularity", "container", "instance" ]
292e80461a0c3498da8e7e987e2891d3ae5981ad
https://github.com/SpheMakh/Stimela/blob/292e80461a0c3498da8e7e987e2891d3ae5981ad/stimela/singularity.py#L106-L121
27,674
SpheMakh/Stimela
stimela/docker.py
build
def build(image, build_path, tag=None, build_args=None, fromline=None, args=[]): """ build a docker image""" if tag: image = ":".join([image, tag]) bdir = tempfile.mkdtemp() os.system('cp -r {0:s}/* {1:s}'.format(build_path, bdir)) if build_args: stdw = tempfile.NamedTemporaryFile(dir=bdir, mode='w') with open("{}/Dockerfile".format(bdir)) as std: dfile = std.readlines() for line in dfile: if fromline and line.lower().startswith('from'): stdw.write('FROM {:s}\n'.format(fromline)) elif line.lower().startswith("cmd"): for arg in build_args: stdw.write(arg+"\n") stdw.write(line) else: stdw.write(line) stdw.flush() utils.xrun("docker build", args+["--force-rm","-f", stdw.name, "-t", image, bdir]) stdw.close() else: utils.xrun("docker build", args+["--force-rm", "-t", image, bdir]) os.system('rm -rf {:s}'.format(bdir))
python
def build(image, build_path, tag=None, build_args=None, fromline=None, args=[]): if tag: image = ":".join([image, tag]) bdir = tempfile.mkdtemp() os.system('cp -r {0:s}/* {1:s}'.format(build_path, bdir)) if build_args: stdw = tempfile.NamedTemporaryFile(dir=bdir, mode='w') with open("{}/Dockerfile".format(bdir)) as std: dfile = std.readlines() for line in dfile: if fromline and line.lower().startswith('from'): stdw.write('FROM {:s}\n'.format(fromline)) elif line.lower().startswith("cmd"): for arg in build_args: stdw.write(arg+"\n") stdw.write(line) else: stdw.write(line) stdw.flush() utils.xrun("docker build", args+["--force-rm","-f", stdw.name, "-t", image, bdir]) stdw.close() else: utils.xrun("docker build", args+["--force-rm", "-t", image, bdir]) os.system('rm -rf {:s}'.format(bdir))
[ "def", "build", "(", "image", ",", "build_path", ",", "tag", "=", "None", ",", "build_args", "=", "None", ",", "fromline", "=", "None", ",", "args", "=", "[", "]", ")", ":", "if", "tag", ":", "image", "=", "\":\"", ".", "join", "(", "[", "image",...
build a docker image
[ "build", "a", "docker", "image" ]
292e80461a0c3498da8e7e987e2891d3ae5981ad
https://github.com/SpheMakh/Stimela/blob/292e80461a0c3498da8e7e987e2891d3ae5981ad/stimela/docker.py#L16-L48
27,675
SpheMakh/Stimela
stimela/docker.py
pull
def pull(image, tag=None): """ pull a docker image """ if tag: image = ":".join([image, tag]) utils.xrun("docker pull", [image])
python
def pull(image, tag=None): if tag: image = ":".join([image, tag]) utils.xrun("docker pull", [image])
[ "def", "pull", "(", "image", ",", "tag", "=", "None", ")", ":", "if", "tag", ":", "image", "=", "\":\"", ".", "join", "(", "[", "image", ",", "tag", "]", ")", "utils", ".", "xrun", "(", "\"docker pull\"", ",", "[", "image", "]", ")" ]
pull a docker image
[ "pull", "a", "docker", "image" ]
292e80461a0c3498da8e7e987e2891d3ae5981ad
https://github.com/SpheMakh/Stimela/blob/292e80461a0c3498da8e7e987e2891d3ae5981ad/stimela/docker.py#L50-L55
27,676
SpheMakh/Stimela
stimela/__init__.py
info
def info(cabdir, header=False): """ prints out help information about a cab """ # First check if cab exists pfile = "{}/parameters.json".format(cabdir) if not os.path.exists(pfile): raise RuntimeError("Cab could not be found at : {}".format(cabdir)) # Get cab info cab_definition = cab.CabDefinition(parameter_file=pfile) cab_definition.display(header)
python
def info(cabdir, header=False): # First check if cab exists pfile = "{}/parameters.json".format(cabdir) if not os.path.exists(pfile): raise RuntimeError("Cab could not be found at : {}".format(cabdir)) # Get cab info cab_definition = cab.CabDefinition(parameter_file=pfile) cab_definition.display(header)
[ "def", "info", "(", "cabdir", ",", "header", "=", "False", ")", ":", "# First check if cab exists", "pfile", "=", "\"{}/parameters.json\"", ".", "format", "(", "cabdir", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "pfile", ")", ":", "raise", ...
prints out help information about a cab
[ "prints", "out", "help", "information", "about", "a", "cab" ]
292e80461a0c3498da8e7e987e2891d3ae5981ad
https://github.com/SpheMakh/Stimela/blob/292e80461a0c3498da8e7e987e2891d3ae5981ad/stimela/__init__.py#L194-L203
27,677
SpheMakh/Stimela
stimela/utils/__init__.py
xrun
def xrun(command, options, log=None, _log_container_as_started=False, logfile=None, timeout=-1, kill_callback=None): """ Run something on command line. Example: _run("ls", ["-lrt", "../"]) """ cmd = " ".join([command] + list(map(str, options)) ) def _print_info(msg): if msg is None: return if log: log.info(msg) else: print(msg) def _print_warn(msg): if msg is None: return if log: log.warn(msg) else: print(msg) _print_info(u"Running: {0:s}".format(cmd)) sys.stdout.flush() starttime = time.time() process = p = None try: foutname = os.path.join("/tmp", "stimela_output_{0:s}_{1:f}".format(hashlib.md5(cmd.encode('utf-8')).hexdigest(), starttime)) with open(foutname, "w+") as fout: p = process = subprocess.Popen(cmd, stderr=fout, stdout=fout, shell=True) def clock_killer(p): while process.poll() is None and (timeout >= 0): currenttime = time.time() if (currenttime - starttime < timeout): DEBUG and _print_warn(u"Clock Reaper: has been running for {0:f}, must finish in {1:f}".format(currenttime - starttime, timeout)) else: _print_warn(u"Clock Reaper: Timeout reached for '{0:s}'... sending the KILL signal".format(cmd)) (kill_callback is not None) and kill_callback() time.sleep(INTERRUPT_TIME) Thread(target=clock_killer, args=tuple([p])).start() while (process.poll() is None): currenttime = time.time() DEBUG and _print_info(u"God mode on: has been running for {0:f}".format(currenttime - starttime)) time.sleep(INTERRUPT_TIME) # this is probably not ideal as it interrupts the process every few seconds, #check whether there is an alternative with a callback assert hasattr(process, "returncode"), "No returncode after termination!" with open(foutname, "r") as fout: _print_info(fout.read()) finally: if (process is not None) and process.returncode: raise StimelaCabRuntimeError('%s: returns errr code %d' % (command, process.returncode))
python
def xrun(command, options, log=None, _log_container_as_started=False, logfile=None, timeout=-1, kill_callback=None): cmd = " ".join([command] + list(map(str, options)) ) def _print_info(msg): if msg is None: return if log: log.info(msg) else: print(msg) def _print_warn(msg): if msg is None: return if log: log.warn(msg) else: print(msg) _print_info(u"Running: {0:s}".format(cmd)) sys.stdout.flush() starttime = time.time() process = p = None try: foutname = os.path.join("/tmp", "stimela_output_{0:s}_{1:f}".format(hashlib.md5(cmd.encode('utf-8')).hexdigest(), starttime)) with open(foutname, "w+") as fout: p = process = subprocess.Popen(cmd, stderr=fout, stdout=fout, shell=True) def clock_killer(p): while process.poll() is None and (timeout >= 0): currenttime = time.time() if (currenttime - starttime < timeout): DEBUG and _print_warn(u"Clock Reaper: has been running for {0:f}, must finish in {1:f}".format(currenttime - starttime, timeout)) else: _print_warn(u"Clock Reaper: Timeout reached for '{0:s}'... sending the KILL signal".format(cmd)) (kill_callback is not None) and kill_callback() time.sleep(INTERRUPT_TIME) Thread(target=clock_killer, args=tuple([p])).start() while (process.poll() is None): currenttime = time.time() DEBUG and _print_info(u"God mode on: has been running for {0:f}".format(currenttime - starttime)) time.sleep(INTERRUPT_TIME) # this is probably not ideal as it interrupts the process every few seconds, #check whether there is an alternative with a callback assert hasattr(process, "returncode"), "No returncode after termination!" with open(foutname, "r") as fout: _print_info(fout.read()) finally: if (process is not None) and process.returncode: raise StimelaCabRuntimeError('%s: returns errr code %d' % (command, process.returncode))
[ "def", "xrun", "(", "command", ",", "options", ",", "log", "=", "None", ",", "_log_container_as_started", "=", "False", ",", "logfile", "=", "None", ",", "timeout", "=", "-", "1", ",", "kill_callback", "=", "None", ")", ":", "cmd", "=", "\" \"", ".", ...
Run something on command line. Example: _run("ls", ["-lrt", "../"])
[ "Run", "something", "on", "command", "line", "." ]
292e80461a0c3498da8e7e987e2891d3ae5981ad
https://github.com/SpheMakh/Stimela/blob/292e80461a0c3498da8e7e987e2891d3ae5981ad/stimela/utils/__init__.py#L52-L110
27,678
SpheMakh/Stimela
stimela/utils/__init__.py
sumcols
def sumcols(msname, col1=None, col2=None, outcol=None, cols=None, suntract=False): """ add col1 to col2, or sum columns in 'cols' list. If subtract, subtract col2 from col1 """ from pyrap.tables import table tab = table(msname, readonly=False) if cols: data = 0 for col in cols: data += tab.getcol(col) else: if subtract: data = tab.getcol(col1) - tab.getcol(col2) else: data = tab.getcol(col1) + tab.getcol(col2) rowchunk = nrows//10 if nrows > 1000 else nrows for row0 in range(0, nrows, rowchunk): nr = min(rowchunk, nrows-row0) tab.putcol(outcol, data[row0:row0+nr], row0, nr) tab.close()
python
def sumcols(msname, col1=None, col2=None, outcol=None, cols=None, suntract=False): from pyrap.tables import table tab = table(msname, readonly=False) if cols: data = 0 for col in cols: data += tab.getcol(col) else: if subtract: data = tab.getcol(col1) - tab.getcol(col2) else: data = tab.getcol(col1) + tab.getcol(col2) rowchunk = nrows//10 if nrows > 1000 else nrows for row0 in range(0, nrows, rowchunk): nr = min(rowchunk, nrows-row0) tab.putcol(outcol, data[row0:row0+nr], row0, nr) tab.close()
[ "def", "sumcols", "(", "msname", ",", "col1", "=", "None", ",", "col2", "=", "None", ",", "outcol", "=", "None", ",", "cols", "=", "None", ",", "suntract", "=", "False", ")", ":", "from", "pyrap", ".", "tables", "import", "table", "tab", "=", "tabl...
add col1 to col2, or sum columns in 'cols' list. If subtract, subtract col2 from col1
[ "add", "col1", "to", "col2", "or", "sum", "columns", "in", "cols", "list", ".", "If", "subtract", "subtract", "col2", "from", "col1" ]
292e80461a0c3498da8e7e987e2891d3ae5981ad
https://github.com/SpheMakh/Stimela/blob/292e80461a0c3498da8e7e987e2891d3ae5981ad/stimela/utils/__init__.py#L397-L420
27,679
SpheMakh/Stimela
stimela/utils/__init__.py
compute_vis_noise
def compute_vis_noise(msname, sefd, spw_id=0): """Computes nominal per-visibility noise""" from pyrap.tables import table tab = table(msname) spwtab = table(msname + "/SPECTRAL_WINDOW") freq0 = spwtab.getcol("CHAN_FREQ")[spw_id, 0] wavelength = 300e+6/freq0 bw = spwtab.getcol("CHAN_WIDTH")[spw_id, 0] dt = tab.getcol("EXPOSURE", 0, 1)[0] dtf = (tab.getcol("TIME", tab.nrows()-1, 1)-tab.getcol("TIME", 0, 1))[0] # close tables properly, else the calls below will hang waiting for a lock... tab.close() spwtab.close() print(">>> %s freq %.2f MHz (lambda=%.2fm), bandwidth %.2g kHz, %.2fs integrations, %.2fh synthesis"%(msname, freq0*1e-6, wavelength, bw*1e-3, dt, dtf/3600)) noise = sefd/math.sqrt(abs(2*bw*dt)) print(">>> SEFD of %.2f Jy gives per-visibility noise of %.2f mJy"%(sefd, noise*1000)) return noise
python
def compute_vis_noise(msname, sefd, spw_id=0): from pyrap.tables import table tab = table(msname) spwtab = table(msname + "/SPECTRAL_WINDOW") freq0 = spwtab.getcol("CHAN_FREQ")[spw_id, 0] wavelength = 300e+6/freq0 bw = spwtab.getcol("CHAN_WIDTH")[spw_id, 0] dt = tab.getcol("EXPOSURE", 0, 1)[0] dtf = (tab.getcol("TIME", tab.nrows()-1, 1)-tab.getcol("TIME", 0, 1))[0] # close tables properly, else the calls below will hang waiting for a lock... tab.close() spwtab.close() print(">>> %s freq %.2f MHz (lambda=%.2fm), bandwidth %.2g kHz, %.2fs integrations, %.2fh synthesis"%(msname, freq0*1e-6, wavelength, bw*1e-3, dt, dtf/3600)) noise = sefd/math.sqrt(abs(2*bw*dt)) print(">>> SEFD of %.2f Jy gives per-visibility noise of %.2f mJy"%(sefd, noise*1000)) return noise
[ "def", "compute_vis_noise", "(", "msname", ",", "sefd", ",", "spw_id", "=", "0", ")", ":", "from", "pyrap", ".", "tables", "import", "table", "tab", "=", "table", "(", "msname", ")", "spwtab", "=", "table", "(", "msname", "+", "\"/SPECTRAL_WINDOW\"", ")"...
Computes nominal per-visibility noise
[ "Computes", "nominal", "per", "-", "visibility", "noise" ]
292e80461a0c3498da8e7e987e2891d3ae5981ad
https://github.com/SpheMakh/Stimela/blob/292e80461a0c3498da8e7e987e2891d3ae5981ad/stimela/utils/__init__.py#L448-L469
27,680
SpheMakh/Stimela
stimela/cargo/cab/specfit/src/addSPI.py
fitsInfo
def fitsInfo(fitsname = None): """ Get fits info """ hdu = pyfits.open(fitsname) hdr = hdu[0].header ra = hdr['CRVAL1'] dra = abs(hdr['CDELT1']) raPix = hdr['CRPIX1'] dec = hdr['CRVAL2'] ddec = abs(hdr['CDELT2']) decPix = hdr['CRPIX2'] freq0 = 0 for i in range(1,hdr['NAXIS']+1): if hdr['CTYPE%d'%i].strip() == 'FREQ': freq0 = hdr['CRVAL%d'%i] break ndim = hdr["NAXIS"] imslice = np.zeros(ndim, dtype=int).tolist() imslice[-2:] = slice(None), slice(None) image = hdu[0].data[imslice] wcs = WCS(hdr,mode='pyfits') return {'image':image,'wcs':wcs,'ra':ra,'dec':dec,'dra':dra,'ddec':ddec,'raPix':raPix,'decPix':decPix,'freq0':freq0}
python
def fitsInfo(fitsname = None): hdu = pyfits.open(fitsname) hdr = hdu[0].header ra = hdr['CRVAL1'] dra = abs(hdr['CDELT1']) raPix = hdr['CRPIX1'] dec = hdr['CRVAL2'] ddec = abs(hdr['CDELT2']) decPix = hdr['CRPIX2'] freq0 = 0 for i in range(1,hdr['NAXIS']+1): if hdr['CTYPE%d'%i].strip() == 'FREQ': freq0 = hdr['CRVAL%d'%i] break ndim = hdr["NAXIS"] imslice = np.zeros(ndim, dtype=int).tolist() imslice[-2:] = slice(None), slice(None) image = hdu[0].data[imslice] wcs = WCS(hdr,mode='pyfits') return {'image':image,'wcs':wcs,'ra':ra,'dec':dec,'dra':dra,'ddec':ddec,'raPix':raPix,'decPix':decPix,'freq0':freq0}
[ "def", "fitsInfo", "(", "fitsname", "=", "None", ")", ":", "hdu", "=", "pyfits", ".", "open", "(", "fitsname", ")", "hdr", "=", "hdu", "[", "0", "]", ".", "header", "ra", "=", "hdr", "[", "'CRVAL1'", "]", "dra", "=", "abs", "(", "hdr", "[", "'C...
Get fits info
[ "Get", "fits", "info" ]
292e80461a0c3498da8e7e987e2891d3ae5981ad
https://github.com/SpheMakh/Stimela/blob/292e80461a0c3498da8e7e987e2891d3ae5981ad/stimela/cargo/cab/specfit/src/addSPI.py#L9-L33
27,681
SpheMakh/Stimela
stimela/cargo/cab/specfit/src/addSPI.py
sky2px
def sky2px(wcs,ra,dec,dra,ddec,cell, beam): """convert a sky region to pixel positions""" dra = beam if dra<beam else dra # assume every source is at least as large as the psf ddec = beam if ddec<beam else ddec offsetDec = int((ddec/2.)/cell) offsetRA = int((dra/2.)/cell) if offsetDec%2==1: offsetDec += 1 if offsetRA%2==1: offsetRA += 1 raPix,decPix = map(int, wcs.wcs2pix(ra,dec)) return np.array([raPix-offsetRA,raPix+offsetRA,decPix-offsetDec,decPix+offsetDec])
python
def sky2px(wcs,ra,dec,dra,ddec,cell, beam): dra = beam if dra<beam else dra # assume every source is at least as large as the psf ddec = beam if ddec<beam else ddec offsetDec = int((ddec/2.)/cell) offsetRA = int((dra/2.)/cell) if offsetDec%2==1: offsetDec += 1 if offsetRA%2==1: offsetRA += 1 raPix,decPix = map(int, wcs.wcs2pix(ra,dec)) return np.array([raPix-offsetRA,raPix+offsetRA,decPix-offsetDec,decPix+offsetDec])
[ "def", "sky2px", "(", "wcs", ",", "ra", ",", "dec", ",", "dra", ",", "ddec", ",", "cell", ",", "beam", ")", ":", "dra", "=", "beam", "if", "dra", "<", "beam", "else", "dra", "# assume every source is at least as large as the psf", "ddec", "=", "beam", "i...
convert a sky region to pixel positions
[ "convert", "a", "sky", "region", "to", "pixel", "positions" ]
292e80461a0c3498da8e7e987e2891d3ae5981ad
https://github.com/SpheMakh/Stimela/blob/292e80461a0c3498da8e7e987e2891d3ae5981ad/stimela/cargo/cab/specfit/src/addSPI.py#L35-L47
27,682
yuma-m/pychord
pychord/quality.py
Quality.get_components
def get_components(self, root='C', visible=False): """ Get components of chord quality :param str root: the root note of the chord :param bool visible: returns the name of notes if True :rtype: list[str|int] :return: components of chord quality """ root_val = note_to_val(root) components = [v + root_val for v in self.components] if visible: components = [val_to_note(c, scale=root) for c in components] return components
python
def get_components(self, root='C', visible=False): root_val = note_to_val(root) components = [v + root_val for v in self.components] if visible: components = [val_to_note(c, scale=root) for c in components] return components
[ "def", "get_components", "(", "self", ",", "root", "=", "'C'", ",", "visible", "=", "False", ")", ":", "root_val", "=", "note_to_val", "(", "root", ")", "components", "=", "[", "v", "+", "root_val", "for", "v", "in", "self", ".", "components", "]", "...
Get components of chord quality :param str root: the root note of the chord :param bool visible: returns the name of notes if True :rtype: list[str|int] :return: components of chord quality
[ "Get", "components", "of", "chord", "quality" ]
4aa39189082daae76e36a2701890f91776d86b47
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/quality.py#L40-L54
27,683
yuma-m/pychord
pychord/quality.py
Quality.append_on_chord
def append_on_chord(self, on_chord, root): """ Append on chord To create Am7/G q = Quality('m7') q.append_on_chord('G', root='A') :param str on_chord: bass note of the chord :param str root: root note of the chord """ root_val = note_to_val(root) on_chord_val = note_to_val(on_chord) - root_val list_ = list(self.components) for idx, val in enumerate(list_): if val % 12 == on_chord_val: self.components.remove(val) break if on_chord_val > root_val: on_chord_val -= 12 if on_chord_val not in self.components: self.components.insert(0, on_chord_val)
python
def append_on_chord(self, on_chord, root): root_val = note_to_val(root) on_chord_val = note_to_val(on_chord) - root_val list_ = list(self.components) for idx, val in enumerate(list_): if val % 12 == on_chord_val: self.components.remove(val) break if on_chord_val > root_val: on_chord_val -= 12 if on_chord_val not in self.components: self.components.insert(0, on_chord_val)
[ "def", "append_on_chord", "(", "self", ",", "on_chord", ",", "root", ")", ":", "root_val", "=", "note_to_val", "(", "root", ")", "on_chord_val", "=", "note_to_val", "(", "on_chord", ")", "-", "root_val", "list_", "=", "list", "(", "self", ".", "components"...
Append on chord To create Am7/G q = Quality('m7') q.append_on_chord('G', root='A') :param str on_chord: bass note of the chord :param str root: root note of the chord
[ "Append", "on", "chord" ]
4aa39189082daae76e36a2701890f91776d86b47
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/quality.py#L56-L79
27,684
yuma-m/pychord
pychord/quality.py
Quality.append_note
def append_note(self, note, root, scale=0): """ Append a note to quality :param str note: note to append on quality :param str root: root note of chord :param int scale: key scale """ root_val = note_to_val(root) note_val = note_to_val(note) - root_val + scale * 12 if note_val not in self.components: self.components.append(note_val) self.components.sort()
python
def append_note(self, note, root, scale=0): root_val = note_to_val(root) note_val = note_to_val(note) - root_val + scale * 12 if note_val not in self.components: self.components.append(note_val) self.components.sort()
[ "def", "append_note", "(", "self", ",", "note", ",", "root", ",", "scale", "=", "0", ")", ":", "root_val", "=", "note_to_val", "(", "root", ")", "note_val", "=", "note_to_val", "(", "note", ")", "-", "root_val", "+", "scale", "*", "12", "if", "note_v...
Append a note to quality :param str note: note to append on quality :param str root: root note of chord :param int scale: key scale
[ "Append", "a", "note", "to", "quality" ]
4aa39189082daae76e36a2701890f91776d86b47
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/quality.py#L81-L92
27,685
yuma-m/pychord
pychord/quality.py
Quality.append_notes
def append_notes(self, notes, root, scale=0): """ Append notes to quality :param list[str] notes: notes to append on quality :param str root: root note of chord :param int scale: key scale """ for note in notes: self.append_note(note, root, scale)
python
def append_notes(self, notes, root, scale=0): for note in notes: self.append_note(note, root, scale)
[ "def", "append_notes", "(", "self", ",", "notes", ",", "root", ",", "scale", "=", "0", ")", ":", "for", "note", "in", "notes", ":", "self", ".", "append_note", "(", "note", ",", "root", ",", "scale", ")" ]
Append notes to quality :param list[str] notes: notes to append on quality :param str root: root note of chord :param int scale: key scale
[ "Append", "notes", "to", "quality" ]
4aa39189082daae76e36a2701890f91776d86b47
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/quality.py#L94-L102
27,686
yuma-m/pychord
pychord/progression.py
ChordProgression.insert
def insert(self, index, chord): """ Insert a chord to chord progressions :param int index: Index to insert a chord :type chord: str|pychord.Chord :param chord: A chord to insert :return: """ self._chords.insert(index, as_chord(chord))
python
def insert(self, index, chord): self._chords.insert(index, as_chord(chord))
[ "def", "insert", "(", "self", ",", "index", ",", "chord", ")", ":", "self", ".", "_chords", ".", "insert", "(", "index", ",", "as_chord", "(", "chord", ")", ")" ]
Insert a chord to chord progressions :param int index: Index to insert a chord :type chord: str|pychord.Chord :param chord: A chord to insert :return:
[ "Insert", "a", "chord", "to", "chord", "progressions" ]
4aa39189082daae76e36a2701890f91776d86b47
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/progression.py#L81-L89
27,687
yuma-m/pychord
pychord/chord.py
as_chord
def as_chord(chord): """ convert from str to Chord instance if input is str :type chord: str|pychord.Chord :param chord: Chord name or Chord instance :rtype: pychord.Chord :return: Chord instance """ if isinstance(chord, Chord): return chord elif isinstance(chord, str): return Chord(chord) else: raise TypeError("input type should be str or Chord instance.")
python
def as_chord(chord): if isinstance(chord, Chord): return chord elif isinstance(chord, str): return Chord(chord) else: raise TypeError("input type should be str or Chord instance.")
[ "def", "as_chord", "(", "chord", ")", ":", "if", "isinstance", "(", "chord", ",", "Chord", ")", ":", "return", "chord", "elif", "isinstance", "(", "chord", ",", "str", ")", ":", "return", "Chord", "(", "chord", ")", "else", ":", "raise", "TypeError", ...
convert from str to Chord instance if input is str :type chord: str|pychord.Chord :param chord: Chord name or Chord instance :rtype: pychord.Chord :return: Chord instance
[ "convert", "from", "str", "to", "Chord", "instance", "if", "input", "is", "str" ]
4aa39189082daae76e36a2701890f91776d86b47
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/chord.py#L130-L143
27,688
yuma-m/pychord
pychord/chord.py
Chord.transpose
def transpose(self, trans, scale="C"): """ Transpose the chord :param int trans: Transpose key :param str scale: key scale :return: """ if not isinstance(trans, int): raise TypeError("Expected integers, not {}".format(type(trans))) self._root = transpose_note(self._root, trans, scale) if self._on: self._on = transpose_note(self._on, trans, scale) self._reconfigure_chord()
python
def transpose(self, trans, scale="C"): if not isinstance(trans, int): raise TypeError("Expected integers, not {}".format(type(trans))) self._root = transpose_note(self._root, trans, scale) if self._on: self._on = transpose_note(self._on, trans, scale) self._reconfigure_chord()
[ "def", "transpose", "(", "self", ",", "trans", ",", "scale", "=", "\"C\"", ")", ":", "if", "not", "isinstance", "(", "trans", ",", "int", ")", ":", "raise", "TypeError", "(", "\"Expected integers, not {}\"", ".", "format", "(", "type", "(", "trans", ")",...
Transpose the chord :param int trans: Transpose key :param str scale: key scale :return:
[ "Transpose", "the", "chord" ]
4aa39189082daae76e36a2701890f91776d86b47
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/chord.py#L85-L97
27,689
yuma-m/pychord
pychord/chord.py
Chord.components
def components(self, visible=True): """ Return the component notes of chord :param bool visible: returns the name of notes if True else list of int :rtype: list[(str or int)] :return: component notes of chord """ if self._on: self._quality.append_on_chord(self.on, self.root) return self._quality.get_components(root=self._root, visible=visible)
python
def components(self, visible=True): if self._on: self._quality.append_on_chord(self.on, self.root) return self._quality.get_components(root=self._root, visible=visible)
[ "def", "components", "(", "self", ",", "visible", "=", "True", ")", ":", "if", "self", ".", "_on", ":", "self", ".", "_quality", ".", "append_on_chord", "(", "self", ".", "on", ",", "self", ".", "root", ")", "return", "self", ".", "_quality", ".", ...
Return the component notes of chord :param bool visible: returns the name of notes if True else list of int :rtype: list[(str or int)] :return: component notes of chord
[ "Return", "the", "component", "notes", "of", "chord" ]
4aa39189082daae76e36a2701890f91776d86b47
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/chord.py#L99-L109
27,690
yuma-m/pychord
pychord/chord.py
Chord._parse
def _parse(self, chord): """ parse a chord :param str chord: Name of chord. """ root, quality, appended, on = parse(chord) self._root = root self._quality = quality self._appended = appended self._on = on
python
def _parse(self, chord): root, quality, appended, on = parse(chord) self._root = root self._quality = quality self._appended = appended self._on = on
[ "def", "_parse", "(", "self", ",", "chord", ")", ":", "root", ",", "quality", ",", "appended", ",", "on", "=", "parse", "(", "chord", ")", "self", ".", "_root", "=", "root", "self", ".", "_quality", "=", "quality", "self", ".", "_appended", "=", "a...
parse a chord :param str chord: Name of chord.
[ "parse", "a", "chord" ]
4aa39189082daae76e36a2701890f91776d86b47
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/chord.py#L111-L120
27,691
yuma-m/pychord
pychord/utils.py
transpose_note
def transpose_note(note, transpose, scale="C"): """ Transpose a note :param str note: note to transpose :type transpose: int :param str scale: key scale :rtype: str :return: transposed note """ val = note_to_val(note) val += transpose return val_to_note(val, scale)
python
def transpose_note(note, transpose, scale="C"): val = note_to_val(note) val += transpose return val_to_note(val, scale)
[ "def", "transpose_note", "(", "note", ",", "transpose", ",", "scale", "=", "\"C\"", ")", ":", "val", "=", "note_to_val", "(", "note", ")", "val", "+=", "transpose", "return", "val_to_note", "(", "val", ",", "scale", ")" ]
Transpose a note :param str note: note to transpose :type transpose: int :param str scale: key scale :rtype: str :return: transposed note
[ "Transpose", "a", "note" ]
4aa39189082daae76e36a2701890f91776d86b47
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/utils.py#L38-L49
27,692
yuma-m/pychord
pychord/parser.py
parse
def parse(chord): """ Parse a string to get chord component :param str chord: str expression of a chord :rtype: (str, pychord.Quality, str, str) :return: (root, quality, appended, on) """ if len(chord) > 1 and chord[1] in ("b", "#"): root = chord[:2] rest = chord[2:] else: root = chord[:1] rest = chord[1:] check_note(root, chord) on_chord_idx = rest.find("/") if on_chord_idx >= 0: on = rest[on_chord_idx + 1:] rest = rest[:on_chord_idx] check_note(on, chord) else: on = None if rest in QUALITY_DICT: quality = Quality(rest) else: raise ValueError("Invalid chord {}: Unknown quality {}".format(chord, rest)) # TODO: Implement parser for appended notes appended = [] return root, quality, appended, on
python
def parse(chord): if len(chord) > 1 and chord[1] in ("b", "#"): root = chord[:2] rest = chord[2:] else: root = chord[:1] rest = chord[1:] check_note(root, chord) on_chord_idx = rest.find("/") if on_chord_idx >= 0: on = rest[on_chord_idx + 1:] rest = rest[:on_chord_idx] check_note(on, chord) else: on = None if rest in QUALITY_DICT: quality = Quality(rest) else: raise ValueError("Invalid chord {}: Unknown quality {}".format(chord, rest)) # TODO: Implement parser for appended notes appended = [] return root, quality, appended, on
[ "def", "parse", "(", "chord", ")", ":", "if", "len", "(", "chord", ")", ">", "1", "and", "chord", "[", "1", "]", "in", "(", "\"b\"", ",", "\"#\"", ")", ":", "root", "=", "chord", "[", ":", "2", "]", "rest", "=", "chord", "[", "2", ":", "]",...
Parse a string to get chord component :param str chord: str expression of a chord :rtype: (str, pychord.Quality, str, str) :return: (root, quality, appended, on)
[ "Parse", "a", "string", "to", "get", "chord", "component" ]
4aa39189082daae76e36a2701890f91776d86b47
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/parser.py#L8-L35
27,693
yuma-m/pychord
pychord/parser.py
check_note
def check_note(note, chord): """ Return True if the note is valid. :param str note: note to check its validity :param str chord: the chord which includes the note :rtype: bool """ if note not in NOTE_VAL_DICT: raise ValueError("Invalid chord {}: Unknown note {}".format(chord, note)) return True
python
def check_note(note, chord): if note not in NOTE_VAL_DICT: raise ValueError("Invalid chord {}: Unknown note {}".format(chord, note)) return True
[ "def", "check_note", "(", "note", ",", "chord", ")", ":", "if", "note", "not", "in", "NOTE_VAL_DICT", ":", "raise", "ValueError", "(", "\"Invalid chord {}: Unknown note {}\"", ".", "format", "(", "chord", ",", "note", ")", ")", "return", "True" ]
Return True if the note is valid. :param str note: note to check its validity :param str chord: the chord which includes the note :rtype: bool
[ "Return", "True", "if", "the", "note", "is", "valid", "." ]
4aa39189082daae76e36a2701890f91776d86b47
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/parser.py#L38-L47
27,694
yuma-m/pychord
pychord/analyzer.py
note_to_chord
def note_to_chord(notes): """ Convert note list to chord list :param list[str] notes: list of note arranged from lower note. ex) ["C", "Eb", "G"] :rtype: list[pychord.Chord] :return: list of chord """ if not notes: raise ValueError("Please specify notes which consist a chord.") root = notes[0] root_and_positions = [] for rotated_notes in get_all_rotated_notes(notes): rotated_root = rotated_notes[0] root_and_positions.append([rotated_root, notes_to_positions(rotated_notes, rotated_notes[0])]) chords = [] for temp_root, positions in root_and_positions: quality = find_quality(positions) if quality is None: continue if temp_root == root: chord = "{}{}".format(root, quality) else: chord = "{}{}/{}".format(temp_root, quality, root) chords.append(Chord(chord)) return chords
python
def note_to_chord(notes): if not notes: raise ValueError("Please specify notes which consist a chord.") root = notes[0] root_and_positions = [] for rotated_notes in get_all_rotated_notes(notes): rotated_root = rotated_notes[0] root_and_positions.append([rotated_root, notes_to_positions(rotated_notes, rotated_notes[0])]) chords = [] for temp_root, positions in root_and_positions: quality = find_quality(positions) if quality is None: continue if temp_root == root: chord = "{}{}".format(root, quality) else: chord = "{}{}/{}".format(temp_root, quality, root) chords.append(Chord(chord)) return chords
[ "def", "note_to_chord", "(", "notes", ")", ":", "if", "not", "notes", ":", "raise", "ValueError", "(", "\"Please specify notes which consist a chord.\"", ")", "root", "=", "notes", "[", "0", "]", "root_and_positions", "=", "[", "]", "for", "rotated_notes", "in",...
Convert note list to chord list :param list[str] notes: list of note arranged from lower note. ex) ["C", "Eb", "G"] :rtype: list[pychord.Chord] :return: list of chord
[ "Convert", "note", "list", "to", "chord", "list" ]
4aa39189082daae76e36a2701890f91776d86b47
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/analyzer.py#L8-L32
27,695
yuma-m/pychord
pychord/analyzer.py
notes_to_positions
def notes_to_positions(notes, root): """ Get notes positions. ex) notes_to_positions(["C", "E", "G"], "C") -> [0, 4, 7] :param list[str] notes: list of notes :param str root: the root note :rtype: list[int] :return: list of note positions """ root_pos = note_to_val(root) current_pos = root_pos positions = [] for note in notes: note_pos = note_to_val(note) if note_pos < current_pos: note_pos += 12 * ((current_pos - note_pos) // 12 + 1) positions.append(note_pos - root_pos) current_pos = note_pos return positions
python
def notes_to_positions(notes, root): root_pos = note_to_val(root) current_pos = root_pos positions = [] for note in notes: note_pos = note_to_val(note) if note_pos < current_pos: note_pos += 12 * ((current_pos - note_pos) // 12 + 1) positions.append(note_pos - root_pos) current_pos = note_pos return positions
[ "def", "notes_to_positions", "(", "notes", ",", "root", ")", ":", "root_pos", "=", "note_to_val", "(", "root", ")", "current_pos", "=", "root_pos", "positions", "=", "[", "]", "for", "note", "in", "notes", ":", "note_pos", "=", "note_to_val", "(", "note", ...
Get notes positions. ex) notes_to_positions(["C", "E", "G"], "C") -> [0, 4, 7] :param list[str] notes: list of notes :param str root: the root note :rtype: list[int] :return: list of note positions
[ "Get", "notes", "positions", "." ]
4aa39189082daae76e36a2701890f91776d86b47
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/analyzer.py#L35-L54
27,696
yuma-m/pychord
pychord/analyzer.py
get_all_rotated_notes
def get_all_rotated_notes(notes): """ Get all rotated notes get_all_rotated_notes([1,3,5]) -> [[1,3,5],[3,5,1],[5,1,3]] :type notes: list[str] :rtype: list[list[str]] """ notes_list = [] for x in range(len(notes)): notes_list.append(notes[x:] + notes[:x]) return notes_list
python
def get_all_rotated_notes(notes): notes_list = [] for x in range(len(notes)): notes_list.append(notes[x:] + notes[:x]) return notes_list
[ "def", "get_all_rotated_notes", "(", "notes", ")", ":", "notes_list", "=", "[", "]", "for", "x", "in", "range", "(", "len", "(", "notes", ")", ")", ":", "notes_list", ".", "append", "(", "notes", "[", "x", ":", "]", "+", "notes", "[", ":", "x", "...
Get all rotated notes get_all_rotated_notes([1,3,5]) -> [[1,3,5],[3,5,1],[5,1,3]] :type notes: list[str] :rtype: list[list[str]]
[ "Get", "all", "rotated", "notes" ]
4aa39189082daae76e36a2701890f91776d86b47
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/analyzer.py#L57-L68
27,697
yuma-m/pychord
pychord/analyzer.py
find_quality
def find_quality(positions): """ Find a quality consists of positions :param list[int] positions: note positions :rtype: str|None """ for q, p in QUALITY_DICT.items(): if positions == list(p): return q return None
python
def find_quality(positions): for q, p in QUALITY_DICT.items(): if positions == list(p): return q return None
[ "def", "find_quality", "(", "positions", ")", ":", "for", "q", ",", "p", "in", "QUALITY_DICT", ".", "items", "(", ")", ":", "if", "positions", "==", "list", "(", "p", ")", ":", "return", "q", "return", "None" ]
Find a quality consists of positions :param list[int] positions: note positions :rtype: str|None
[ "Find", "a", "quality", "consists", "of", "positions" ]
4aa39189082daae76e36a2701890f91776d86b47
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/analyzer.py#L71-L80
27,698
globality-corp/microcosm-flask
microcosm_flask/conventions/base.py
Convention.configure
def configure(self, ns, mappings=None, **kwargs): """ Apply mappings to a namespace. """ if mappings is None: mappings = dict() mappings.update(kwargs) for operation, definition in mappings.items(): try: configure_func = self._find_func(operation) except AttributeError: pass else: configure_func(ns, self._make_definition(definition))
python
def configure(self, ns, mappings=None, **kwargs): if mappings is None: mappings = dict() mappings.update(kwargs) for operation, definition in mappings.items(): try: configure_func = self._find_func(operation) except AttributeError: pass else: configure_func(ns, self._make_definition(definition))
[ "def", "configure", "(", "self", ",", "ns", ",", "mappings", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "mappings", "is", "None", ":", "mappings", "=", "dict", "(", ")", "mappings", ".", "update", "(", "kwargs", ")", "for", "operation", ...
Apply mappings to a namespace.
[ "Apply", "mappings", "to", "a", "namespace", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/base.py#L80-L95
27,699
globality-corp/microcosm-flask
microcosm_flask/conventions/base.py
Convention._find_func
def _find_func(self, operation): """ Find the function to use to configure the given operation. The input might be an `Operation` enum or a string. """ if isinstance(operation, Operation): operation_name = operation.name.lower() else: operation_name = operation.lower() return getattr(self, "configure_{}".format(operation_name))
python
def _find_func(self, operation): if isinstance(operation, Operation): operation_name = operation.name.lower() else: operation_name = operation.lower() return getattr(self, "configure_{}".format(operation_name))
[ "def", "_find_func", "(", "self", ",", "operation", ")", ":", "if", "isinstance", "(", "operation", ",", "Operation", ")", ":", "operation_name", "=", "operation", ".", "name", ".", "lower", "(", ")", "else", ":", "operation_name", "=", "operation", ".", ...
Find the function to use to configure the given operation. The input might be an `Operation` enum or a string.
[ "Find", "the", "function", "to", "use", "to", "configure", "the", "given", "operation", "." ]
c2eaf57f03e7d041eea343751a4a90fcc80df418
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/base.py#L107-L119