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
20,600
Stewori/pytypes
pytypes/type_util.py
generator_checker_py3
def generator_checker_py3(gen, gen_type, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): """Builds a typechecking wrapper around a Python 3 style generator object. """ initialized = False sn = None try: while True: a = gen.send(sn) if initialized or not a is None: if not gen_type.__args__[0] is Any and \ not _isinstance(a, gen_type.__args__[0], bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): tpa = deep_type(a) msg = _make_generator_error_message(deep_type(a), gen, gen_type.__args__[0], 'has incompatible yield type') _raise_typecheck_error(msg, True, a, tpa, gen_type.__args__[0]) # raise pytypes.ReturnTypeError(_make_generator_error_message(deep_type(a), gen, # gen_type.__args__[0], 'has incompatible yield type')) initialized = True sn = yield a if not gen_type.__args__[1] is Any and \ not _isinstance(sn, gen_type.__args__[1], bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): tpsn = deep_type(sn) msg = _make_generator_error_message(tpsn, gen, gen_type.__args__[1], 'has incompatible send type') _raise_typecheck_error(msg, False, sn, tpsn, gen_type.__args__[1]) # raise pytypes.InputTypeError(_make_generator_error_message(deep_type(sn), gen, # gen_type.__args__[1], 'has incompatible send type')) except StopIteration as st: # Python 3: # todo: Check if st.value is always defined (i.e. as None if not present) if not gen_type.__args__[2] is Any and \ not _isinstance(st.value, gen_type.__args__[2], bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): tpst = deep_type(st.value) msg = _make_generator_error_message(tpst, gen, gen_type.__args__[2], 'has incompatible return type') _raise_typecheck_error(msg, True, st.value, tpst, gen_type.__args__[2]) # raise pytypes.ReturnTypeError(_make_generator_error_message(sttp, gen, # gen_type.__args__[2], 'has incompatible return type')) raise st
python
def generator_checker_py3(gen, gen_type, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): initialized = False sn = None try: while True: a = gen.send(sn) if initialized or not a is None: if not gen_type.__args__[0] is Any and \ not _isinstance(a, gen_type.__args__[0], bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): tpa = deep_type(a) msg = _make_generator_error_message(deep_type(a), gen, gen_type.__args__[0], 'has incompatible yield type') _raise_typecheck_error(msg, True, a, tpa, gen_type.__args__[0]) # raise pytypes.ReturnTypeError(_make_generator_error_message(deep_type(a), gen, # gen_type.__args__[0], 'has incompatible yield type')) initialized = True sn = yield a if not gen_type.__args__[1] is Any and \ not _isinstance(sn, gen_type.__args__[1], bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): tpsn = deep_type(sn) msg = _make_generator_error_message(tpsn, gen, gen_type.__args__[1], 'has incompatible send type') _raise_typecheck_error(msg, False, sn, tpsn, gen_type.__args__[1]) # raise pytypes.InputTypeError(_make_generator_error_message(deep_type(sn), gen, # gen_type.__args__[1], 'has incompatible send type')) except StopIteration as st: # Python 3: # todo: Check if st.value is always defined (i.e. as None if not present) if not gen_type.__args__[2] is Any and \ not _isinstance(st.value, gen_type.__args__[2], bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): tpst = deep_type(st.value) msg = _make_generator_error_message(tpst, gen, gen_type.__args__[2], 'has incompatible return type') _raise_typecheck_error(msg, True, st.value, tpst, gen_type.__args__[2]) # raise pytypes.ReturnTypeError(_make_generator_error_message(sttp, gen, # gen_type.__args__[2], 'has incompatible return type')) raise st
[ "def", "generator_checker_py3", "(", "gen", ",", "gen_type", ",", "bound_Generic", ",", "bound_typevars", ",", "bound_typevars_readonly", ",", "follow_fwd_refs", ",", "_recursion_check", ")", ":", "initialized", "=", "False", "sn", "=", "None", "try", ":", "while"...
Builds a typechecking wrapper around a Python 3 style generator object.
[ "Builds", "a", "typechecking", "wrapper", "around", "a", "Python", "3", "style", "generator", "object", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L1919-L1962
20,601
Stewori/pytypes
pytypes/type_util.py
generator_checker_py2
def generator_checker_py2(gen, gen_type, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): """Builds a typechecking wrapper around a Python 2 style generator object. """ initialized = False sn = None while True: a = gen.send(sn) if initialized or not a is None: if not gen_type.__args__[0] is Any and \ not _isinstance(a, gen_type.__args__[0], bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): tpa = deep_type(a) msg = _make_generator_error_message(tpa, gen, gen_type.__args__[0], 'has incompatible yield type') _raise_typecheck_error(msg, True, a, tpa, gen_type.__args__[0]) # raise pytypes.ReturnTypeError(_make_generator_error_message(tpa, gen, # gen_type.__args__[0], 'has incompatible yield type')) initialized = True sn = yield a if not gen_type.__args__[1] is Any and \ not _isinstance(sn, gen_type.__args__[1], bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): tpsn = deep_type(sn) msg = _make_generator_error_message(tpsn, gen, gen_type.__args__[1], 'has incompatible send type') _raise_typecheck_error(msg, False, sn, tpsn, gen_type.__args__[1])
python
def generator_checker_py2(gen, gen_type, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): initialized = False sn = None while True: a = gen.send(sn) if initialized or not a is None: if not gen_type.__args__[0] is Any and \ not _isinstance(a, gen_type.__args__[0], bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): tpa = deep_type(a) msg = _make_generator_error_message(tpa, gen, gen_type.__args__[0], 'has incompatible yield type') _raise_typecheck_error(msg, True, a, tpa, gen_type.__args__[0]) # raise pytypes.ReturnTypeError(_make_generator_error_message(tpa, gen, # gen_type.__args__[0], 'has incompatible yield type')) initialized = True sn = yield a if not gen_type.__args__[1] is Any and \ not _isinstance(sn, gen_type.__args__[1], bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): tpsn = deep_type(sn) msg = _make_generator_error_message(tpsn, gen, gen_type.__args__[1], 'has incompatible send type') _raise_typecheck_error(msg, False, sn, tpsn, gen_type.__args__[1])
[ "def", "generator_checker_py2", "(", "gen", ",", "gen_type", ",", "bound_Generic", ",", "bound_typevars", ",", "bound_typevars_readonly", ",", "follow_fwd_refs", ",", "_recursion_check", ")", ":", "initialized", "=", "False", "sn", "=", "None", "while", "True", ":...
Builds a typechecking wrapper around a Python 2 style generator object.
[ "Builds", "a", "typechecking", "wrapper", "around", "a", "Python", "2", "style", "generator", "object", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L1965-L1991
20,602
Stewori/pytypes
pytypes/type_util.py
annotations_func
def annotations_func(func): """Works like annotations, but is only applicable to functions, methods and properties. """ if not has_type_hints(func): # What about defaults? func.__annotations__ = {} func.__annotations__ = _get_type_hints(func, infer_defaults = False) return func
python
def annotations_func(func): if not has_type_hints(func): # What about defaults? func.__annotations__ = {} func.__annotations__ = _get_type_hints(func, infer_defaults = False) return func
[ "def", "annotations_func", "(", "func", ")", ":", "if", "not", "has_type_hints", "(", "func", ")", ":", "# What about defaults?", "func", ".", "__annotations__", "=", "{", "}", "func", ".", "__annotations__", "=", "_get_type_hints", "(", "func", ",", "infer_de...
Works like annotations, but is only applicable to functions, methods and properties.
[ "Works", "like", "annotations", "but", "is", "only", "applicable", "to", "functions", "methods", "and", "properties", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L2006-L2015
20,603
Stewori/pytypes
pytypes/type_util.py
annotations_class
def annotations_class(cls): """Works like annotations, but is only applicable to classes. """ assert(isclass(cls)) # To play it safe we avoid to modify the dict while iterating over it, # so we previously cache keys. # For this we don't use keys() because of Python 3. # Todo: Better use inspect.getmembers here keys = [key for key in cls.__dict__] for key in keys: memb = cls.__dict__[key] if _check_as_func(memb): annotations_func(memb) elif isclass(memb): annotations_class(memb) return cls
python
def annotations_class(cls): assert(isclass(cls)) # To play it safe we avoid to modify the dict while iterating over it, # so we previously cache keys. # For this we don't use keys() because of Python 3. # Todo: Better use inspect.getmembers here keys = [key for key in cls.__dict__] for key in keys: memb = cls.__dict__[key] if _check_as_func(memb): annotations_func(memb) elif isclass(memb): annotations_class(memb) return cls
[ "def", "annotations_class", "(", "cls", ")", ":", "assert", "(", "isclass", "(", "cls", ")", ")", "# To play it safe we avoid to modify the dict while iterating over it,", "# so we previously cache keys.", "# For this we don't use keys() because of Python 3.", "# Todo: Better use ins...
Works like annotations, but is only applicable to classes.
[ "Works", "like", "annotations", "but", "is", "only", "applicable", "to", "classes", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L2018-L2033
20,604
Stewori/pytypes
pytypes/typelogger.py
dump_cache
def dump_cache(path=None, python2=False, suffix=None): """Writes cached observations by @typelogged into stubfiles. Files will be created in the directory provided as 'path'; overwrites existing files without notice. Uses 'pyi2' suffix if 'python2' flag is given else 'pyi'. Resulting files will be Python 2.7 compilant accordingly. """ typelogging_enabled_tmp = pytypes.typelogging_enabled pytypes.typelogging_enabled = False if suffix is None: suffix = 'pyi2' if python2 else 'pyi' if path is None: path = pytypes.default_typelogger_path modules = {} for key in _member_cache: node = _member_cache[key] mname = node.get_modulename() if not mname in modules: mnode = _module_node(mname) modules[mname] = mnode else: mnode = modules[mname] mnode.append(node) for module in modules: _dump_module(modules[module], path, python2, suffix) pytypes.typelogging_enabled = typelogging_enabled_tmp
python
def dump_cache(path=None, python2=False, suffix=None): typelogging_enabled_tmp = pytypes.typelogging_enabled pytypes.typelogging_enabled = False if suffix is None: suffix = 'pyi2' if python2 else 'pyi' if path is None: path = pytypes.default_typelogger_path modules = {} for key in _member_cache: node = _member_cache[key] mname = node.get_modulename() if not mname in modules: mnode = _module_node(mname) modules[mname] = mnode else: mnode = modules[mname] mnode.append(node) for module in modules: _dump_module(modules[module], path, python2, suffix) pytypes.typelogging_enabled = typelogging_enabled_tmp
[ "def", "dump_cache", "(", "path", "=", "None", ",", "python2", "=", "False", ",", "suffix", "=", "None", ")", ":", "typelogging_enabled_tmp", "=", "pytypes", ".", "typelogging_enabled", "pytypes", ".", "typelogging_enabled", "=", "False", "if", "suffix", "is",...
Writes cached observations by @typelogged into stubfiles. Files will be created in the directory provided as 'path'; overwrites existing files without notice. Uses 'pyi2' suffix if 'python2' flag is given else 'pyi'. Resulting files will be Python 2.7 compilant accordingly.
[ "Writes", "cached", "observations", "by" ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/typelogger.py#L325-L350
20,605
Stewori/pytypes
pytypes/typelogger.py
get_indentation
def get_indentation(func): """Extracts a function's indentation as a string, In contrast to an inspect.indentsize based implementation, this function preserves tabs if present. """ src_lines = getsourcelines(func)[0] for line in src_lines: if not (line.startswith('@') or line.startswith('def') or line.lstrip().startswith('#')): return line[:len(line) - len(line.lstrip())] return pytypes.default_indent
python
def get_indentation(func): src_lines = getsourcelines(func)[0] for line in src_lines: if not (line.startswith('@') or line.startswith('def') or line.lstrip().startswith('#')): return line[:len(line) - len(line.lstrip())] return pytypes.default_indent
[ "def", "get_indentation", "(", "func", ")", ":", "src_lines", "=", "getsourcelines", "(", "func", ")", "[", "0", "]", "for", "line", "in", "src_lines", ":", "if", "not", "(", "line", ".", "startswith", "(", "'@'", ")", "or", "line", ".", "startswith", ...
Extracts a function's indentation as a string, In contrast to an inspect.indentsize based implementation, this function preserves tabs if present.
[ "Extracts", "a", "function", "s", "indentation", "as", "a", "string", "In", "contrast", "to", "an", "inspect", ".", "indentsize", "based", "implementation", "this", "function", "preserves", "tabs", "if", "present", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/typelogger.py#L498-L507
20,606
Stewori/pytypes
pytypes/typelogger.py
typelogged_func
def typelogged_func(func): """Works like typelogged, but is only applicable to functions, methods and properties. """ if not pytypes.typelogging_enabled: return func if hasattr(func, 'do_logging'): func.do_logging = True return func elif hasattr(func, 'do_typecheck'): # actually shouldn't happen return _typeinspect_func(func, func.do_typecheck, True) else: return _typeinspect_func(func, False, True)
python
def typelogged_func(func): if not pytypes.typelogging_enabled: return func if hasattr(func, 'do_logging'): func.do_logging = True return func elif hasattr(func, 'do_typecheck'): # actually shouldn't happen return _typeinspect_func(func, func.do_typecheck, True) else: return _typeinspect_func(func, False, True)
[ "def", "typelogged_func", "(", "func", ")", ":", "if", "not", "pytypes", ".", "typelogging_enabled", ":", "return", "func", "if", "hasattr", "(", "func", ",", "'do_logging'", ")", ":", "func", ".", "do_logging", "=", "True", "return", "func", "elif", "hasa...
Works like typelogged, but is only applicable to functions, methods and properties.
[ "Works", "like", "typelogged", "but", "is", "only", "applicable", "to", "functions", "methods", "and", "properties", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/typelogger.py#L837-L850
20,607
Stewori/pytypes
pytypes/typelogger.py
typelogged_class
def typelogged_class(cls): """Works like typelogged, but is only applicable to classes. """ if not pytypes.typelogging_enabled: return cls assert(isclass(cls)) # To play it safe we avoid to modify the dict while iterating over it, # so we previously cache keys. # For this we don't use keys() because of Python 3. # Todo: Better use inspect.getmembers here keys = [key for key in cls.__dict__] for key in keys: memb = cls.__dict__[key] if _check_as_func(memb): setattr(cls, key, typelogged_func(memb)) elif isclass(memb): typelogged_class(memb) return cls
python
def typelogged_class(cls): if not pytypes.typelogging_enabled: return cls assert(isclass(cls)) # To play it safe we avoid to modify the dict while iterating over it, # so we previously cache keys. # For this we don't use keys() because of Python 3. # Todo: Better use inspect.getmembers here keys = [key for key in cls.__dict__] for key in keys: memb = cls.__dict__[key] if _check_as_func(memb): setattr(cls, key, typelogged_func(memb)) elif isclass(memb): typelogged_class(memb) return cls
[ "def", "typelogged_class", "(", "cls", ")", ":", "if", "not", "pytypes", ".", "typelogging_enabled", ":", "return", "cls", "assert", "(", "isclass", "(", "cls", ")", ")", "# To play it safe we avoid to modify the dict while iterating over it,", "# so we previously cache k...
Works like typelogged, but is only applicable to classes.
[ "Works", "like", "typelogged", "but", "is", "only", "applicable", "to", "classes", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/typelogger.py#L853-L870
20,608
Stewori/pytypes
pytypes/typelogger.py
typelogged_module
def typelogged_module(md): """Works like typelogged, but is only applicable to modules by explicit call). md must be a module or a module name contained in sys.modules. """ if not pytypes.typelogging_enabled: return md if isinstance(md, str): if md in sys.modules: md = sys.modules[md] if md is None: return md elif md in pytypes.typechecker._pending_modules: # if import is pending, we just store this call for later pytypes.typechecker._pending_modules[md].append(typelogged_module) return md assert(ismodule(md)) if md.__name__ in pytypes.typechecker._pending_modules: # if import is pending, we just store this call for later pytypes.typechecker._pending_modules[md.__name__].append(typelogged_module) # we already process the module now as far as possible for its internal use # todo: Issue warning here that not the whole module might be covered yet assert(ismodule(md)) if md.__name__ in _fully_typelogged_modules and \ _fully_typelogged_modules[md.__name__] == len(md.__dict__): return md # To play it safe we avoid to modify the dict while iterating over it, # so we previously cache keys. # For this we don't use keys() because of Python 3. # Todo: Better use inspect.getmembers here keys = [key for key in md.__dict__] for key in keys: memb = md.__dict__[key] if _check_as_func(memb) and memb.__module__ == md.__name__: setattr(md, key, typelogged_func(memb)) elif isclass(memb) and memb.__module__ == md.__name__: typelogged_class(memb) if not md.__name__ in pytypes.typechecker._pending_modules: _fully_typelogged_modules[md.__name__] = len(md.__dict__) return md
python
def typelogged_module(md): if not pytypes.typelogging_enabled: return md if isinstance(md, str): if md in sys.modules: md = sys.modules[md] if md is None: return md elif md in pytypes.typechecker._pending_modules: # if import is pending, we just store this call for later pytypes.typechecker._pending_modules[md].append(typelogged_module) return md assert(ismodule(md)) if md.__name__ in pytypes.typechecker._pending_modules: # if import is pending, we just store this call for later pytypes.typechecker._pending_modules[md.__name__].append(typelogged_module) # we already process the module now as far as possible for its internal use # todo: Issue warning here that not the whole module might be covered yet assert(ismodule(md)) if md.__name__ in _fully_typelogged_modules and \ _fully_typelogged_modules[md.__name__] == len(md.__dict__): return md # To play it safe we avoid to modify the dict while iterating over it, # so we previously cache keys. # For this we don't use keys() because of Python 3. # Todo: Better use inspect.getmembers here keys = [key for key in md.__dict__] for key in keys: memb = md.__dict__[key] if _check_as_func(memb) and memb.__module__ == md.__name__: setattr(md, key, typelogged_func(memb)) elif isclass(memb) and memb.__module__ == md.__name__: typelogged_class(memb) if not md.__name__ in pytypes.typechecker._pending_modules: _fully_typelogged_modules[md.__name__] = len(md.__dict__) return md
[ "def", "typelogged_module", "(", "md", ")", ":", "if", "not", "pytypes", ".", "typelogging_enabled", ":", "return", "md", "if", "isinstance", "(", "md", ",", "str", ")", ":", "if", "md", "in", "sys", ".", "modules", ":", "md", "=", "sys", ".", "modul...
Works like typelogged, but is only applicable to modules by explicit call). md must be a module or a module name contained in sys.modules.
[ "Works", "like", "typelogged", "but", "is", "only", "applicable", "to", "modules", "by", "explicit", "call", ")", ".", "md", "must", "be", "a", "module", "or", "a", "module", "name", "contained", "in", "sys", ".", "modules", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/typelogger.py#L873-L911
20,609
Stewori/pytypes
pytypes/__init__.py
enable_global_typechecked_decorator
def enable_global_typechecked_decorator(flag = True, retrospective = True): """Enables or disables global typechecking mode via decorators. See flag global_typechecked_decorator. In contrast to setting the flag directly, this function provides a retrospective option. If retrospective is true, this will also affect already imported modules, not only future imports. Does not work if checking_enabled is false. Does not work reliably if checking_enabled has ever been set to false during current run. """ global global_typechecked_decorator global_typechecked_decorator = flag if import_hook_enabled: _install_import_hook() if global_typechecked_decorator and retrospective: _catch_up_global_typechecked_decorator() return global_typechecked_decorator
python
def enable_global_typechecked_decorator(flag = True, retrospective = True): global global_typechecked_decorator global_typechecked_decorator = flag if import_hook_enabled: _install_import_hook() if global_typechecked_decorator and retrospective: _catch_up_global_typechecked_decorator() return global_typechecked_decorator
[ "def", "enable_global_typechecked_decorator", "(", "flag", "=", "True", ",", "retrospective", "=", "True", ")", ":", "global", "global_typechecked_decorator", "global_typechecked_decorator", "=", "flag", "if", "import_hook_enabled", ":", "_install_import_hook", "(", ")", ...
Enables or disables global typechecking mode via decorators. See flag global_typechecked_decorator. In contrast to setting the flag directly, this function provides a retrospective option. If retrospective is true, this will also affect already imported modules, not only future imports. Does not work if checking_enabled is false. Does not work reliably if checking_enabled has ever been set to false during current run.
[ "Enables", "or", "disables", "global", "typechecking", "mode", "via", "decorators", ".", "See", "flag", "global_typechecked_decorator", ".", "In", "contrast", "to", "setting", "the", "flag", "directly", "this", "function", "provides", "a", "retrospective", "option",...
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/__init__.py#L390-L406
20,610
Stewori/pytypes
pytypes/__init__.py
enable_global_auto_override_decorator
def enable_global_auto_override_decorator(flag = True, retrospective = True): """Enables or disables global auto_override mode via decorators. See flag global_auto_override_decorator. In contrast to setting the flag directly, this function provides a retrospective option. If retrospective is true, this will also affect already imported modules, not only future imports. """ global global_auto_override_decorator global_auto_override_decorator = flag if import_hook_enabled: _install_import_hook() if global_auto_override_decorator and retrospective: _catch_up_global_auto_override_decorator() return global_auto_override_decorator
python
def enable_global_auto_override_decorator(flag = True, retrospective = True): global global_auto_override_decorator global_auto_override_decorator = flag if import_hook_enabled: _install_import_hook() if global_auto_override_decorator and retrospective: _catch_up_global_auto_override_decorator() return global_auto_override_decorator
[ "def", "enable_global_auto_override_decorator", "(", "flag", "=", "True", ",", "retrospective", "=", "True", ")", ":", "global", "global_auto_override_decorator", "global_auto_override_decorator", "=", "flag", "if", "import_hook_enabled", ":", "_install_import_hook", "(", ...
Enables or disables global auto_override mode via decorators. See flag global_auto_override_decorator. In contrast to setting the flag directly, this function provides a retrospective option. If retrospective is true, this will also affect already imported modules, not only future imports.
[ "Enables", "or", "disables", "global", "auto_override", "mode", "via", "decorators", ".", "See", "flag", "global_auto_override_decorator", ".", "In", "contrast", "to", "setting", "the", "flag", "directly", "this", "function", "provides", "a", "retrospective", "optio...
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/__init__.py#L409-L422
20,611
Stewori/pytypes
pytypes/__init__.py
enable_global_annotations_decorator
def enable_global_annotations_decorator(flag = True, retrospective = True): """Enables or disables global annotation mode via decorators. See flag global_annotations_decorator. In contrast to setting the flag directly, this function provides a retrospective option. If retrospective is true, this will also affect already imported modules, not only future imports. """ global global_annotations_decorator global_annotations_decorator = flag if import_hook_enabled: _install_import_hook() if global_annotations_decorator and retrospective: _catch_up_global_annotations_decorator() return global_annotations_decorator
python
def enable_global_annotations_decorator(flag = True, retrospective = True): global global_annotations_decorator global_annotations_decorator = flag if import_hook_enabled: _install_import_hook() if global_annotations_decorator and retrospective: _catch_up_global_annotations_decorator() return global_annotations_decorator
[ "def", "enable_global_annotations_decorator", "(", "flag", "=", "True", ",", "retrospective", "=", "True", ")", ":", "global", "global_annotations_decorator", "global_annotations_decorator", "=", "flag", "if", "import_hook_enabled", ":", "_install_import_hook", "(", ")", ...
Enables or disables global annotation mode via decorators. See flag global_annotations_decorator. In contrast to setting the flag directly, this function provides a retrospective option. If retrospective is true, this will also affect already imported modules, not only future imports.
[ "Enables", "or", "disables", "global", "annotation", "mode", "via", "decorators", ".", "See", "flag", "global_annotations_decorator", ".", "In", "contrast", "to", "setting", "the", "flag", "directly", "this", "function", "provides", "a", "retrospective", "option", ...
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/__init__.py#L425-L438
20,612
Stewori/pytypes
pytypes/__init__.py
enable_global_typelogged_decorator
def enable_global_typelogged_decorator(flag = True, retrospective = True): """Enables or disables global typelog mode via decorators. See flag global_typelogged_decorator. In contrast to setting the flag directly, this function provides a retrospective option. If retrospective is true, this will also affect already imported modules, not only future imports. """ global global_typelogged_decorator global_typelogged_decorator = flag if import_hook_enabled: _install_import_hook() if global_typelogged_decorator and retrospective: _catch_up_global_typelogged_decorator() return global_typelogged_decorator
python
def enable_global_typelogged_decorator(flag = True, retrospective = True): global global_typelogged_decorator global_typelogged_decorator = flag if import_hook_enabled: _install_import_hook() if global_typelogged_decorator and retrospective: _catch_up_global_typelogged_decorator() return global_typelogged_decorator
[ "def", "enable_global_typelogged_decorator", "(", "flag", "=", "True", ",", "retrospective", "=", "True", ")", ":", "global", "global_typelogged_decorator", "global_typelogged_decorator", "=", "flag", "if", "import_hook_enabled", ":", "_install_import_hook", "(", ")", "...
Enables or disables global typelog mode via decorators. See flag global_typelogged_decorator. In contrast to setting the flag directly, this function provides a retrospective option. If retrospective is true, this will also affect already imported modules, not only future imports.
[ "Enables", "or", "disables", "global", "typelog", "mode", "via", "decorators", ".", "See", "flag", "global_typelogged_decorator", ".", "In", "contrast", "to", "setting", "the", "flag", "directly", "this", "function", "provides", "a", "retrospective", "option", "."...
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/__init__.py#L441-L454
20,613
Stewori/pytypes
pytypes/__init__.py
enable_global_typechecked_profiler
def enable_global_typechecked_profiler(flag = True): """Enables or disables global typechecking mode via a profiler. See flag global_typechecked_profiler. Does not work if checking_enabled is false. """ global global_typechecked_profiler, _global_type_agent, global_typelogged_profiler global_typechecked_profiler = flag if flag and checking_enabled: if _global_type_agent is None: _global_type_agent = TypeAgent() _global_type_agent.start() elif not _global_type_agent.active: _global_type_agent.start() elif not flag and not global_typelogged_profiler and \ not _global_type_agent is None and _global_type_agent.active: _global_type_agent.stop()
python
def enable_global_typechecked_profiler(flag = True): global global_typechecked_profiler, _global_type_agent, global_typelogged_profiler global_typechecked_profiler = flag if flag and checking_enabled: if _global_type_agent is None: _global_type_agent = TypeAgent() _global_type_agent.start() elif not _global_type_agent.active: _global_type_agent.start() elif not flag and not global_typelogged_profiler and \ not _global_type_agent is None and _global_type_agent.active: _global_type_agent.stop()
[ "def", "enable_global_typechecked_profiler", "(", "flag", "=", "True", ")", ":", "global", "global_typechecked_profiler", ",", "_global_type_agent", ",", "global_typelogged_profiler", "global_typechecked_profiler", "=", "flag", "if", "flag", "and", "checking_enabled", ":", ...
Enables or disables global typechecking mode via a profiler. See flag global_typechecked_profiler. Does not work if checking_enabled is false.
[ "Enables", "or", "disables", "global", "typechecking", "mode", "via", "a", "profiler", ".", "See", "flag", "global_typechecked_profiler", ".", "Does", "not", "work", "if", "checking_enabled", "is", "false", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/__init__.py#L457-L472
20,614
Stewori/pytypes
pytypes/__init__.py
enable_global_typelogged_profiler
def enable_global_typelogged_profiler(flag = True): """Enables or disables global typelogging mode via a profiler. See flag global_typelogged_profiler. Does not work if typelogging_enabled is false. """ global global_typelogged_profiler, _global_type_agent, global_typechecked_profiler global_typelogged_profiler = flag if flag and typelogging_enabled: if _global_type_agent is None: _global_type_agent = TypeAgent() _global_type_agent.start() elif not _global_type_agent.active: _global_type_agent.start() elif not flag and not global_typechecked_profiler and \ not _global_type_agent is None and _global_type_agent.active: _global_type_agent.stop()
python
def enable_global_typelogged_profiler(flag = True): global global_typelogged_profiler, _global_type_agent, global_typechecked_profiler global_typelogged_profiler = flag if flag and typelogging_enabled: if _global_type_agent is None: _global_type_agent = TypeAgent() _global_type_agent.start() elif not _global_type_agent.active: _global_type_agent.start() elif not flag and not global_typechecked_profiler and \ not _global_type_agent is None and _global_type_agent.active: _global_type_agent.stop()
[ "def", "enable_global_typelogged_profiler", "(", "flag", "=", "True", ")", ":", "global", "global_typelogged_profiler", ",", "_global_type_agent", ",", "global_typechecked_profiler", "global_typelogged_profiler", "=", "flag", "if", "flag", "and", "typelogging_enabled", ":",...
Enables or disables global typelogging mode via a profiler. See flag global_typelogged_profiler. Does not work if typelogging_enabled is false.
[ "Enables", "or", "disables", "global", "typelogging", "mode", "via", "a", "profiler", ".", "See", "flag", "global_typelogged_profiler", ".", "Does", "not", "work", "if", "typelogging_enabled", "is", "false", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/__init__.py#L475-L490
20,615
Stewori/pytypes
pytypes/typechecker.py
typechecked_func
def typechecked_func(func, force = False, argType = None, resType = None, prop_getter = False): """Works like typechecked, but is only applicable to functions, methods and properties. """ if not pytypes.checking_enabled and not pytypes.do_logging_in_typechecked: return func assert(_check_as_func(func)) if not force and is_no_type_check(func): return func if hasattr(func, 'do_typecheck'): func.do_typecheck = True return func elif hasattr(func, 'do_logging'): # actually shouldn't happen return _typeinspect_func(func, True, func.do_logging, argType, resType, prop_getter) else: return _typeinspect_func(func, True, False, argType, resType, prop_getter)
python
def typechecked_func(func, force = False, argType = None, resType = None, prop_getter = False): if not pytypes.checking_enabled and not pytypes.do_logging_in_typechecked: return func assert(_check_as_func(func)) if not force and is_no_type_check(func): return func if hasattr(func, 'do_typecheck'): func.do_typecheck = True return func elif hasattr(func, 'do_logging'): # actually shouldn't happen return _typeinspect_func(func, True, func.do_logging, argType, resType, prop_getter) else: return _typeinspect_func(func, True, False, argType, resType, prop_getter)
[ "def", "typechecked_func", "(", "func", ",", "force", "=", "False", ",", "argType", "=", "None", ",", "resType", "=", "None", ",", "prop_getter", "=", "False", ")", ":", "if", "not", "pytypes", ".", "checking_enabled", "and", "not", "pytypes", ".", "do_l...
Works like typechecked, but is only applicable to functions, methods and properties.
[ "Works", "like", "typechecked", "but", "is", "only", "applicable", "to", "functions", "methods", "and", "properties", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/typechecker.py#L726-L741
20,616
Stewori/pytypes
pytypes/typechecker.py
typechecked_class
def typechecked_class(cls, force = False, force_recursive = False): """Works like typechecked, but is only applicable to classes. """ return _typechecked_class(cls, set(), force, force_recursive)
python
def typechecked_class(cls, force = False, force_recursive = False): return _typechecked_class(cls, set(), force, force_recursive)
[ "def", "typechecked_class", "(", "cls", ",", "force", "=", "False", ",", "force_recursive", "=", "False", ")", ":", "return", "_typechecked_class", "(", "cls", ",", "set", "(", ")", ",", "force", ",", "force_recursive", ")" ]
Works like typechecked, but is only applicable to classes.
[ "Works", "like", "typechecked", "but", "is", "only", "applicable", "to", "classes", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/typechecker.py#L921-L924
20,617
Stewori/pytypes
pytypes/typechecker.py
auto_override_class
def auto_override_class(cls, force = False, force_recursive = False): """Works like auto_override, but is only applicable to classes. """ if not pytypes.checking_enabled: return cls assert(isclass(cls)) if not force and is_no_type_check(cls): return cls # To play it safe we avoid to modify the dict while iterating over it, # so we previously cache keys. # For this we don't use keys() because of Python 3. # Todo: Better use inspect.getmembers here keys = [key for key in cls.__dict__] for key in keys: memb = cls.__dict__[key] if force_recursive or not is_no_type_check(memb): if isfunction(memb) or ismethod(memb) or ismethoddescriptor(memb): if util._has_base_method(memb, cls): setattr(cls, key, override(memb)) elif isclass(memb): auto_override_class(memb, force_recursive, force_recursive) return cls
python
def auto_override_class(cls, force = False, force_recursive = False): if not pytypes.checking_enabled: return cls assert(isclass(cls)) if not force and is_no_type_check(cls): return cls # To play it safe we avoid to modify the dict while iterating over it, # so we previously cache keys. # For this we don't use keys() because of Python 3. # Todo: Better use inspect.getmembers here keys = [key for key in cls.__dict__] for key in keys: memb = cls.__dict__[key] if force_recursive or not is_no_type_check(memb): if isfunction(memb) or ismethod(memb) or ismethoddescriptor(memb): if util._has_base_method(memb, cls): setattr(cls, key, override(memb)) elif isclass(memb): auto_override_class(memb, force_recursive, force_recursive) return cls
[ "def", "auto_override_class", "(", "cls", ",", "force", "=", "False", ",", "force_recursive", "=", "False", ")", ":", "if", "not", "pytypes", ".", "checking_enabled", ":", "return", "cls", "assert", "(", "isclass", "(", "cls", ")", ")", "if", "not", "for...
Works like auto_override, but is only applicable to classes.
[ "Works", "like", "auto_override", "but", "is", "only", "applicable", "to", "classes", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/typechecker.py#L1025-L1046
20,618
Stewori/pytypes
pytypes/typechecker.py
is_no_type_check
def is_no_type_check(memb): """Checks if an object was annotated with @no_type_check (from typing or pytypes.typechecker). """ try: return hasattr(memb, '__no_type_check__') and memb.__no_type_check__ or \ memb in _not_type_checked except TypeError: return False
python
def is_no_type_check(memb): try: return hasattr(memb, '__no_type_check__') and memb.__no_type_check__ or \ memb in _not_type_checked except TypeError: return False
[ "def", "is_no_type_check", "(", "memb", ")", ":", "try", ":", "return", "hasattr", "(", "memb", ",", "'__no_type_check__'", ")", "and", "memb", ".", "__no_type_check__", "or", "memb", "in", "_not_type_checked", "except", "TypeError", ":", "return", "False" ]
Checks if an object was annotated with @no_type_check (from typing or pytypes.typechecker).
[ "Checks", "if", "an", "object", "was", "annotated", "with" ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/typechecker.py#L1156-L1164
20,619
Stewori/pytypes
pytypes/typechecker.py
check_argument_types
def check_argument_types(cllable = None, call_args = None, clss = None, caller_level = 0): """Can be called from within a function or method to apply typechecking to the arguments that were passed in by the caller. Checking is applied w.r.t. type hints of the function or method hosting the call to check_argument_types. """ return _check_caller_type(False, cllable, call_args, clss, caller_level+1)
python
def check_argument_types(cllable = None, call_args = None, clss = None, caller_level = 0): return _check_caller_type(False, cllable, call_args, clss, caller_level+1)
[ "def", "check_argument_types", "(", "cllable", "=", "None", ",", "call_args", "=", "None", ",", "clss", "=", "None", ",", "caller_level", "=", "0", ")", ":", "return", "_check_caller_type", "(", "False", ",", "cllable", ",", "call_args", ",", "clss", ",", ...
Can be called from within a function or method to apply typechecking to the arguments that were passed in by the caller. Checking is applied w.r.t. type hints of the function or method hosting the call to check_argument_types.
[ "Can", "be", "called", "from", "within", "a", "function", "or", "method", "to", "apply", "typechecking", "to", "the", "arguments", "that", "were", "passed", "in", "by", "the", "caller", ".", "Checking", "is", "applied", "w", ".", "r", ".", "t", ".", "t...
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/typechecker.py#L1167-L1172
20,620
Stewori/pytypes
pytypes/typechecker.py
check_return_type
def check_return_type(value, cllable = None, clss = None, caller_level = 0): """Can be called from within a function or method to apply typechecking to the value that is going to be returned. Checking is applied w.r.t. type hints of the function or method hosting the call to check_return_type. """ return _check_caller_type(True, cllable, value, clss, caller_level+1)
python
def check_return_type(value, cllable = None, clss = None, caller_level = 0): return _check_caller_type(True, cllable, value, clss, caller_level+1)
[ "def", "check_return_type", "(", "value", ",", "cllable", "=", "None", ",", "clss", "=", "None", ",", "caller_level", "=", "0", ")", ":", "return", "_check_caller_type", "(", "True", ",", "cllable", ",", "value", ",", "clss", ",", "caller_level", "+", "1...
Can be called from within a function or method to apply typechecking to the value that is going to be returned. Checking is applied w.r.t. type hints of the function or method hosting the call to check_return_type.
[ "Can", "be", "called", "from", "within", "a", "function", "or", "method", "to", "apply", "typechecking", "to", "the", "value", "that", "is", "going", "to", "be", "returned", ".", "Checking", "is", "applied", "w", ".", "r", ".", "t", ".", "type", "hints...
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/typechecker.py#L1175-L1180
20,621
KrzyHonk/bpmn-python
bpmn_python/bpmn_process_csv_import.py
BpmnDiagramGraphCSVImport.load_diagram_from_csv
def load_diagram_from_csv(filepath, bpmn_diagram): """ Reads an CSV file from given filepath and maps it into inner representation of BPMN diagram. Returns an instance of BPMNDiagramGraph class. :param filepath: string with output filepath, :param bpmn_diagram: an instance of BpmnDiagramGraph class. """ sequence_flows = bpmn_diagram.sequence_flows process_elements_dict = bpmn_diagram.process_elements diagram_attributes = bpmn_diagram.diagram_attributes plane_attributes = bpmn_diagram.plane_attributes process_dict = BpmnDiagramGraphCSVImport.import_csv_file_as_dict(filepath) BpmnDiagramGraphCSVImport.populate_diagram_elements_dict(diagram_attributes) BpmnDiagramGraphCSVImport.populate_process_elements_dict(process_elements_dict, process_dict) BpmnDiagramGraphCSVImport.populate_plane_elements_dict(plane_attributes) BpmnDiagramGraphCSVImport.import_nodes(process_dict, bpmn_diagram, sequence_flows) BpmnDiagramGraphCSVImport.representation_adjustment(process_dict, bpmn_diagram, sequence_flows)
python
def load_diagram_from_csv(filepath, bpmn_diagram): sequence_flows = bpmn_diagram.sequence_flows process_elements_dict = bpmn_diagram.process_elements diagram_attributes = bpmn_diagram.diagram_attributes plane_attributes = bpmn_diagram.plane_attributes process_dict = BpmnDiagramGraphCSVImport.import_csv_file_as_dict(filepath) BpmnDiagramGraphCSVImport.populate_diagram_elements_dict(diagram_attributes) BpmnDiagramGraphCSVImport.populate_process_elements_dict(process_elements_dict, process_dict) BpmnDiagramGraphCSVImport.populate_plane_elements_dict(plane_attributes) BpmnDiagramGraphCSVImport.import_nodes(process_dict, bpmn_diagram, sequence_flows) BpmnDiagramGraphCSVImport.representation_adjustment(process_dict, bpmn_diagram, sequence_flows)
[ "def", "load_diagram_from_csv", "(", "filepath", ",", "bpmn_diagram", ")", ":", "sequence_flows", "=", "bpmn_diagram", ".", "sequence_flows", "process_elements_dict", "=", "bpmn_diagram", ".", "process_elements", "diagram_attributes", "=", "bpmn_diagram", ".", "diagram_at...
Reads an CSV file from given filepath and maps it into inner representation of BPMN diagram. Returns an instance of BPMNDiagramGraph class. :param filepath: string with output filepath, :param bpmn_diagram: an instance of BpmnDiagramGraph class.
[ "Reads", "an", "CSV", "file", "from", "given", "filepath", "and", "maps", "it", "into", "inner", "representation", "of", "BPMN", "diagram", ".", "Returns", "an", "instance", "of", "BPMNDiagramGraph", "class", "." ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_process_csv_import.py#L583-L603
20,622
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_import.py
BpmnDiagramGraphImport.load_diagram_from_xml
def load_diagram_from_xml(filepath, bpmn_diagram): """ Reads an XML file from given filepath and maps it into inner representation of BPMN diagram. Returns an instance of BPMNDiagramGraph class. :param filepath: string with output filepath, :param bpmn_diagram: an instance of BpmnDiagramGraph class. """ diagram_graph = bpmn_diagram.diagram_graph sequence_flows = bpmn_diagram.sequence_flows process_elements_dict = bpmn_diagram.process_elements diagram_attributes = bpmn_diagram.diagram_attributes plane_attributes = bpmn_diagram.plane_attributes collaboration = bpmn_diagram.collaboration document = BpmnDiagramGraphImport.read_xml_file(filepath) # According to BPMN 2.0 XML Schema, there's only one 'BPMNDiagram' and 'BPMNPlane' diagram_element = document.getElementsByTagNameNS("*", "BPMNDiagram")[0] plane_element = diagram_element.getElementsByTagNameNS("*", "BPMNPlane")[0] BpmnDiagramGraphImport.import_diagram_and_plane_attributes(diagram_attributes, plane_attributes, diagram_element, plane_element) BpmnDiagramGraphImport.import_process_elements(document, diagram_graph, sequence_flows, process_elements_dict, plane_element) collaboration_element_list = document.getElementsByTagNameNS("*", consts.Consts.collaboration) if collaboration_element_list is not None and len(collaboration_element_list) > 0: # Diagram has multiple pools and lanes collaboration_element = collaboration_element_list[0] BpmnDiagramGraphImport.import_collaboration_element(diagram_graph, collaboration_element, collaboration) if consts.Consts.message_flows in collaboration: message_flows = collaboration[consts.Consts.message_flows] else: message_flows = {} participants = [] if consts.Consts.participants in collaboration: participants = collaboration[consts.Consts.participants] for element in utils.BpmnImportUtils.iterate_elements(plane_element): if element.nodeType != element.TEXT_NODE: tag_name = utils.BpmnImportUtils.remove_namespace_from_tag_name(element.tagName) if tag_name == consts.Consts.bpmn_shape: BpmnDiagramGraphImport.import_shape_di(participants, diagram_graph, element) elif tag_name == consts.Consts.bpmn_edge: BpmnDiagramGraphImport.import_flow_di(diagram_graph, sequence_flows, message_flows, element)
python
def load_diagram_from_xml(filepath, bpmn_diagram): diagram_graph = bpmn_diagram.diagram_graph sequence_flows = bpmn_diagram.sequence_flows process_elements_dict = bpmn_diagram.process_elements diagram_attributes = bpmn_diagram.diagram_attributes plane_attributes = bpmn_diagram.plane_attributes collaboration = bpmn_diagram.collaboration document = BpmnDiagramGraphImport.read_xml_file(filepath) # According to BPMN 2.0 XML Schema, there's only one 'BPMNDiagram' and 'BPMNPlane' diagram_element = document.getElementsByTagNameNS("*", "BPMNDiagram")[0] plane_element = diagram_element.getElementsByTagNameNS("*", "BPMNPlane")[0] BpmnDiagramGraphImport.import_diagram_and_plane_attributes(diagram_attributes, plane_attributes, diagram_element, plane_element) BpmnDiagramGraphImport.import_process_elements(document, diagram_graph, sequence_flows, process_elements_dict, plane_element) collaboration_element_list = document.getElementsByTagNameNS("*", consts.Consts.collaboration) if collaboration_element_list is not None and len(collaboration_element_list) > 0: # Diagram has multiple pools and lanes collaboration_element = collaboration_element_list[0] BpmnDiagramGraphImport.import_collaboration_element(diagram_graph, collaboration_element, collaboration) if consts.Consts.message_flows in collaboration: message_flows = collaboration[consts.Consts.message_flows] else: message_flows = {} participants = [] if consts.Consts.participants in collaboration: participants = collaboration[consts.Consts.participants] for element in utils.BpmnImportUtils.iterate_elements(plane_element): if element.nodeType != element.TEXT_NODE: tag_name = utils.BpmnImportUtils.remove_namespace_from_tag_name(element.tagName) if tag_name == consts.Consts.bpmn_shape: BpmnDiagramGraphImport.import_shape_di(participants, diagram_graph, element) elif tag_name == consts.Consts.bpmn_edge: BpmnDiagramGraphImport.import_flow_di(diagram_graph, sequence_flows, message_flows, element)
[ "def", "load_diagram_from_xml", "(", "filepath", ",", "bpmn_diagram", ")", ":", "diagram_graph", "=", "bpmn_diagram", ".", "diagram_graph", "sequence_flows", "=", "bpmn_diagram", ".", "sequence_flows", "process_elements_dict", "=", "bpmn_diagram", ".", "process_elements",...
Reads an XML file from given filepath and maps it into inner representation of BPMN diagram. Returns an instance of BPMNDiagramGraph class. :param filepath: string with output filepath, :param bpmn_diagram: an instance of BpmnDiagramGraph class.
[ "Reads", "an", "XML", "file", "from", "given", "filepath", "and", "maps", "it", "into", "inner", "representation", "of", "BPMN", "diagram", ".", "Returns", "an", "instance", "of", "BPMNDiagramGraph", "class", "." ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_import.py#L21-L67
20,623
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_import.py
BpmnDiagramGraphImport.import_collaboration_element
def import_collaboration_element(diagram_graph, collaboration_element, collaboration_dict): """ Method that imports information from 'collaboration' element. :param diagram_graph: NetworkX graph representing a BPMN process diagram, :param collaboration_element: XML doument element, :param collaboration_dict: dictionary, that consist all information imported from 'collaboration' element. Includes three key-value pairs - 'id' which keeps ID of collaboration element, 'participants' that keeps information about 'participant' elements and 'message_flows' that keeps information about message flows. """ collaboration_dict[consts.Consts.id] = collaboration_element.getAttribute(consts.Consts.id) collaboration_dict[consts.Consts.participants] = {} participants_dict = collaboration_dict[consts.Consts.participants] collaboration_dict[consts.Consts.message_flows] = {} message_flows_dict = collaboration_dict[consts.Consts.message_flows] for element in utils.BpmnImportUtils.iterate_elements(collaboration_element): if element.nodeType != element.TEXT_NODE: tag_name = utils.BpmnImportUtils.remove_namespace_from_tag_name(element.tagName) if tag_name == consts.Consts.participant: BpmnDiagramGraphImport.import_participant_element(diagram_graph, participants_dict, element) elif tag_name == consts.Consts.message_flow: BpmnDiagramGraphImport.import_message_flow_to_graph(diagram_graph, message_flows_dict, element)
python
def import_collaboration_element(diagram_graph, collaboration_element, collaboration_dict): collaboration_dict[consts.Consts.id] = collaboration_element.getAttribute(consts.Consts.id) collaboration_dict[consts.Consts.participants] = {} participants_dict = collaboration_dict[consts.Consts.participants] collaboration_dict[consts.Consts.message_flows] = {} message_flows_dict = collaboration_dict[consts.Consts.message_flows] for element in utils.BpmnImportUtils.iterate_elements(collaboration_element): if element.nodeType != element.TEXT_NODE: tag_name = utils.BpmnImportUtils.remove_namespace_from_tag_name(element.tagName) if tag_name == consts.Consts.participant: BpmnDiagramGraphImport.import_participant_element(diagram_graph, participants_dict, element) elif tag_name == consts.Consts.message_flow: BpmnDiagramGraphImport.import_message_flow_to_graph(diagram_graph, message_flows_dict, element)
[ "def", "import_collaboration_element", "(", "diagram_graph", ",", "collaboration_element", ",", "collaboration_dict", ")", ":", "collaboration_dict", "[", "consts", ".", "Consts", ".", "id", "]", "=", "collaboration_element", ".", "getAttribute", "(", "consts", ".", ...
Method that imports information from 'collaboration' element. :param diagram_graph: NetworkX graph representing a BPMN process diagram, :param collaboration_element: XML doument element, :param collaboration_dict: dictionary, that consist all information imported from 'collaboration' element. Includes three key-value pairs - 'id' which keeps ID of collaboration element, 'participants' that keeps information about 'participant' elements and 'message_flows' that keeps information about message flows.
[ "Method", "that", "imports", "information", "from", "collaboration", "element", "." ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_import.py#L70-L92
20,624
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_import.py
BpmnDiagramGraphImport.import_participant_element
def import_participant_element(diagram_graph, participants_dictionary, participant_element): """ Adds 'participant' element to the collaboration dictionary. :param diagram_graph: NetworkX graph representing a BPMN process diagram, :param participants_dictionary: dictionary with participant element attributes. Key is participant ID, value is a dictionary of participant attributes, :param participant_element: object representing a BPMN XML 'participant' element. """ participant_id = participant_element.getAttribute(consts.Consts.id) name = participant_element.getAttribute(consts.Consts.name) process_ref = participant_element.getAttribute(consts.Consts.process_ref) if participant_element.getAttribute(consts.Consts.process_ref) == '': diagram_graph.add_node(participant_id) diagram_graph.node[participant_id][consts.Consts.type] = consts.Consts.participant diagram_graph.node[participant_id][consts.Consts.process] = participant_id participants_dictionary[participant_id] = {consts.Consts.name: name, consts.Consts.process_ref: process_ref}
python
def import_participant_element(diagram_graph, participants_dictionary, participant_element): participant_id = participant_element.getAttribute(consts.Consts.id) name = participant_element.getAttribute(consts.Consts.name) process_ref = participant_element.getAttribute(consts.Consts.process_ref) if participant_element.getAttribute(consts.Consts.process_ref) == '': diagram_graph.add_node(participant_id) diagram_graph.node[participant_id][consts.Consts.type] = consts.Consts.participant diagram_graph.node[participant_id][consts.Consts.process] = participant_id participants_dictionary[participant_id] = {consts.Consts.name: name, consts.Consts.process_ref: process_ref}
[ "def", "import_participant_element", "(", "diagram_graph", ",", "participants_dictionary", ",", "participant_element", ")", ":", "participant_id", "=", "participant_element", ".", "getAttribute", "(", "consts", ".", "Consts", ".", "id", ")", "name", "=", "participant_...
Adds 'participant' element to the collaboration dictionary. :param diagram_graph: NetworkX graph representing a BPMN process diagram, :param participants_dictionary: dictionary with participant element attributes. Key is participant ID, value is a dictionary of participant attributes, :param participant_element: object representing a BPMN XML 'participant' element.
[ "Adds", "participant", "element", "to", "the", "collaboration", "dictionary", "." ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_import.py#L95-L111
20,625
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_import.py
BpmnDiagramGraphImport.import_process_elements
def import_process_elements(document, diagram_graph, sequence_flows, process_elements_dict, plane_element): """ Method for importing all 'process' elements in diagram. :param document: XML document, :param diagram_graph: NetworkX graph representing a BPMN process diagram, :param sequence_flows: a list of sequence flows existing in diagram, :param process_elements_dict: dictionary that holds attribute values for imported 'process' elements. Key is an ID of process, value - a dictionary of process attributes, :param plane_element: object representing a BPMN XML 'plane' element. """ for process_element in document.getElementsByTagNameNS("*", consts.Consts.process): BpmnDiagramGraphImport.import_process_element(process_elements_dict, process_element) process_id = process_element.getAttribute(consts.Consts.id) process_attributes = process_elements_dict[process_id] lane_set_list = process_element.getElementsByTagNameNS("*", consts.Consts.lane_set) if lane_set_list is not None and len(lane_set_list) > 0: # according to BPMN 2.0 XML Schema, there's at most one 'laneSet' element inside 'process' lane_set = lane_set_list[0] BpmnDiagramGraphImport.import_lane_set_element(process_attributes, lane_set, plane_element) for element in utils.BpmnImportUtils.iterate_elements(process_element): if element.nodeType != element.TEXT_NODE: tag_name = utils.BpmnImportUtils.remove_namespace_from_tag_name(element.tagName) BpmnDiagramGraphImport.__import_element_by_tag_name(diagram_graph, sequence_flows, process_id, process_attributes, element, tag_name) for flow in utils.BpmnImportUtils.iterate_elements(process_element): if flow.nodeType != flow.TEXT_NODE: tag_name = utils.BpmnImportUtils.remove_namespace_from_tag_name(flow.tagName) if tag_name == consts.Consts.sequence_flow: BpmnDiagramGraphImport.import_sequence_flow_to_graph(diagram_graph, sequence_flows, process_id, flow)
python
def import_process_elements(document, diagram_graph, sequence_flows, process_elements_dict, plane_element): for process_element in document.getElementsByTagNameNS("*", consts.Consts.process): BpmnDiagramGraphImport.import_process_element(process_elements_dict, process_element) process_id = process_element.getAttribute(consts.Consts.id) process_attributes = process_elements_dict[process_id] lane_set_list = process_element.getElementsByTagNameNS("*", consts.Consts.lane_set) if lane_set_list is not None and len(lane_set_list) > 0: # according to BPMN 2.0 XML Schema, there's at most one 'laneSet' element inside 'process' lane_set = lane_set_list[0] BpmnDiagramGraphImport.import_lane_set_element(process_attributes, lane_set, plane_element) for element in utils.BpmnImportUtils.iterate_elements(process_element): if element.nodeType != element.TEXT_NODE: tag_name = utils.BpmnImportUtils.remove_namespace_from_tag_name(element.tagName) BpmnDiagramGraphImport.__import_element_by_tag_name(diagram_graph, sequence_flows, process_id, process_attributes, element, tag_name) for flow in utils.BpmnImportUtils.iterate_elements(process_element): if flow.nodeType != flow.TEXT_NODE: tag_name = utils.BpmnImportUtils.remove_namespace_from_tag_name(flow.tagName) if tag_name == consts.Consts.sequence_flow: BpmnDiagramGraphImport.import_sequence_flow_to_graph(diagram_graph, sequence_flows, process_id, flow)
[ "def", "import_process_elements", "(", "document", ",", "diagram_graph", ",", "sequence_flows", ",", "process_elements_dict", ",", "plane_element", ")", ":", "for", "process_element", "in", "document", ".", "getElementsByTagNameNS", "(", "\"*\"", ",", "consts", ".", ...
Method for importing all 'process' elements in diagram. :param document: XML document, :param diagram_graph: NetworkX graph representing a BPMN process diagram, :param sequence_flows: a list of sequence flows existing in diagram, :param process_elements_dict: dictionary that holds attribute values for imported 'process' elements. Key is an ID of process, value - a dictionary of process attributes, :param plane_element: object representing a BPMN XML 'plane' element.
[ "Method", "for", "importing", "all", "process", "elements", "in", "diagram", "." ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_import.py#L141-L175
20,626
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_import.py
BpmnDiagramGraphImport.import_child_lane_set_element
def import_child_lane_set_element(child_lane_set_element, plane_element): """ Method for importing 'childLaneSet' element from diagram file. :param child_lane_set_element: XML document element, :param plane_element: object representing a BPMN XML 'plane' element. """ lane_set_id = child_lane_set_element.getAttribute(consts.Consts.id) lanes_attr = {} for element in utils.BpmnImportUtils.iterate_elements(child_lane_set_element): if element.nodeType != element.TEXT_NODE: tag_name = utils.BpmnImportUtils.remove_namespace_from_tag_name(element.tagName) if tag_name == consts.Consts.lane: lane = element lane_id = lane.getAttribute(consts.Consts.id) lane_attr = BpmnDiagramGraphImport.import_lane_element(lane, plane_element) lanes_attr[lane_id] = lane_attr child_lane_set_attr = {consts.Consts.id: lane_set_id, consts.Consts.lanes: lanes_attr} return child_lane_set_attr
python
def import_child_lane_set_element(child_lane_set_element, plane_element): lane_set_id = child_lane_set_element.getAttribute(consts.Consts.id) lanes_attr = {} for element in utils.BpmnImportUtils.iterate_elements(child_lane_set_element): if element.nodeType != element.TEXT_NODE: tag_name = utils.BpmnImportUtils.remove_namespace_from_tag_name(element.tagName) if tag_name == consts.Consts.lane: lane = element lane_id = lane.getAttribute(consts.Consts.id) lane_attr = BpmnDiagramGraphImport.import_lane_element(lane, plane_element) lanes_attr[lane_id] = lane_attr child_lane_set_attr = {consts.Consts.id: lane_set_id, consts.Consts.lanes: lanes_attr} return child_lane_set_attr
[ "def", "import_child_lane_set_element", "(", "child_lane_set_element", ",", "plane_element", ")", ":", "lane_set_id", "=", "child_lane_set_element", ".", "getAttribute", "(", "consts", ".", "Consts", ".", "id", ")", "lanes_attr", "=", "{", "}", "for", "element", "...
Method for importing 'childLaneSet' element from diagram file. :param child_lane_set_element: XML document element, :param plane_element: object representing a BPMN XML 'plane' element.
[ "Method", "for", "importing", "childLaneSet", "element", "from", "diagram", "file", "." ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_import.py#L240-L259
20,627
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_import.py
BpmnDiagramGraphImport.import_task_to_graph
def import_task_to_graph(diagram_graph, process_id, process_attributes, task_element): """ Adds to graph the new element that represents BPMN task. In our representation tasks have only basic attributes and elements, inherited from Activity type, so this method only needs to call add_flownode_to_graph. :param diagram_graph: NetworkX graph representing a BPMN process diagram, :param process_id: string object, representing an ID of process element, :param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of imported flow node, :param task_element: object representing a BPMN XML 'task' element. """ BpmnDiagramGraphImport.import_activity_to_graph(diagram_graph, process_id, process_attributes, task_element)
python
def import_task_to_graph(diagram_graph, process_id, process_attributes, task_element): BpmnDiagramGraphImport.import_activity_to_graph(diagram_graph, process_id, process_attributes, task_element)
[ "def", "import_task_to_graph", "(", "diagram_graph", ",", "process_id", ",", "process_attributes", ",", "task_element", ")", ":", "BpmnDiagramGraphImport", ".", "import_activity_to_graph", "(", "diagram_graph", ",", "process_id", ",", "process_attributes", ",", "task_elem...
Adds to graph the new element that represents BPMN task. In our representation tasks have only basic attributes and elements, inherited from Activity type, so this method only needs to call add_flownode_to_graph. :param diagram_graph: NetworkX graph representing a BPMN process diagram, :param process_id: string object, representing an ID of process element, :param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of imported flow node, :param task_element: object representing a BPMN XML 'task' element.
[ "Adds", "to", "graph", "the", "new", "element", "that", "represents", "BPMN", "task", ".", "In", "our", "representation", "tasks", "have", "only", "basic", "attributes", "and", "elements", "inherited", "from", "Activity", "type", "so", "this", "method", "only"...
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_import.py#L381-L393
20,628
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_import.py
BpmnDiagramGraphImport.import_data_object_to_graph
def import_data_object_to_graph(diagram_graph, process_id, process_attributes, data_object_element): """ Adds to graph the new element that represents BPMN data object. Data object inherits attributes from FlowNode. In addition, an attribute 'isCollection' is added to the node. :param diagram_graph: NetworkX graph representing a BPMN process diagram, :param process_id: string object, representing an ID of process element, :param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of imported flow node, :param data_object_element: object representing a BPMN XML 'dataObject' element. """ BpmnDiagramGraphImport.import_flow_node_to_graph(diagram_graph, process_id, process_attributes, data_object_element) data_object_id = data_object_element.getAttribute(consts.Consts.id) diagram_graph.node[data_object_id][consts.Consts.is_collection] = \ data_object_element.getAttribute(consts.Consts.is_collection) \ if data_object_element.hasAttribute(consts.Consts.is_collection) else "false"
python
def import_data_object_to_graph(diagram_graph, process_id, process_attributes, data_object_element): BpmnDiagramGraphImport.import_flow_node_to_graph(diagram_graph, process_id, process_attributes, data_object_element) data_object_id = data_object_element.getAttribute(consts.Consts.id) diagram_graph.node[data_object_id][consts.Consts.is_collection] = \ data_object_element.getAttribute(consts.Consts.is_collection) \ if data_object_element.hasAttribute(consts.Consts.is_collection) else "false"
[ "def", "import_data_object_to_graph", "(", "diagram_graph", ",", "process_id", ",", "process_attributes", ",", "data_object_element", ")", ":", "BpmnDiagramGraphImport", ".", "import_flow_node_to_graph", "(", "diagram_graph", ",", "process_id", ",", "process_attributes", ",...
Adds to graph the new element that represents BPMN data object. Data object inherits attributes from FlowNode. In addition, an attribute 'isCollection' is added to the node. :param diagram_graph: NetworkX graph representing a BPMN process diagram, :param process_id: string object, representing an ID of process element, :param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of imported flow node, :param data_object_element: object representing a BPMN XML 'dataObject' element.
[ "Adds", "to", "graph", "the", "new", "element", "that", "represents", "BPMN", "data", "object", ".", "Data", "object", "inherits", "attributes", "from", "FlowNode", ".", "In", "addition", "an", "attribute", "isCollection", "is", "added", "to", "the", "node", ...
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_import.py#L433-L449
20,629
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_import.py
BpmnDiagramGraphImport.import_parallel_gateway_to_graph
def import_parallel_gateway_to_graph(diagram_graph, process_id, process_attributes, element): """ Adds to graph the new element that represents BPMN parallel gateway. Parallel gateway doesn't have additional attributes. Separate method is used to improve code readability. :param diagram_graph: NetworkX graph representing a BPMN process diagram, :param process_id: string object, representing an ID of process element, :param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of imported flow node, :param element: object representing a BPMN XML 'parallelGateway'. """ BpmnDiagramGraphImport.import_gateway_to_graph(diagram_graph, process_id, process_attributes, element)
python
def import_parallel_gateway_to_graph(diagram_graph, process_id, process_attributes, element): BpmnDiagramGraphImport.import_gateway_to_graph(diagram_graph, process_id, process_attributes, element)
[ "def", "import_parallel_gateway_to_graph", "(", "diagram_graph", ",", "process_id", ",", "process_attributes", ",", "element", ")", ":", "BpmnDiagramGraphImport", ".", "import_gateway_to_graph", "(", "diagram_graph", ",", "process_id", ",", "process_attributes", ",", "ele...
Adds to graph the new element that represents BPMN parallel gateway. Parallel gateway doesn't have additional attributes. Separate method is used to improve code readability. :param diagram_graph: NetworkX graph representing a BPMN process diagram, :param process_id: string object, representing an ID of process element, :param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of imported flow node, :param element: object representing a BPMN XML 'parallelGateway'.
[ "Adds", "to", "graph", "the", "new", "element", "that", "represents", "BPMN", "parallel", "gateway", ".", "Parallel", "gateway", "doesn", "t", "have", "additional", "attributes", ".", "Separate", "method", "is", "used", "to", "improve", "code", "readability", ...
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_import.py#L550-L561
20,630
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_export.py
BpmnDiagramGraphExport.export_task_info
def export_task_info(node_params, output_element): """ Adds Task node attributes to exported XML element :param node_params: dictionary with given task parameters, :param output_element: object representing BPMN XML 'task' element. """ if consts.Consts.default in node_params and node_params[consts.Consts.default] is not None: output_element.set(consts.Consts.default, node_params[consts.Consts.default])
python
def export_task_info(node_params, output_element): if consts.Consts.default in node_params and node_params[consts.Consts.default] is not None: output_element.set(consts.Consts.default, node_params[consts.Consts.default])
[ "def", "export_task_info", "(", "node_params", ",", "output_element", ")", ":", "if", "consts", ".", "Consts", ".", "default", "in", "node_params", "and", "node_params", "[", "consts", ".", "Consts", ".", "default", "]", "is", "not", "None", ":", "output_ele...
Adds Task node attributes to exported XML element :param node_params: dictionary with given task parameters, :param output_element: object representing BPMN XML 'task' element.
[ "Adds", "Task", "node", "attributes", "to", "exported", "XML", "element" ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_export.py#L26-L34
20,631
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_export.py
BpmnDiagramGraphExport.export_subprocess_info
def export_subprocess_info(bpmn_diagram, subprocess_params, output_element): """ Adds Subprocess node attributes to exported XML element :param bpmn_diagram: BPMNDiagramGraph class instantion representing a BPMN process diagram, :param subprocess_params: dictionary with given subprocess parameters, :param output_element: object representing BPMN XML 'subprocess' element. """ output_element.set(consts.Consts.triggered_by_event, subprocess_params[consts.Consts.triggered_by_event]) if consts.Consts.default in subprocess_params and subprocess_params[consts.Consts.default] is not None: output_element.set(consts.Consts.default, subprocess_params[consts.Consts.default]) # for each node in graph add correct type of element, its attributes and BPMNShape element subprocess_id = subprocess_params[consts.Consts.id] nodes = bpmn_diagram.get_nodes_list_by_process_id(subprocess_id) for node in nodes: node_id = node[0] params = node[1] BpmnDiagramGraphExport.export_node_data(bpmn_diagram, node_id, params, output_element) # for each edge in graph add sequence flow element, its attributes and BPMNEdge element flows = bpmn_diagram.get_flows_list_by_process_id(subprocess_id) for flow in flows: params = flow[2] BpmnDiagramGraphExport.export_flow_process_data(params, output_element)
python
def export_subprocess_info(bpmn_diagram, subprocess_params, output_element): output_element.set(consts.Consts.triggered_by_event, subprocess_params[consts.Consts.triggered_by_event]) if consts.Consts.default in subprocess_params and subprocess_params[consts.Consts.default] is not None: output_element.set(consts.Consts.default, subprocess_params[consts.Consts.default]) # for each node in graph add correct type of element, its attributes and BPMNShape element subprocess_id = subprocess_params[consts.Consts.id] nodes = bpmn_diagram.get_nodes_list_by_process_id(subprocess_id) for node in nodes: node_id = node[0] params = node[1] BpmnDiagramGraphExport.export_node_data(bpmn_diagram, node_id, params, output_element) # for each edge in graph add sequence flow element, its attributes and BPMNEdge element flows = bpmn_diagram.get_flows_list_by_process_id(subprocess_id) for flow in flows: params = flow[2] BpmnDiagramGraphExport.export_flow_process_data(params, output_element)
[ "def", "export_subprocess_info", "(", "bpmn_diagram", ",", "subprocess_params", ",", "output_element", ")", ":", "output_element", ".", "set", "(", "consts", ".", "Consts", ".", "triggered_by_event", ",", "subprocess_params", "[", "consts", ".", "Consts", ".", "tr...
Adds Subprocess node attributes to exported XML element :param bpmn_diagram: BPMNDiagramGraph class instantion representing a BPMN process diagram, :param subprocess_params: dictionary with given subprocess parameters, :param output_element: object representing BPMN XML 'subprocess' element.
[ "Adds", "Subprocess", "node", "attributes", "to", "exported", "XML", "element" ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_export.py#L37-L61
20,632
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_export.py
BpmnDiagramGraphExport.export_data_object_info
def export_data_object_info(bpmn_diagram, data_object_params, output_element): """ Adds DataObject node attributes to exported XML element :param bpmn_diagram: BPMNDiagramGraph class instantion representing a BPMN process diagram, :param data_object_params: dictionary with given subprocess parameters, :param output_element: object representing BPMN XML 'subprocess' element. """ output_element.set(consts.Consts.is_collection, data_object_params[consts.Consts.is_collection])
python
def export_data_object_info(bpmn_diagram, data_object_params, output_element): output_element.set(consts.Consts.is_collection, data_object_params[consts.Consts.is_collection])
[ "def", "export_data_object_info", "(", "bpmn_diagram", ",", "data_object_params", ",", "output_element", ")", ":", "output_element", ".", "set", "(", "consts", ".", "Consts", ".", "is_collection", ",", "data_object_params", "[", "consts", ".", "Consts", ".", "is_c...
Adds DataObject node attributes to exported XML element :param bpmn_diagram: BPMNDiagramGraph class instantion representing a BPMN process diagram, :param data_object_params: dictionary with given subprocess parameters, :param output_element: object representing BPMN XML 'subprocess' element.
[ "Adds", "DataObject", "node", "attributes", "to", "exported", "XML", "element" ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_export.py#L64-L72
20,633
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_export.py
BpmnDiagramGraphExport.export_complex_gateway_info
def export_complex_gateway_info(node_params, output_element): """ Adds ComplexGateway node attributes to exported XML element :param node_params: dictionary with given complex gateway parameters, :param output_element: object representing BPMN XML 'complexGateway' element. """ output_element.set(consts.Consts.gateway_direction, node_params[consts.Consts.gateway_direction]) if consts.Consts.default in node_params and node_params[consts.Consts.default] is not None: output_element.set(consts.Consts.default, node_params[consts.Consts.default])
python
def export_complex_gateway_info(node_params, output_element): output_element.set(consts.Consts.gateway_direction, node_params[consts.Consts.gateway_direction]) if consts.Consts.default in node_params and node_params[consts.Consts.default] is not None: output_element.set(consts.Consts.default, node_params[consts.Consts.default])
[ "def", "export_complex_gateway_info", "(", "node_params", ",", "output_element", ")", ":", "output_element", ".", "set", "(", "consts", ".", "Consts", ".", "gateway_direction", ",", "node_params", "[", "consts", ".", "Consts", ".", "gateway_direction", "]", ")", ...
Adds ComplexGateway node attributes to exported XML element :param node_params: dictionary with given complex gateway parameters, :param output_element: object representing BPMN XML 'complexGateway' element.
[ "Adds", "ComplexGateway", "node", "attributes", "to", "exported", "XML", "element" ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_export.py#L77-L86
20,634
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_export.py
BpmnDiagramGraphExport.export_event_based_gateway_info
def export_event_based_gateway_info(node_params, output_element): """ Adds EventBasedGateway node attributes to exported XML element :param node_params: dictionary with given event based gateway parameters, :param output_element: object representing BPMN XML 'eventBasedGateway' element. """ output_element.set(consts.Consts.gateway_direction, node_params[consts.Consts.gateway_direction]) output_element.set(consts.Consts.instantiate, node_params[consts.Consts.instantiate]) output_element.set(consts.Consts.event_gateway_type, node_params[consts.Consts.event_gateway_type])
python
def export_event_based_gateway_info(node_params, output_element): output_element.set(consts.Consts.gateway_direction, node_params[consts.Consts.gateway_direction]) output_element.set(consts.Consts.instantiate, node_params[consts.Consts.instantiate]) output_element.set(consts.Consts.event_gateway_type, node_params[consts.Consts.event_gateway_type])
[ "def", "export_event_based_gateway_info", "(", "node_params", ",", "output_element", ")", ":", "output_element", ".", "set", "(", "consts", ".", "Consts", ".", "gateway_direction", ",", "node_params", "[", "consts", ".", "Consts", ".", "gateway_direction", "]", ")...
Adds EventBasedGateway node attributes to exported XML element :param node_params: dictionary with given event based gateway parameters, :param output_element: object representing BPMN XML 'eventBasedGateway' element.
[ "Adds", "EventBasedGateway", "node", "attributes", "to", "exported", "XML", "element" ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_export.py#L89-L98
20,635
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_export.py
BpmnDiagramGraphExport.export_inclusive_exclusive_gateway_info
def export_inclusive_exclusive_gateway_info(node_params, output_element): """ Adds InclusiveGateway or ExclusiveGateway node attributes to exported XML element :param node_params: dictionary with given inclusive or exclusive gateway parameters, :param output_element: object representing BPMN XML 'inclusiveGateway'/'exclusive' element. """ output_element.set(consts.Consts.gateway_direction, node_params[consts.Consts.gateway_direction]) if consts.Consts.default in node_params and node_params[consts.Consts.default] is not None: output_element.set(consts.Consts.default, node_params[consts.Consts.default])
python
def export_inclusive_exclusive_gateway_info(node_params, output_element): output_element.set(consts.Consts.gateway_direction, node_params[consts.Consts.gateway_direction]) if consts.Consts.default in node_params and node_params[consts.Consts.default] is not None: output_element.set(consts.Consts.default, node_params[consts.Consts.default])
[ "def", "export_inclusive_exclusive_gateway_info", "(", "node_params", ",", "output_element", ")", ":", "output_element", ".", "set", "(", "consts", ".", "Consts", ".", "gateway_direction", ",", "node_params", "[", "consts", ".", "Consts", ".", "gateway_direction", "...
Adds InclusiveGateway or ExclusiveGateway node attributes to exported XML element :param node_params: dictionary with given inclusive or exclusive gateway parameters, :param output_element: object representing BPMN XML 'inclusiveGateway'/'exclusive' element.
[ "Adds", "InclusiveGateway", "or", "ExclusiveGateway", "node", "attributes", "to", "exported", "XML", "element" ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_export.py#L101-L110
20,636
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_export.py
BpmnDiagramGraphExport.export_parallel_gateway_info
def export_parallel_gateway_info(node_params, output_element): """ Adds parallel gateway node attributes to exported XML element :param node_params: dictionary with given parallel gateway parameters, :param output_element: object representing BPMN XML 'parallelGateway' element. """ output_element.set(consts.Consts.gateway_direction, node_params[consts.Consts.gateway_direction])
python
def export_parallel_gateway_info(node_params, output_element): output_element.set(consts.Consts.gateway_direction, node_params[consts.Consts.gateway_direction])
[ "def", "export_parallel_gateway_info", "(", "node_params", ",", "output_element", ")", ":", "output_element", ".", "set", "(", "consts", ".", "Consts", ".", "gateway_direction", ",", "node_params", "[", "consts", ".", "Consts", ".", "gateway_direction", "]", ")" ]
Adds parallel gateway node attributes to exported XML element :param node_params: dictionary with given parallel gateway parameters, :param output_element: object representing BPMN XML 'parallelGateway' element.
[ "Adds", "parallel", "gateway", "node", "attributes", "to", "exported", "XML", "element" ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_export.py#L113-L120
20,637
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_export.py
BpmnDiagramGraphExport.export_start_event_info
def export_start_event_info(node_params, output_element): """ Adds StartEvent attributes to exported XML element :param node_params: dictionary with given intermediate catch event parameters, :param output_element: object representing BPMN XML 'intermediateCatchEvent' element. """ output_element.set(consts.Consts.parallel_multiple, node_params.get(consts.Consts.parallel_multiple)) output_element.set(consts.Consts.is_interrupting, node_params.get(consts.Consts.is_interrupting)) definitions = node_params.get(consts.Consts.event_definitions) for definition in definitions: definition_id = definition[consts.Consts.id] definition_type = definition[consts.Consts.definition_type] output_definition = eTree.SubElement(output_element, definition_type) if definition_id != "": output_definition.set(consts.Consts.id, definition_id)
python
def export_start_event_info(node_params, output_element): output_element.set(consts.Consts.parallel_multiple, node_params.get(consts.Consts.parallel_multiple)) output_element.set(consts.Consts.is_interrupting, node_params.get(consts.Consts.is_interrupting)) definitions = node_params.get(consts.Consts.event_definitions) for definition in definitions: definition_id = definition[consts.Consts.id] definition_type = definition[consts.Consts.definition_type] output_definition = eTree.SubElement(output_element, definition_type) if definition_id != "": output_definition.set(consts.Consts.id, definition_id)
[ "def", "export_start_event_info", "(", "node_params", ",", "output_element", ")", ":", "output_element", ".", "set", "(", "consts", ".", "Consts", ".", "parallel_multiple", ",", "node_params", ".", "get", "(", "consts", ".", "Consts", ".", "parallel_multiple", "...
Adds StartEvent attributes to exported XML element :param node_params: dictionary with given intermediate catch event parameters, :param output_element: object representing BPMN XML 'intermediateCatchEvent' element.
[ "Adds", "StartEvent", "attributes", "to", "exported", "XML", "element" ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_export.py#L140-L155
20,638
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_export.py
BpmnDiagramGraphExport.export_throw_event_info
def export_throw_event_info(node_params, output_element): """ Adds EndEvent or IntermediateThrowingEvent attributes to exported XML element :param node_params: dictionary with given intermediate throw event parameters, :param output_element: object representing BPMN XML 'intermediateThrowEvent' element. """ definitions = node_params[consts.Consts.event_definitions] for definition in definitions: definition_id = definition[consts.Consts.id] definition_type = definition[consts.Consts.definition_type] output_definition = eTree.SubElement(output_element, definition_type) if definition_id != "": output_definition.set(consts.Consts.id, definition_id)
python
def export_throw_event_info(node_params, output_element): definitions = node_params[consts.Consts.event_definitions] for definition in definitions: definition_id = definition[consts.Consts.id] definition_type = definition[consts.Consts.definition_type] output_definition = eTree.SubElement(output_element, definition_type) if definition_id != "": output_definition.set(consts.Consts.id, definition_id)
[ "def", "export_throw_event_info", "(", "node_params", ",", "output_element", ")", ":", "definitions", "=", "node_params", "[", "consts", ".", "Consts", ".", "event_definitions", "]", "for", "definition", "in", "definitions", ":", "definition_id", "=", "definition", ...
Adds EndEvent or IntermediateThrowingEvent attributes to exported XML element :param node_params: dictionary with given intermediate throw event parameters, :param output_element: object representing BPMN XML 'intermediateThrowEvent' element.
[ "Adds", "EndEvent", "or", "IntermediateThrowingEvent", "attributes", "to", "exported", "XML", "element" ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_export.py#L158-L171
20,639
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_export.py
BpmnDiagramGraphExport.export_boundary_event_info
def export_boundary_event_info(node_params, output_element): """ Adds IntermediateCatchEvent attributes to exported XML element :param node_params: dictionary with given intermediate catch event parameters, :param output_element: object representing BPMN XML 'intermediateCatchEvent' element. """ output_element.set(consts.Consts.parallel_multiple, node_params[consts.Consts.parallel_multiple]) output_element.set(consts.Consts.cancel_activity, node_params[consts.Consts.cancel_activity]) output_element.set(consts.Consts.attached_to_ref, node_params[consts.Consts.attached_to_ref]) definitions = node_params[consts.Consts.event_definitions] for definition in definitions: definition_id = definition[consts.Consts.id] definition_type = definition[consts.Consts.definition_type] output_definition = eTree.SubElement(output_element, definition_type) if definition_id != "": output_definition.set(consts.Consts.id, definition_id)
python
def export_boundary_event_info(node_params, output_element): output_element.set(consts.Consts.parallel_multiple, node_params[consts.Consts.parallel_multiple]) output_element.set(consts.Consts.cancel_activity, node_params[consts.Consts.cancel_activity]) output_element.set(consts.Consts.attached_to_ref, node_params[consts.Consts.attached_to_ref]) definitions = node_params[consts.Consts.event_definitions] for definition in definitions: definition_id = definition[consts.Consts.id] definition_type = definition[consts.Consts.definition_type] output_definition = eTree.SubElement(output_element, definition_type) if definition_id != "": output_definition.set(consts.Consts.id, definition_id)
[ "def", "export_boundary_event_info", "(", "node_params", ",", "output_element", ")", ":", "output_element", ".", "set", "(", "consts", ".", "Consts", ".", "parallel_multiple", ",", "node_params", "[", "consts", ".", "Consts", ".", "parallel_multiple", "]", ")", ...
Adds IntermediateCatchEvent attributes to exported XML element :param node_params: dictionary with given intermediate catch event parameters, :param output_element: object representing BPMN XML 'intermediateCatchEvent' element.
[ "Adds", "IntermediateCatchEvent", "attributes", "to", "exported", "XML", "element" ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_export.py#L174-L190
20,640
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_export.py
BpmnDiagramGraphExport.export_process_element
def export_process_element(definitions, process_id, process_attributes_dictionary): """ Creates process element for exported BPMN XML file. :param process_id: string object. ID of exported process element, :param definitions: an XML element ('definitions'), root element of BPMN 2.0 document :param process_attributes_dictionary: dictionary that holds attribute values of 'process' element :return: process XML element """ process = eTree.SubElement(definitions, consts.Consts.process) process.set(consts.Consts.id, process_id) process.set(consts.Consts.is_closed, process_attributes_dictionary[consts.Consts.is_closed]) process.set(consts.Consts.is_executable, process_attributes_dictionary[consts.Consts.is_executable]) process.set(consts.Consts.process_type, process_attributes_dictionary[consts.Consts.process_type]) return process
python
def export_process_element(definitions, process_id, process_attributes_dictionary): process = eTree.SubElement(definitions, consts.Consts.process) process.set(consts.Consts.id, process_id) process.set(consts.Consts.is_closed, process_attributes_dictionary[consts.Consts.is_closed]) process.set(consts.Consts.is_executable, process_attributes_dictionary[consts.Consts.is_executable]) process.set(consts.Consts.process_type, process_attributes_dictionary[consts.Consts.process_type]) return process
[ "def", "export_process_element", "(", "definitions", ",", "process_id", ",", "process_attributes_dictionary", ")", ":", "process", "=", "eTree", ".", "SubElement", "(", "definitions", ",", "consts", ".", "Consts", ".", "process", ")", "process", ".", "set", "(",...
Creates process element for exported BPMN XML file. :param process_id: string object. ID of exported process element, :param definitions: an XML element ('definitions'), root element of BPMN 2.0 document :param process_attributes_dictionary: dictionary that holds attribute values of 'process' element :return: process XML element
[ "Creates", "process", "element", "for", "exported", "BPMN", "XML", "file", "." ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_export.py#L213-L228
20,641
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_export.py
BpmnDiagramGraphExport.export_lane_set
def export_lane_set(process, lane_set, plane_element): """ Creates 'laneSet' element for exported BPMN XML file. :param process: an XML element ('process'), from exported BPMN 2.0 document, :param lane_set: dictionary with exported 'laneSet' element attributes and child elements, :param plane_element: XML object, representing 'plane' element of exported BPMN 2.0 XML. """ lane_set_xml = eTree.SubElement(process, consts.Consts.lane_set) for key, value in lane_set[consts.Consts.lanes].items(): BpmnDiagramGraphExport.export_lane(lane_set_xml, key, value, plane_element)
python
def export_lane_set(process, lane_set, plane_element): lane_set_xml = eTree.SubElement(process, consts.Consts.lane_set) for key, value in lane_set[consts.Consts.lanes].items(): BpmnDiagramGraphExport.export_lane(lane_set_xml, key, value, plane_element)
[ "def", "export_lane_set", "(", "process", ",", "lane_set", ",", "plane_element", ")", ":", "lane_set_xml", "=", "eTree", ".", "SubElement", "(", "process", ",", "consts", ".", "Consts", ".", "lane_set", ")", "for", "key", ",", "value", "in", "lane_set", "[...
Creates 'laneSet' element for exported BPMN XML file. :param process: an XML element ('process'), from exported BPMN 2.0 document, :param lane_set: dictionary with exported 'laneSet' element attributes and child elements, :param plane_element: XML object, representing 'plane' element of exported BPMN 2.0 XML.
[ "Creates", "laneSet", "element", "for", "exported", "BPMN", "XML", "file", "." ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_export.py#L231-L241
20,642
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_export.py
BpmnDiagramGraphExport.export_child_lane_set
def export_child_lane_set(parent_xml_element, child_lane_set, plane_element): """ Creates 'childLaneSet' element for exported BPMN XML file. :param parent_xml_element: an XML element, parent of exported 'childLaneSet' element, :param child_lane_set: dictionary with exported 'childLaneSet' element attributes and child elements, :param plane_element: XML object, representing 'plane' element of exported BPMN 2.0 XML. """ lane_set_xml = eTree.SubElement(parent_xml_element, consts.Consts.lane_set) for key, value in child_lane_set[consts.Consts.lanes].items(): BpmnDiagramGraphExport.export_lane(lane_set_xml, key, value, plane_element)
python
def export_child_lane_set(parent_xml_element, child_lane_set, plane_element): lane_set_xml = eTree.SubElement(parent_xml_element, consts.Consts.lane_set) for key, value in child_lane_set[consts.Consts.lanes].items(): BpmnDiagramGraphExport.export_lane(lane_set_xml, key, value, plane_element)
[ "def", "export_child_lane_set", "(", "parent_xml_element", ",", "child_lane_set", ",", "plane_element", ")", ":", "lane_set_xml", "=", "eTree", ".", "SubElement", "(", "parent_xml_element", ",", "consts", ".", "Consts", ".", "lane_set", ")", "for", "key", ",", "...
Creates 'childLaneSet' element for exported BPMN XML file. :param parent_xml_element: an XML element, parent of exported 'childLaneSet' element, :param child_lane_set: dictionary with exported 'childLaneSet' element attributes and child elements, :param plane_element: XML object, representing 'plane' element of exported BPMN 2.0 XML.
[ "Creates", "childLaneSet", "element", "for", "exported", "BPMN", "XML", "file", "." ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_export.py#L244-L254
20,643
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_export.py
BpmnDiagramGraphExport.export_lane
def export_lane(parent_xml_element, lane_id, lane_attr, plane_element): """ Creates 'lane' element for exported BPMN XML file. :param parent_xml_element: an XML element, parent of exported 'lane' element, :param lane_id: string object. ID of exported lane element, :param lane_attr: dictionary with lane element attributes, :param plane_element: XML object, representing 'plane' element of exported BPMN 2.0 XML. """ lane_xml = eTree.SubElement(parent_xml_element, consts.Consts.lane) lane_xml.set(consts.Consts.id, lane_id) lane_xml.set(consts.Consts.name, lane_attr[consts.Consts.name]) if consts.Consts.child_lane_set in lane_attr and len(lane_attr[consts.Consts.child_lane_set]): child_lane_set = lane_attr[consts.Consts.child_lane_set] BpmnDiagramGraphExport.export_child_lane_set(lane_xml, child_lane_set, plane_element) if consts.Consts.flow_node_refs in lane_attr and len(lane_attr[consts.Consts.flow_node_refs]): for flow_node_ref_id in lane_attr[consts.Consts.flow_node_refs]: flow_node_ref_xml = eTree.SubElement(lane_xml, consts.Consts.flow_node_ref) flow_node_ref_xml.text = flow_node_ref_id output_element_di = eTree.SubElement(plane_element, BpmnDiagramGraphExport.bpmndi_namespace + consts.Consts.bpmn_shape) output_element_di.set(consts.Consts.id, lane_id + "_gui") output_element_di.set(consts.Consts.bpmn_element, lane_id) output_element_di.set(consts.Consts.is_horizontal, lane_attr[consts.Consts.is_horizontal]) bounds = eTree.SubElement(output_element_di, "omgdc:Bounds") bounds.set(consts.Consts.width, lane_attr[consts.Consts.width]) bounds.set(consts.Consts.height, lane_attr[consts.Consts.height]) bounds.set(consts.Consts.x, lane_attr[consts.Consts.x]) bounds.set(consts.Consts.y, lane_attr[consts.Consts.y])
python
def export_lane(parent_xml_element, lane_id, lane_attr, plane_element): lane_xml = eTree.SubElement(parent_xml_element, consts.Consts.lane) lane_xml.set(consts.Consts.id, lane_id) lane_xml.set(consts.Consts.name, lane_attr[consts.Consts.name]) if consts.Consts.child_lane_set in lane_attr and len(lane_attr[consts.Consts.child_lane_set]): child_lane_set = lane_attr[consts.Consts.child_lane_set] BpmnDiagramGraphExport.export_child_lane_set(lane_xml, child_lane_set, plane_element) if consts.Consts.flow_node_refs in lane_attr and len(lane_attr[consts.Consts.flow_node_refs]): for flow_node_ref_id in lane_attr[consts.Consts.flow_node_refs]: flow_node_ref_xml = eTree.SubElement(lane_xml, consts.Consts.flow_node_ref) flow_node_ref_xml.text = flow_node_ref_id output_element_di = eTree.SubElement(plane_element, BpmnDiagramGraphExport.bpmndi_namespace + consts.Consts.bpmn_shape) output_element_di.set(consts.Consts.id, lane_id + "_gui") output_element_di.set(consts.Consts.bpmn_element, lane_id) output_element_di.set(consts.Consts.is_horizontal, lane_attr[consts.Consts.is_horizontal]) bounds = eTree.SubElement(output_element_di, "omgdc:Bounds") bounds.set(consts.Consts.width, lane_attr[consts.Consts.width]) bounds.set(consts.Consts.height, lane_attr[consts.Consts.height]) bounds.set(consts.Consts.x, lane_attr[consts.Consts.x]) bounds.set(consts.Consts.y, lane_attr[consts.Consts.y])
[ "def", "export_lane", "(", "parent_xml_element", ",", "lane_id", ",", "lane_attr", ",", "plane_element", ")", ":", "lane_xml", "=", "eTree", ".", "SubElement", "(", "parent_xml_element", ",", "consts", ".", "Consts", ".", "lane", ")", "lane_xml", ".", "set", ...
Creates 'lane' element for exported BPMN XML file. :param parent_xml_element: an XML element, parent of exported 'lane' element, :param lane_id: string object. ID of exported lane element, :param lane_attr: dictionary with lane element attributes, :param plane_element: XML object, representing 'plane' element of exported BPMN 2.0 XML.
[ "Creates", "lane", "element", "for", "exported", "BPMN", "XML", "file", "." ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_export.py#L257-L287
20,644
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_export.py
BpmnDiagramGraphExport.export_node_di_data
def export_node_di_data(node_id, params, plane): """ Creates a new BPMNShape XML element for given node parameters and adds it to 'plane' element. :param node_id: string representing ID of given flow node, :param params: dictionary with node parameters, :param plane: object of Element class, representing BPMN XML 'BPMNPlane' element (root for node DI data). """ output_element_di = eTree.SubElement(plane, BpmnDiagramGraphExport.bpmndi_namespace + consts.Consts.bpmn_shape) output_element_di.set(consts.Consts.id, node_id + "_gui") output_element_di.set(consts.Consts.bpmn_element, node_id) bounds = eTree.SubElement(output_element_di, "omgdc:Bounds") bounds.set(consts.Consts.width, params[consts.Consts.width]) bounds.set(consts.Consts.height, params[consts.Consts.height]) bounds.set(consts.Consts.x, params[consts.Consts.x]) bounds.set(consts.Consts.y, params[consts.Consts.y]) if params[consts.Consts.type] == consts.Consts.subprocess: output_element_di.set(consts.Consts.is_expanded, params[consts.Consts.is_expanded])
python
def export_node_di_data(node_id, params, plane): output_element_di = eTree.SubElement(plane, BpmnDiagramGraphExport.bpmndi_namespace + consts.Consts.bpmn_shape) output_element_di.set(consts.Consts.id, node_id + "_gui") output_element_di.set(consts.Consts.bpmn_element, node_id) bounds = eTree.SubElement(output_element_di, "omgdc:Bounds") bounds.set(consts.Consts.width, params[consts.Consts.width]) bounds.set(consts.Consts.height, params[consts.Consts.height]) bounds.set(consts.Consts.x, params[consts.Consts.x]) bounds.set(consts.Consts.y, params[consts.Consts.y]) if params[consts.Consts.type] == consts.Consts.subprocess: output_element_di.set(consts.Consts.is_expanded, params[consts.Consts.is_expanded])
[ "def", "export_node_di_data", "(", "node_id", ",", "params", ",", "plane", ")", ":", "output_element_di", "=", "eTree", ".", "SubElement", "(", "plane", ",", "BpmnDiagramGraphExport", ".", "bpmndi_namespace", "+", "consts", ".", "Consts", ".", "bpmn_shape", ")",...
Creates a new BPMNShape XML element for given node parameters and adds it to 'plane' element. :param node_id: string representing ID of given flow node, :param params: dictionary with node parameters, :param plane: object of Element class, representing BPMN XML 'BPMNPlane' element (root for node DI data).
[ "Creates", "a", "new", "BPMNShape", "XML", "element", "for", "given", "node", "parameters", "and", "adds", "it", "to", "plane", "element", "." ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_export.py#L358-L376
20,645
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_export.py
BpmnDiagramGraphExport.export_flow_process_data
def export_flow_process_data(params, process): """ Creates a new SequenceFlow XML element for given edge parameters and adds it to 'process' element. :param params: dictionary with edge parameters, :param process: object of Element class, representing BPMN XML 'process' element (root for sequence flows) """ output_flow = eTree.SubElement(process, consts.Consts.sequence_flow) output_flow.set(consts.Consts.id, params[consts.Consts.id]) output_flow.set(consts.Consts.name, params[consts.Consts.name]) output_flow.set(consts.Consts.source_ref, params[consts.Consts.source_ref]) output_flow.set(consts.Consts.target_ref, params[consts.Consts.target_ref]) if consts.Consts.condition_expression in params: condition_expression_params = params[consts.Consts.condition_expression] condition_expression = eTree.SubElement(output_flow, consts.Consts.condition_expression) condition_expression.set(consts.Consts.id, condition_expression_params[consts.Consts.id]) condition_expression.set(consts.Consts.id, condition_expression_params[consts.Consts.id]) condition_expression.text = condition_expression_params[consts.Consts.condition_expression] output_flow.set(consts.Consts.name, condition_expression_params[consts.Consts.condition_expression])
python
def export_flow_process_data(params, process): output_flow = eTree.SubElement(process, consts.Consts.sequence_flow) output_flow.set(consts.Consts.id, params[consts.Consts.id]) output_flow.set(consts.Consts.name, params[consts.Consts.name]) output_flow.set(consts.Consts.source_ref, params[consts.Consts.source_ref]) output_flow.set(consts.Consts.target_ref, params[consts.Consts.target_ref]) if consts.Consts.condition_expression in params: condition_expression_params = params[consts.Consts.condition_expression] condition_expression = eTree.SubElement(output_flow, consts.Consts.condition_expression) condition_expression.set(consts.Consts.id, condition_expression_params[consts.Consts.id]) condition_expression.set(consts.Consts.id, condition_expression_params[consts.Consts.id]) condition_expression.text = condition_expression_params[consts.Consts.condition_expression] output_flow.set(consts.Consts.name, condition_expression_params[consts.Consts.condition_expression])
[ "def", "export_flow_process_data", "(", "params", ",", "process", ")", ":", "output_flow", "=", "eTree", ".", "SubElement", "(", "process", ",", "consts", ".", "Consts", ".", "sequence_flow", ")", "output_flow", ".", "set", "(", "consts", ".", "Consts", ".",...
Creates a new SequenceFlow XML element for given edge parameters and adds it to 'process' element. :param params: dictionary with edge parameters, :param process: object of Element class, representing BPMN XML 'process' element (root for sequence flows)
[ "Creates", "a", "new", "SequenceFlow", "XML", "element", "for", "given", "edge", "parameters", "and", "adds", "it", "to", "process", "element", "." ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_export.py#L379-L397
20,646
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_export.py
BpmnDiagramGraphExport.export_flow_di_data
def export_flow_di_data(params, plane): """ Creates a new BPMNEdge XML element for given edge parameters and adds it to 'plane' element. :param params: dictionary with edge parameters, :param plane: object of Element class, representing BPMN XML 'BPMNPlane' element (root for edge DI data). """ output_flow = eTree.SubElement(plane, BpmnDiagramGraphExport.bpmndi_namespace + consts.Consts.bpmn_edge) output_flow.set(consts.Consts.id, params[consts.Consts.id] + "_gui") output_flow.set(consts.Consts.bpmn_element, params[consts.Consts.id]) waypoints = params[consts.Consts.waypoints] for waypoint in waypoints: waypoint_element = eTree.SubElement(output_flow, "omgdi:waypoint") waypoint_element.set(consts.Consts.x, waypoint[0]) waypoint_element.set(consts.Consts.y, waypoint[1])
python
def export_flow_di_data(params, plane): output_flow = eTree.SubElement(plane, BpmnDiagramGraphExport.bpmndi_namespace + consts.Consts.bpmn_edge) output_flow.set(consts.Consts.id, params[consts.Consts.id] + "_gui") output_flow.set(consts.Consts.bpmn_element, params[consts.Consts.id]) waypoints = params[consts.Consts.waypoints] for waypoint in waypoints: waypoint_element = eTree.SubElement(output_flow, "omgdi:waypoint") waypoint_element.set(consts.Consts.x, waypoint[0]) waypoint_element.set(consts.Consts.y, waypoint[1])
[ "def", "export_flow_di_data", "(", "params", ",", "plane", ")", ":", "output_flow", "=", "eTree", ".", "SubElement", "(", "plane", ",", "BpmnDiagramGraphExport", ".", "bpmndi_namespace", "+", "consts", ".", "Consts", ".", "bpmn_edge", ")", "output_flow", ".", ...
Creates a new BPMNEdge XML element for given edge parameters and adds it to 'plane' element. :param params: dictionary with edge parameters, :param plane: object of Element class, representing BPMN XML 'BPMNPlane' element (root for edge DI data).
[ "Creates", "a", "new", "BPMNEdge", "XML", "element", "for", "given", "edge", "parameters", "and", "adds", "it", "to", "plane", "element", "." ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_export.py#L400-L414
20,647
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_export.py
BpmnDiagramGraphExport.indent
def indent(elem, level=0): """ Helper function, adds indentation to XML output. :param elem: object of Element class, representing element to which method adds intendation, :param level: current level of intendation. """ i = "\n" + level * " " j = "\n" + (level - 1) * " " if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " if not elem.tail or not elem.tail.strip(): elem.tail = i for subelem in elem: BpmnDiagramGraphExport.indent(subelem, level + 1) if not elem.tail or not elem.tail.strip(): elem.tail = j else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = j return elem
python
def indent(elem, level=0): i = "\n" + level * " " j = "\n" + (level - 1) * " " if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " if not elem.tail or not elem.tail.strip(): elem.tail = i for subelem in elem: BpmnDiagramGraphExport.indent(subelem, level + 1) if not elem.tail or not elem.tail.strip(): elem.tail = j else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = j return elem
[ "def", "indent", "(", "elem", ",", "level", "=", "0", ")", ":", "i", "=", "\"\\n\"", "+", "level", "*", "\" \"", "j", "=", "\"\\n\"", "+", "(", "level", "-", "1", ")", "*", "\" \"", "if", "len", "(", "elem", ")", ":", "if", "not", "elem", "...
Helper function, adds indentation to XML output. :param elem: object of Element class, representing element to which method adds intendation, :param level: current level of intendation.
[ "Helper", "function", "adds", "indentation", "to", "XML", "output", "." ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_export.py#L557-L578
20,648
KrzyHonk/bpmn-python
bpmn_python/bpmn_import_utils.py
BpmnImportUtils.generate_nodes_clasification
def generate_nodes_clasification(bpmn_diagram): """ Diagram elements classification. Implementation based on article "A Simple Algorithm for Automatic Layout of BPMN Processes". Assigns a classification to the diagram element according to specific element parameters. - Element - every element of the process which is not an edge, - Start Event - all types of start events, - End Event - all types of end events, - Join - an element with more than one incoming edge, - Split - an element with more than one outgoing edge. :param bpmn_diagram: BPMNDiagramGraph class instance representing a BPMN process diagram. :return: a dictionary of classification labels. Key - node id. Values - a list of labels. """ nodes_classification = {} classification_element = "Element" classification_start_event = "Start Event" classification_end_event = "End Event" task_list = bpmn_diagram.get_nodes(consts.Consts.task) for element in task_list: classification_labels = [classification_element] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) subprocess_list = bpmn_diagram.get_nodes(consts.Consts.subprocess) for element in subprocess_list: classification_labels = [classification_element] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) complex_gateway_list = bpmn_diagram.get_nodes(consts.Consts.complex_gateway) for element in complex_gateway_list: classification_labels = [classification_element] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) event_based_gateway_list = bpmn_diagram.get_nodes(consts.Consts.event_based_gateway) for element in event_based_gateway_list: classification_labels = [classification_element] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) inclusive_gateway_list = bpmn_diagram.get_nodes(consts.Consts.inclusive_gateway) for element in inclusive_gateway_list: classification_labels = [classification_element] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) exclusive_gateway_list = bpmn_diagram.get_nodes(consts.Consts.exclusive_gateway) for element in exclusive_gateway_list: classification_labels = [classification_element] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) parallel_gateway_list = bpmn_diagram.get_nodes(consts.Consts.parallel_gateway) for element in parallel_gateway_list: classification_labels = [classification_element] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) start_event_list = bpmn_diagram.get_nodes(consts.Consts.start_event) for element in start_event_list: classification_labels = [classification_element, classification_start_event] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) intermediate_catch_event_list = bpmn_diagram.get_nodes(consts.Consts.intermediate_catch_event) for element in intermediate_catch_event_list: classification_labels = [classification_element] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) end_event_list = bpmn_diagram.get_nodes(consts.Consts.end_event) for element in end_event_list: classification_labels = [classification_element, classification_end_event] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) intermediate_throw_event_list = bpmn_diagram.get_nodes(consts.Consts.intermediate_throw_event) for element in intermediate_throw_event_list: classification_labels = [classification_element] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) return nodes_classification
python
def generate_nodes_clasification(bpmn_diagram): nodes_classification = {} classification_element = "Element" classification_start_event = "Start Event" classification_end_event = "End Event" task_list = bpmn_diagram.get_nodes(consts.Consts.task) for element in task_list: classification_labels = [classification_element] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) subprocess_list = bpmn_diagram.get_nodes(consts.Consts.subprocess) for element in subprocess_list: classification_labels = [classification_element] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) complex_gateway_list = bpmn_diagram.get_nodes(consts.Consts.complex_gateway) for element in complex_gateway_list: classification_labels = [classification_element] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) event_based_gateway_list = bpmn_diagram.get_nodes(consts.Consts.event_based_gateway) for element in event_based_gateway_list: classification_labels = [classification_element] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) inclusive_gateway_list = bpmn_diagram.get_nodes(consts.Consts.inclusive_gateway) for element in inclusive_gateway_list: classification_labels = [classification_element] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) exclusive_gateway_list = bpmn_diagram.get_nodes(consts.Consts.exclusive_gateway) for element in exclusive_gateway_list: classification_labels = [classification_element] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) parallel_gateway_list = bpmn_diagram.get_nodes(consts.Consts.parallel_gateway) for element in parallel_gateway_list: classification_labels = [classification_element] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) start_event_list = bpmn_diagram.get_nodes(consts.Consts.start_event) for element in start_event_list: classification_labels = [classification_element, classification_start_event] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) intermediate_catch_event_list = bpmn_diagram.get_nodes(consts.Consts.intermediate_catch_event) for element in intermediate_catch_event_list: classification_labels = [classification_element] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) end_event_list = bpmn_diagram.get_nodes(consts.Consts.end_event) for element in end_event_list: classification_labels = [classification_element, classification_end_event] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) intermediate_throw_event_list = bpmn_diagram.get_nodes(consts.Consts.intermediate_throw_event) for element in intermediate_throw_event_list: classification_labels = [classification_element] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) return nodes_classification
[ "def", "generate_nodes_clasification", "(", "bpmn_diagram", ")", ":", "nodes_classification", "=", "{", "}", "classification_element", "=", "\"Element\"", "classification_start_event", "=", "\"Start Event\"", "classification_end_event", "=", "\"End Event\"", "task_list", "=",...
Diagram elements classification. Implementation based on article "A Simple Algorithm for Automatic Layout of BPMN Processes". Assigns a classification to the diagram element according to specific element parameters. - Element - every element of the process which is not an edge, - Start Event - all types of start events, - End Event - all types of end events, - Join - an element with more than one incoming edge, - Split - an element with more than one outgoing edge. :param bpmn_diagram: BPMNDiagramGraph class instance representing a BPMN process diagram. :return: a dictionary of classification labels. Key - node id. Values - a list of labels.
[ "Diagram", "elements", "classification", ".", "Implementation", "based", "on", "article", "A", "Simple", "Algorithm", "for", "Automatic", "Layout", "of", "BPMN", "Processes", ".", "Assigns", "a", "classification", "to", "the", "diagram", "element", "according", "t...
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_import_utils.py#L39-L114
20,649
KrzyHonk/bpmn-python
bpmn_python/bpmn_import_utils.py
BpmnImportUtils.split_join_classification
def split_join_classification(element, classification_labels, nodes_classification): """ Add the "Split", "Join" classification, if the element qualifies for. :param element: an element from BPMN diagram, :param classification_labels: list of labels attached to the element, :param nodes_classification: dictionary of classification labels. Key - node id. Value - a list of labels. """ classification_join = "Join" classification_split = "Split" if len(element[1][consts.Consts.incoming_flow]) >= 2: classification_labels.append(classification_join) if len(element[1][consts.Consts.outgoing_flow]) >= 2: classification_labels.append(classification_split) nodes_classification[element[0]] = classification_labels
python
def split_join_classification(element, classification_labels, nodes_classification): classification_join = "Join" classification_split = "Split" if len(element[1][consts.Consts.incoming_flow]) >= 2: classification_labels.append(classification_join) if len(element[1][consts.Consts.outgoing_flow]) >= 2: classification_labels.append(classification_split) nodes_classification[element[0]] = classification_labels
[ "def", "split_join_classification", "(", "element", ",", "classification_labels", ",", "nodes_classification", ")", ":", "classification_join", "=", "\"Join\"", "classification_split", "=", "\"Split\"", "if", "len", "(", "element", "[", "1", "]", "[", "consts", ".",...
Add the "Split", "Join" classification, if the element qualifies for. :param element: an element from BPMN diagram, :param classification_labels: list of labels attached to the element, :param nodes_classification: dictionary of classification labels. Key - node id. Value - a list of labels.
[ "Add", "the", "Split", "Join", "classification", "if", "the", "element", "qualifies", "for", "." ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_import_utils.py#L117-L131
20,650
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_metrics.py
get_all_gateways
def get_all_gateways(bpmn_graph): """ Returns a list with all gateways in diagram :param bpmn_graph: an instance of BpmnDiagramGraph representing BPMN model. :return: a list with all gateways in diagram """ gateways = filter(lambda node: node[1]['type'] in GATEWAY_TYPES, bpmn_graph.get_nodes()) return gateways
python
def get_all_gateways(bpmn_graph): gateways = filter(lambda node: node[1]['type'] in GATEWAY_TYPES, bpmn_graph.get_nodes()) return gateways
[ "def", "get_all_gateways", "(", "bpmn_graph", ")", ":", "gateways", "=", "filter", "(", "lambda", "node", ":", "node", "[", "1", "]", "[", "'type'", "]", "in", "GATEWAY_TYPES", ",", "bpmn_graph", ".", "get_nodes", "(", ")", ")", "return", "gateways" ]
Returns a list with all gateways in diagram :param bpmn_graph: an instance of BpmnDiagramGraph representing BPMN model. :return: a list with all gateways in diagram
[ "Returns", "a", "list", "with", "all", "gateways", "in", "diagram" ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_metrics.py#L29-L38
20,651
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_metrics.py
all_control_flow_elements_count
def all_control_flow_elements_count(bpmn_graph): """ Returns the total count of all control flow elements in the BPMNDiagramGraph instance. :param bpmn_graph: an instance of BpmnDiagramGraph representing BPMN model. :return: total count of the control flow elements in the BPMNDiagramGraph instance """ gateway_counts = get_gateway_counts(bpmn_graph) events_counts = get_events_counts(bpmn_graph) control_flow_elements_counts = gateway_counts.copy() control_flow_elements_counts.update(events_counts) return sum([ count for name, count in control_flow_elements_counts.items() ])
python
def all_control_flow_elements_count(bpmn_graph): gateway_counts = get_gateway_counts(bpmn_graph) events_counts = get_events_counts(bpmn_graph) control_flow_elements_counts = gateway_counts.copy() control_flow_elements_counts.update(events_counts) return sum([ count for name, count in control_flow_elements_counts.items() ])
[ "def", "all_control_flow_elements_count", "(", "bpmn_graph", ")", ":", "gateway_counts", "=", "get_gateway_counts", "(", "bpmn_graph", ")", "events_counts", "=", "get_events_counts", "(", "bpmn_graph", ")", "control_flow_elements_counts", "=", "gateway_counts", ".", "copy...
Returns the total count of all control flow elements in the BPMNDiagramGraph instance. :param bpmn_graph: an instance of BpmnDiagramGraph representing BPMN model. :return: total count of the control flow elements in the BPMNDiagramGraph instance
[ "Returns", "the", "total", "count", "of", "all", "control", "flow", "elements", "in", "the", "BPMNDiagramGraph", "instance", "." ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_metrics.py#L111-L128
20,652
KrzyHonk/bpmn-python
bpmn_python/bpmn_process_csv_export.py
BpmnDiagramGraphCsvExport.export_process_to_csv
def export_process_to_csv(bpmn_diagram, directory, filename): """ Root method of CSV export functionality. :param bpmn_diagram: an instance of BpmnDiagramGraph class, :param directory: a string object, which is a path of output directory, :param filename: a string object, which is a name of output file. """ nodes = copy.deepcopy(bpmn_diagram.get_nodes()) start_nodes = [] export_elements = [] for node in nodes: incoming_list = node[1].get(consts.Consts.incoming_flow) if len(incoming_list) == 0: start_nodes.append(node) if len(start_nodes) != 1: raise bpmn_exception.BpmnPythonError("Exporting to CSV format accepts only one start event") nodes_classification = utils.BpmnImportUtils.generate_nodes_clasification(bpmn_diagram) start_node = start_nodes.pop() BpmnDiagramGraphCsvExport.export_node(bpmn_diagram, export_elements, start_node, nodes_classification) try: os.makedirs(directory) except OSError as exception: if exception.errno != errno.EEXIST: raise file_object = open(directory + filename, "w") file_object.write("Order,Activity,Condition,Who,Subprocess,Terminated\n") BpmnDiagramGraphCsvExport.write_export_node_to_file(file_object, export_elements) file_object.close()
python
def export_process_to_csv(bpmn_diagram, directory, filename): nodes = copy.deepcopy(bpmn_diagram.get_nodes()) start_nodes = [] export_elements = [] for node in nodes: incoming_list = node[1].get(consts.Consts.incoming_flow) if len(incoming_list) == 0: start_nodes.append(node) if len(start_nodes) != 1: raise bpmn_exception.BpmnPythonError("Exporting to CSV format accepts only one start event") nodes_classification = utils.BpmnImportUtils.generate_nodes_clasification(bpmn_diagram) start_node = start_nodes.pop() BpmnDiagramGraphCsvExport.export_node(bpmn_diagram, export_elements, start_node, nodes_classification) try: os.makedirs(directory) except OSError as exception: if exception.errno != errno.EEXIST: raise file_object = open(directory + filename, "w") file_object.write("Order,Activity,Condition,Who,Subprocess,Terminated\n") BpmnDiagramGraphCsvExport.write_export_node_to_file(file_object, export_elements) file_object.close()
[ "def", "export_process_to_csv", "(", "bpmn_diagram", ",", "directory", ",", "filename", ")", ":", "nodes", "=", "copy", ".", "deepcopy", "(", "bpmn_diagram", ".", "get_nodes", "(", ")", ")", "start_nodes", "=", "[", "]", "export_elements", "=", "[", "]", "...
Root method of CSV export functionality. :param bpmn_diagram: an instance of BpmnDiagramGraph class, :param directory: a string object, which is a path of output directory, :param filename: a string object, which is a name of output file.
[ "Root", "method", "of", "CSV", "export", "functionality", "." ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_process_csv_export.py#L44-L75
20,653
KrzyHonk/bpmn-python
bpmn_python/bpmn_process_csv_export.py
BpmnDiagramGraphCsvExport.export_node
def export_node(bpmn_graph, export_elements, node, nodes_classification, order=0, prefix="", condition="", who="", add_join=False): """ General method for node exporting :param bpmn_graph: an instance of BpmnDiagramGraph class, :param export_elements: a dictionary object. The key is a node ID, value is a dictionary of parameters that will be used in exported CSV document, :param node: networkx.Node object, :param nodes_classification: dictionary of classification labels. Key - node id. Value - a list of labels, :param order: the order param of exported node, :param prefix: the prefix of exported node - if the task appears after some gateway, the prefix will identify the branch :param condition: the condition param of exported node, :param who: the condition param of exported node, :param add_join: boolean flag. Used to indicate if "Join" element should be added to CSV. :return: None or the next node object if the exported node was a gateway join. """ node_type = node[1][consts.Consts.type] if node_type == consts.Consts.start_event: return BpmnDiagramGraphCsvExport.export_start_event(bpmn_graph, export_elements, node, nodes_classification, order=order, prefix=prefix, condition=condition, who=who) elif node_type == consts.Consts.end_event: return BpmnDiagramGraphCsvExport.export_end_event(export_elements, node, order=order, prefix=prefix, condition=condition, who=who) else: return BpmnDiagramGraphCsvExport.export_element(bpmn_graph, export_elements, node, nodes_classification, order=order, prefix=prefix, condition=condition, who=who, add_join=add_join)
python
def export_node(bpmn_graph, export_elements, node, nodes_classification, order=0, prefix="", condition="", who="", add_join=False): node_type = node[1][consts.Consts.type] if node_type == consts.Consts.start_event: return BpmnDiagramGraphCsvExport.export_start_event(bpmn_graph, export_elements, node, nodes_classification, order=order, prefix=prefix, condition=condition, who=who) elif node_type == consts.Consts.end_event: return BpmnDiagramGraphCsvExport.export_end_event(export_elements, node, order=order, prefix=prefix, condition=condition, who=who) else: return BpmnDiagramGraphCsvExport.export_element(bpmn_graph, export_elements, node, nodes_classification, order=order, prefix=prefix, condition=condition, who=who, add_join=add_join)
[ "def", "export_node", "(", "bpmn_graph", ",", "export_elements", ",", "node", ",", "nodes_classification", ",", "order", "=", "0", ",", "prefix", "=", "\"\"", ",", "condition", "=", "\"\"", ",", "who", "=", "\"\"", ",", "add_join", "=", "False", ")", ":"...
General method for node exporting :param bpmn_graph: an instance of BpmnDiagramGraph class, :param export_elements: a dictionary object. The key is a node ID, value is a dictionary of parameters that will be used in exported CSV document, :param node: networkx.Node object, :param nodes_classification: dictionary of classification labels. Key - node id. Value - a list of labels, :param order: the order param of exported node, :param prefix: the prefix of exported node - if the task appears after some gateway, the prefix will identify the branch :param condition: the condition param of exported node, :param who: the condition param of exported node, :param add_join: boolean flag. Used to indicate if "Join" element should be added to CSV. :return: None or the next node object if the exported node was a gateway join.
[ "General", "method", "for", "node", "exporting" ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_process_csv_export.py#L78-L107
20,654
KrzyHonk/bpmn-python
bpmn_python/bpmn_process_csv_export.py
BpmnDiagramGraphCsvExport.export_start_event
def export_start_event(bpmn_graph, export_elements, node, nodes_classification, order=0, prefix="", condition="", who=""): """ Start event export :param bpmn_graph: an instance of BpmnDiagramGraph class, :param export_elements: a dictionary object. The key is a node ID, value is a dictionary of parameters that will be used in exported CSV document, :param node: networkx.Node object, :param order: the order param of exported node, :param nodes_classification: dictionary of classification labels. Key - node id. Value - a list of labels, :param prefix: the prefix of exported node - if the task appears after some gateway, the prefix will identify the branch :param condition: the condition param of exported node, :param who: the condition param of exported node, :return: None or the next node object if the exported node was a gateway join. """ # Assuming that there is only one event definition event_definitions = node[1].get(consts.Consts.event_definitions) if event_definitions is not None and len(event_definitions) > 0: event_definition = node[1][consts.Consts.event_definitions][0] else: event_definition = None if event_definition is None: activity = node[1][consts.Consts.node_name] elif event_definition[consts.Consts.definition_type] == "messageEventDefinition": activity = "message " + node[1][consts.Consts.node_name] elif event_definition[consts.Consts.definition_type] == "timerEventDefinition": activity = "timer " + node[1][consts.Consts.node_name] else: activity = node[1][consts.Consts.node_name] export_elements.append({"Order": prefix + str(order), "Activity": activity, "Condition": condition, "Who": who, "Subprocess": "", "Terminated": ""}) outgoing_flow_id = node[1][consts.Consts.outgoing_flow][0] outgoing_flow = bpmn_graph.get_flow_by_id(outgoing_flow_id) outgoing_node = bpmn_graph.get_node_by_id(outgoing_flow[2][consts.Consts.target_ref]) return BpmnDiagramGraphCsvExport.export_node(bpmn_graph, export_elements, outgoing_node, nodes_classification, order + 1, prefix, who)
python
def export_start_event(bpmn_graph, export_elements, node, nodes_classification, order=0, prefix="", condition="", who=""): # Assuming that there is only one event definition event_definitions = node[1].get(consts.Consts.event_definitions) if event_definitions is not None and len(event_definitions) > 0: event_definition = node[1][consts.Consts.event_definitions][0] else: event_definition = None if event_definition is None: activity = node[1][consts.Consts.node_name] elif event_definition[consts.Consts.definition_type] == "messageEventDefinition": activity = "message " + node[1][consts.Consts.node_name] elif event_definition[consts.Consts.definition_type] == "timerEventDefinition": activity = "timer " + node[1][consts.Consts.node_name] else: activity = node[1][consts.Consts.node_name] export_elements.append({"Order": prefix + str(order), "Activity": activity, "Condition": condition, "Who": who, "Subprocess": "", "Terminated": ""}) outgoing_flow_id = node[1][consts.Consts.outgoing_flow][0] outgoing_flow = bpmn_graph.get_flow_by_id(outgoing_flow_id) outgoing_node = bpmn_graph.get_node_by_id(outgoing_flow[2][consts.Consts.target_ref]) return BpmnDiagramGraphCsvExport.export_node(bpmn_graph, export_elements, outgoing_node, nodes_classification, order + 1, prefix, who)
[ "def", "export_start_event", "(", "bpmn_graph", ",", "export_elements", ",", "node", ",", "nodes_classification", ",", "order", "=", "0", ",", "prefix", "=", "\"\"", ",", "condition", "=", "\"\"", ",", "who", "=", "\"\"", ")", ":", "# Assuming that there is on...
Start event export :param bpmn_graph: an instance of BpmnDiagramGraph class, :param export_elements: a dictionary object. The key is a node ID, value is a dictionary of parameters that will be used in exported CSV document, :param node: networkx.Node object, :param order: the order param of exported node, :param nodes_classification: dictionary of classification labels. Key - node id. Value - a list of labels, :param prefix: the prefix of exported node - if the task appears after some gateway, the prefix will identify the branch :param condition: the condition param of exported node, :param who: the condition param of exported node, :return: None or the next node object if the exported node was a gateway join.
[ "Start", "event", "export" ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_process_csv_export.py#L208-L249
20,655
KrzyHonk/bpmn-python
bpmn_python/bpmn_process_csv_export.py
BpmnDiagramGraphCsvExport.export_end_event
def export_end_event(export_elements, node, order=0, prefix="", condition="", who=""): """ End event export :param export_elements: a dictionary object. The key is a node ID, value is a dictionary of parameters that will be used in exported CSV document, :param node: networkx.Node object, :param order: the order param of exported node, :param prefix: the prefix of exported node - if the task appears after some gateway, the prefix will identify the branch :param condition: the condition param of exported node, :param who: the condition param of exported node, :return: None or the next node object if the exported node was a gateway join. """ # Assuming that there is only one event definition event_definitions = node[1].get(consts.Consts.event_definitions) if event_definitions is not None and len(event_definitions) > 0: event_definition = node[1][consts.Consts.event_definitions][0] else: event_definition = None if event_definition is None: activity = node[1][consts.Consts.node_name] elif event_definition[consts.Consts.definition_type] == "messageEventDefinition": activity = "message " + node[1][consts.Consts.node_name] else: activity = node[1][consts.Consts.node_name] export_elements.append({"Order": prefix + str(order), "Activity": activity, "Condition": condition, "Who": who, "Subprocess": "", "Terminated": "yes"}) # No outgoing elements for EndEvent return None
python
def export_end_event(export_elements, node, order=0, prefix="", condition="", who=""): # Assuming that there is only one event definition event_definitions = node[1].get(consts.Consts.event_definitions) if event_definitions is not None and len(event_definitions) > 0: event_definition = node[1][consts.Consts.event_definitions][0] else: event_definition = None if event_definition is None: activity = node[1][consts.Consts.node_name] elif event_definition[consts.Consts.definition_type] == "messageEventDefinition": activity = "message " + node[1][consts.Consts.node_name] else: activity = node[1][consts.Consts.node_name] export_elements.append({"Order": prefix + str(order), "Activity": activity, "Condition": condition, "Who": who, "Subprocess": "", "Terminated": "yes"}) # No outgoing elements for EndEvent return None
[ "def", "export_end_event", "(", "export_elements", ",", "node", ",", "order", "=", "0", ",", "prefix", "=", "\"\"", ",", "condition", "=", "\"\"", ",", "who", "=", "\"\"", ")", ":", "# Assuming that there is only one event definition", "event_definitions", "=", ...
End event export :param export_elements: a dictionary object. The key is a node ID, value is a dictionary of parameters that will be used in exported CSV document, :param node: networkx.Node object, :param order: the order param of exported node, :param prefix: the prefix of exported node - if the task appears after some gateway, the prefix will identify the branch :param condition: the condition param of exported node, :param who: the condition param of exported node, :return: None or the next node object if the exported node was a gateway join.
[ "End", "event", "export" ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_process_csv_export.py#L252-L284
20,656
KrzyHonk/bpmn-python
bpmn_python/bpmn_process_csv_export.py
BpmnDiagramGraphCsvExport.write_export_node_to_file
def write_export_node_to_file(file_object, export_elements): """ Exporting process to CSV file :param file_object: object of File class, :param export_elements: a dictionary object. The key is a node ID, value is a dictionary of parameters that will be used in exported CSV document. """ for export_element in export_elements: # Order,Activity,Condition,Who,Subprocess,Terminated file_object.write( export_element["Order"] + "," + export_element["Activity"] + "," + export_element["Condition"] + "," + export_element["Who"] + "," + export_element["Subprocess"] + "," + export_element["Terminated"] + "\n")
python
def write_export_node_to_file(file_object, export_elements): for export_element in export_elements: # Order,Activity,Condition,Who,Subprocess,Terminated file_object.write( export_element["Order"] + "," + export_element["Activity"] + "," + export_element["Condition"] + "," + export_element["Who"] + "," + export_element["Subprocess"] + "," + export_element["Terminated"] + "\n")
[ "def", "write_export_node_to_file", "(", "file_object", ",", "export_elements", ")", ":", "for", "export_element", "in", "export_elements", ":", "# Order,Activity,Condition,Who,Subprocess,Terminated", "file_object", ".", "write", "(", "export_element", "[", "\"Order\"", "]"...
Exporting process to CSV file :param file_object: object of File class, :param export_elements: a dictionary object. The key is a node ID, value is a dictionary of parameters that will be used in exported CSV document.
[ "Exporting", "process", "to", "CSV", "file" ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_process_csv_export.py#L287-L299
20,657
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_visualizer.py
visualize_diagram
def visualize_diagram(bpmn_diagram): """ Shows a simple visualization of diagram :param bpmn_diagram: an instance of BPMNDiagramGraph class. """ g = bpmn_diagram.diagram_graph pos = bpmn_diagram.get_nodes_positions() nx.draw_networkx_nodes(g, pos, node_shape='s', node_color='white', nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.task)) nx.draw_networkx_nodes(g, pos, node_shape='s', node_color='white', nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.subprocess)) nx.draw_networkx_nodes(g, pos, node_shape='d', node_color='white', nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.complex_gateway)) nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white', nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.event_based_gateway)) nx.draw_networkx_nodes(g, pos, node_shape='d', node_color='white', nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.inclusive_gateway)) nx.draw_networkx_nodes(g, pos, node_shape='d', node_color='white', nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.exclusive_gateway)) nx.draw_networkx_nodes(g, pos, node_shape='d', node_color='white', nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.parallel_gateway)) nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white', nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.start_event)) nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white', nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.intermediate_catch_event)) nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white', nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.end_event)) nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white', nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.intermediate_throw_event)) node_labels = {} for node in g.nodes(data=True): node_labels[node[0]] = node[1].get(consts.Consts.node_name) nx.draw_networkx_labels(g, pos, node_labels) nx.draw_networkx_edges(g, pos) edge_labels = {} for edge in g.edges(data=True): edge_labels[(edge[0], edge[1])] = edge[2].get(consts.Consts.name) nx.draw_networkx_edge_labels(g, pos, edge_labels) plt.show()
python
def visualize_diagram(bpmn_diagram): g = bpmn_diagram.diagram_graph pos = bpmn_diagram.get_nodes_positions() nx.draw_networkx_nodes(g, pos, node_shape='s', node_color='white', nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.task)) nx.draw_networkx_nodes(g, pos, node_shape='s', node_color='white', nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.subprocess)) nx.draw_networkx_nodes(g, pos, node_shape='d', node_color='white', nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.complex_gateway)) nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white', nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.event_based_gateway)) nx.draw_networkx_nodes(g, pos, node_shape='d', node_color='white', nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.inclusive_gateway)) nx.draw_networkx_nodes(g, pos, node_shape='d', node_color='white', nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.exclusive_gateway)) nx.draw_networkx_nodes(g, pos, node_shape='d', node_color='white', nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.parallel_gateway)) nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white', nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.start_event)) nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white', nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.intermediate_catch_event)) nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white', nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.end_event)) nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white', nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.intermediate_throw_event)) node_labels = {} for node in g.nodes(data=True): node_labels[node[0]] = node[1].get(consts.Consts.node_name) nx.draw_networkx_labels(g, pos, node_labels) nx.draw_networkx_edges(g, pos) edge_labels = {} for edge in g.edges(data=True): edge_labels[(edge[0], edge[1])] = edge[2].get(consts.Consts.name) nx.draw_networkx_edge_labels(g, pos, edge_labels) plt.show()
[ "def", "visualize_diagram", "(", "bpmn_diagram", ")", ":", "g", "=", "bpmn_diagram", ".", "diagram_graph", "pos", "=", "bpmn_diagram", ".", "get_nodes_positions", "(", ")", "nx", ".", "draw_networkx_nodes", "(", "g", ",", "pos", ",", "node_shape", "=", "'s'", ...
Shows a simple visualization of diagram :param bpmn_diagram: an instance of BPMNDiagramGraph class.
[ "Shows", "a", "simple", "visualization", "of", "diagram" ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_visualizer.py#L13-L56
20,658
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_visualizer.py
bpmn_diagram_to_png
def bpmn_diagram_to_png(bpmn_diagram, file_name): """ Create a png picture for given diagram :param bpmn_diagram: an instance of BPMNDiagramGraph class, :param file_name: name of generated file. """ g = bpmn_diagram.diagram_graph graph = pydotplus.Dot() for node in g.nodes(data=True): if node[1].get(consts.Consts.type) == consts.Consts.task: n = pydotplus.Node(name=node[0], shape="box", style="rounded", label=node[1].get(consts.Consts.node_name)) elif node[1].get(consts.Consts.type) == consts.Consts.exclusive_gateway: n = pydotplus.Node(name=node[0], shape="diamond", label=node[1].get(consts.Consts.node_name)) else: n = pydotplus.Node(name=node[0], label=node[1].get(consts.Consts.node_name)) graph.add_node(n) for edge in g.edges(data=True): e = pydotplus.Edge(src=edge[0], dst=edge[1], label=edge[2].get(consts.Consts.name)) graph.add_edge(e) graph.write(file_name + ".png", format='png')
python
def bpmn_diagram_to_png(bpmn_diagram, file_name): g = bpmn_diagram.diagram_graph graph = pydotplus.Dot() for node in g.nodes(data=True): if node[1].get(consts.Consts.type) == consts.Consts.task: n = pydotplus.Node(name=node[0], shape="box", style="rounded", label=node[1].get(consts.Consts.node_name)) elif node[1].get(consts.Consts.type) == consts.Consts.exclusive_gateway: n = pydotplus.Node(name=node[0], shape="diamond", label=node[1].get(consts.Consts.node_name)) else: n = pydotplus.Node(name=node[0], label=node[1].get(consts.Consts.node_name)) graph.add_node(n) for edge in g.edges(data=True): e = pydotplus.Edge(src=edge[0], dst=edge[1], label=edge[2].get(consts.Consts.name)) graph.add_edge(e) graph.write(file_name + ".png", format='png')
[ "def", "bpmn_diagram_to_png", "(", "bpmn_diagram", ",", "file_name", ")", ":", "g", "=", "bpmn_diagram", ".", "diagram_graph", "graph", "=", "pydotplus", ".", "Dot", "(", ")", "for", "node", "in", "g", ".", "nodes", "(", "data", "=", "True", ")", ":", ...
Create a png picture for given diagram :param bpmn_diagram: an instance of BPMNDiagramGraph class, :param file_name: name of generated file.
[ "Create", "a", "png", "picture", "for", "given", "diagram" ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_visualizer.py#L70-L94
20,659
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_rep.py
BpmnDiagramGraph.get_node_by_id
def get_node_by_id(self, node_id): """ Gets a node with requested ID. Returns a tuple, where first value is node ID, second - a dictionary of all node attributes. :param node_id: string with ID of node. """ tmp_nodes = self.diagram_graph.nodes(data=True) for node in tmp_nodes: if node[0] == node_id: return node
python
def get_node_by_id(self, node_id): tmp_nodes = self.diagram_graph.nodes(data=True) for node in tmp_nodes: if node[0] == node_id: return node
[ "def", "get_node_by_id", "(", "self", ",", "node_id", ")", ":", "tmp_nodes", "=", "self", ".", "diagram_graph", ".", "nodes", "(", "data", "=", "True", ")", "for", "node", "in", "tmp_nodes", ":", "if", "node", "[", "0", "]", "==", "node_id", ":", "re...
Gets a node with requested ID. Returns a tuple, where first value is node ID, second - a dictionary of all node attributes. :param node_id: string with ID of node.
[ "Gets", "a", "node", "with", "requested", "ID", ".", "Returns", "a", "tuple", "where", "first", "value", "is", "node", "ID", "second", "-", "a", "dictionary", "of", "all", "node", "attributes", "." ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_rep.py#L136-L146
20,660
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_rep.py
BpmnDiagramGraph.get_nodes_id_list_by_type
def get_nodes_id_list_by_type(self, node_type): """ Get a list of node's id by requested type. Returns a list of ids :param node_type: string with valid BPMN XML tag name (e.g. 'task', 'sequenceFlow'). """ tmp_nodes = self.diagram_graph.nodes(data=True) id_list = [] for node in tmp_nodes: if node[1][consts.Consts.type] == node_type: id_list.append(node[0]) return id_list
python
def get_nodes_id_list_by_type(self, node_type): tmp_nodes = self.diagram_graph.nodes(data=True) id_list = [] for node in tmp_nodes: if node[1][consts.Consts.type] == node_type: id_list.append(node[0]) return id_list
[ "def", "get_nodes_id_list_by_type", "(", "self", ",", "node_type", ")", ":", "tmp_nodes", "=", "self", ".", "diagram_graph", ".", "nodes", "(", "data", "=", "True", ")", "id_list", "=", "[", "]", "for", "node", "in", "tmp_nodes", ":", "if", "node", "[", ...
Get a list of node's id by requested type. Returns a list of ids :param node_type: string with valid BPMN XML tag name (e.g. 'task', 'sequenceFlow').
[ "Get", "a", "list", "of", "node", "s", "id", "by", "requested", "type", ".", "Returns", "a", "list", "of", "ids" ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_rep.py#L148-L160
20,661
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_rep.py
BpmnDiagramGraph.add_process_to_diagram
def add_process_to_diagram(self, process_name="", process_is_closed=False, process_is_executable=False, process_type="None"): """ Adds a new process to diagram and corresponding participant process, diagram and plane Accepts a user-defined values for following attributes: (Process element) - isClosed - default value false, - isExecutable - default value false, - processType - default value None. :param process_name: string obejct, process name. Default value - empty string, :param process_is_closed: boolean type. Represents a user-defined value of 'process' element attribute 'isClosed'. Default value false, :param process_is_executable: boolean type. Represents a user-defined value of 'process' element attribute 'isExecutable'. Default value false, :param process_type: string type. Represents a user-defined value of 'process' element attribute 'procesType'. Default value "None", """ plane_id = BpmnDiagramGraph.id_prefix + str(uuid.uuid4()) process_id = BpmnDiagramGraph.id_prefix + str(uuid.uuid4()) self.process_elements[process_id] = {consts.Consts.name: process_name, consts.Consts.is_closed: "true" if process_is_closed else "false", consts.Consts.is_executable: "true" if process_is_executable else "false", consts.Consts.process_type: process_type} self.plane_attributes[consts.Consts.id] = plane_id self.plane_attributes[consts.Consts.bpmn_element] = process_id return process_id
python
def add_process_to_diagram(self, process_name="", process_is_closed=False, process_is_executable=False, process_type="None"): plane_id = BpmnDiagramGraph.id_prefix + str(uuid.uuid4()) process_id = BpmnDiagramGraph.id_prefix + str(uuid.uuid4()) self.process_elements[process_id] = {consts.Consts.name: process_name, consts.Consts.is_closed: "true" if process_is_closed else "false", consts.Consts.is_executable: "true" if process_is_executable else "false", consts.Consts.process_type: process_type} self.plane_attributes[consts.Consts.id] = plane_id self.plane_attributes[consts.Consts.bpmn_element] = process_id return process_id
[ "def", "add_process_to_diagram", "(", "self", ",", "process_name", "=", "\"\"", ",", "process_is_closed", "=", "False", ",", "process_is_executable", "=", "False", ",", "process_type", "=", "\"None\"", ")", ":", "plane_id", "=", "BpmnDiagramGraph", ".", "id_prefix...
Adds a new process to diagram and corresponding participant process, diagram and plane Accepts a user-defined values for following attributes: (Process element) - isClosed - default value false, - isExecutable - default value false, - processType - default value None. :param process_name: string obejct, process name. Default value - empty string, :param process_is_closed: boolean type. Represents a user-defined value of 'process' element attribute 'isClosed'. Default value false, :param process_is_executable: boolean type. Represents a user-defined value of 'process' element attribute 'isExecutable'. Default value false, :param process_type: string type. Represents a user-defined value of 'process' element attribute 'procesType'. Default value "None",
[ "Adds", "a", "new", "process", "to", "diagram", "and", "corresponding", "participant", "process", "diagram", "and", "plane" ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_rep.py#L214-L244
20,662
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_rep.py
BpmnDiagramGraph.add_flow_node_to_diagram
def add_flow_node_to_diagram(self, process_id, node_type, name, node_id=None): """ Helper function that adds a new Flow Node to diagram. It is used to add a new node of specified type. Adds a basic information inherited from Flow Node type. :param process_id: string object. ID of parent process, :param node_type: string object. Represents type of BPMN node passed to method, :param name: string object. Name of the node, :param node_id: string object. ID of node. Default value - None. """ if node_id is None: node_id = BpmnDiagramGraph.id_prefix + str(uuid.uuid4()) self.diagram_graph.add_node(node_id) self.diagram_graph.node[node_id][consts.Consts.id] = node_id self.diagram_graph.node[node_id][consts.Consts.type] = node_type self.diagram_graph.node[node_id][consts.Consts.node_name] = name self.diagram_graph.node[node_id][consts.Consts.incoming_flow] = [] self.diagram_graph.node[node_id][consts.Consts.outgoing_flow] = [] self.diagram_graph.node[node_id][consts.Consts.process] = process_id # Adding some dummy constant values self.diagram_graph.node[node_id][consts.Consts.width] = "100" self.diagram_graph.node[node_id][consts.Consts.height] = "100" self.diagram_graph.node[node_id][consts.Consts.x] = "100" self.diagram_graph.node[node_id][consts.Consts.y] = "100" return node_id, self.diagram_graph.node[node_id]
python
def add_flow_node_to_diagram(self, process_id, node_type, name, node_id=None): if node_id is None: node_id = BpmnDiagramGraph.id_prefix + str(uuid.uuid4()) self.diagram_graph.add_node(node_id) self.diagram_graph.node[node_id][consts.Consts.id] = node_id self.diagram_graph.node[node_id][consts.Consts.type] = node_type self.diagram_graph.node[node_id][consts.Consts.node_name] = name self.diagram_graph.node[node_id][consts.Consts.incoming_flow] = [] self.diagram_graph.node[node_id][consts.Consts.outgoing_flow] = [] self.diagram_graph.node[node_id][consts.Consts.process] = process_id # Adding some dummy constant values self.diagram_graph.node[node_id][consts.Consts.width] = "100" self.diagram_graph.node[node_id][consts.Consts.height] = "100" self.diagram_graph.node[node_id][consts.Consts.x] = "100" self.diagram_graph.node[node_id][consts.Consts.y] = "100" return node_id, self.diagram_graph.node[node_id]
[ "def", "add_flow_node_to_diagram", "(", "self", ",", "process_id", ",", "node_type", ",", "name", ",", "node_id", "=", "None", ")", ":", "if", "node_id", "is", "None", ":", "node_id", "=", "BpmnDiagramGraph", ".", "id_prefix", "+", "str", "(", "uuid", ".",...
Helper function that adds a new Flow Node to diagram. It is used to add a new node of specified type. Adds a basic information inherited from Flow Node type. :param process_id: string object. ID of parent process, :param node_type: string object. Represents type of BPMN node passed to method, :param name: string object. Name of the node, :param node_id: string object. ID of node. Default value - None.
[ "Helper", "function", "that", "adds", "a", "new", "Flow", "Node", "to", "diagram", ".", "It", "is", "used", "to", "add", "a", "new", "node", "of", "specified", "type", ".", "Adds", "a", "basic", "information", "inherited", "from", "Flow", "Node", "type",...
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_rep.py#L246-L271
20,663
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_rep.py
BpmnDiagramGraph.add_start_event_to_diagram
def add_start_event_to_diagram(self, process_id, start_event_name="", start_event_definition=None, parallel_multiple=False, is_interrupting=True, node_id=None): """ Adds a StartEvent element to BPMN diagram. User-defined attributes: - name - parallel_multiple - is_interrupting - event definition (creates a special type of start event). Supported event definitions - * 'message': 'messageEventDefinition', * 'timer': 'timerEventDefinition', * 'signal': 'signalEventDefinition', * 'conditional': 'conditionalEventDefinition', * 'escalation': 'escalationEventDefinition'. :param process_id: string object. ID of parent process, :param start_event_name: string object. Name of start event, :param start_event_definition: list of event definitions. By default - empty, :param parallel_multiple: boolean value for attribute "parallelMultiple", :param is_interrupting: boolean value for attribute "isInterrupting, :param node_id: string object. ID of node. Default value - None. :return: a tuple, where first value is startEvent ID, second a reference to created object. """ start_event_id, start_event = self.add_flow_node_to_diagram(process_id, consts.Consts.start_event, start_event_name, node_id) self.diagram_graph.node[start_event_id][consts.Consts.parallel_multiple] = \ "true" if parallel_multiple else "false" self.diagram_graph.node[start_event_id][consts.Consts.is_interrupting] = "true" if is_interrupting else "false" start_event_definitions = {"message": "messageEventDefinition", "timer": "timerEventDefinition", "conditional": "conditionalEventDefinition", "signal": "signalEventDefinition", "escalation": "escalationEventDefinition"} event_def_list = [] if start_event_definition == "message": event_def_list.append(BpmnDiagramGraph.add_event_definition_element("message", start_event_definitions)) elif start_event_definition == "timer": event_def_list.append(BpmnDiagramGraph.add_event_definition_element("timer", start_event_definitions)) elif start_event_definition == "conditional": event_def_list.append(BpmnDiagramGraph.add_event_definition_element("conditional", start_event_definitions)) elif start_event_definition == "signal": event_def_list.append(BpmnDiagramGraph.add_event_definition_element("signal", start_event_definitions)) elif start_event_definition == "escalation": event_def_list.append(BpmnDiagramGraph.add_event_definition_element("escalation", start_event_definitions)) self.diagram_graph.node[start_event_id][consts.Consts.event_definitions] = event_def_list return start_event_id, start_event
python
def add_start_event_to_diagram(self, process_id, start_event_name="", start_event_definition=None, parallel_multiple=False, is_interrupting=True, node_id=None): start_event_id, start_event = self.add_flow_node_to_diagram(process_id, consts.Consts.start_event, start_event_name, node_id) self.diagram_graph.node[start_event_id][consts.Consts.parallel_multiple] = \ "true" if parallel_multiple else "false" self.diagram_graph.node[start_event_id][consts.Consts.is_interrupting] = "true" if is_interrupting else "false" start_event_definitions = {"message": "messageEventDefinition", "timer": "timerEventDefinition", "conditional": "conditionalEventDefinition", "signal": "signalEventDefinition", "escalation": "escalationEventDefinition"} event_def_list = [] if start_event_definition == "message": event_def_list.append(BpmnDiagramGraph.add_event_definition_element("message", start_event_definitions)) elif start_event_definition == "timer": event_def_list.append(BpmnDiagramGraph.add_event_definition_element("timer", start_event_definitions)) elif start_event_definition == "conditional": event_def_list.append(BpmnDiagramGraph.add_event_definition_element("conditional", start_event_definitions)) elif start_event_definition == "signal": event_def_list.append(BpmnDiagramGraph.add_event_definition_element("signal", start_event_definitions)) elif start_event_definition == "escalation": event_def_list.append(BpmnDiagramGraph.add_event_definition_element("escalation", start_event_definitions)) self.diagram_graph.node[start_event_id][consts.Consts.event_definitions] = event_def_list return start_event_id, start_event
[ "def", "add_start_event_to_diagram", "(", "self", ",", "process_id", ",", "start_event_name", "=", "\"\"", ",", "start_event_definition", "=", "None", ",", "parallel_multiple", "=", "False", ",", "is_interrupting", "=", "True", ",", "node_id", "=", "None", ")", ...
Adds a StartEvent element to BPMN diagram. User-defined attributes: - name - parallel_multiple - is_interrupting - event definition (creates a special type of start event). Supported event definitions - * 'message': 'messageEventDefinition', * 'timer': 'timerEventDefinition', * 'signal': 'signalEventDefinition', * 'conditional': 'conditionalEventDefinition', * 'escalation': 'escalationEventDefinition'. :param process_id: string object. ID of parent process, :param start_event_name: string object. Name of start event, :param start_event_definition: list of event definitions. By default - empty, :param parallel_multiple: boolean value for attribute "parallelMultiple", :param is_interrupting: boolean value for attribute "isInterrupting, :param node_id: string object. ID of node. Default value - None. :return: a tuple, where first value is startEvent ID, second a reference to created object.
[ "Adds", "a", "StartEvent", "element", "to", "BPMN", "diagram", "." ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_rep.py#L312-L359
20,664
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_rep.py
BpmnDiagramGraph.add_inclusive_gateway_to_diagram
def add_inclusive_gateway_to_diagram(self, process_id, gateway_name="", gateway_direction="Unspecified", default=None, node_id=None): """ Adds an inclusiveGateway element to BPMN diagram. :param process_id: string object. ID of parent process, :param gateway_name: string object. Name of inclusive gateway, :param gateway_direction: string object. Accepted values - "Unspecified", "Converging", "Diverging", "Mixed". Default value - "Unspecified", :param default: string object. ID of flow node, target of gateway default path. Default value - None, :param node_id: string object. ID of node. Default value - None. :return: a tuple, where first value is inclusiveGateway ID, second a reference to created object. """ inclusive_gateway_id, inclusive_gateway = self.add_gateway_to_diagram(process_id, consts.Consts.inclusive_gateway, gateway_name=gateway_name, gateway_direction=gateway_direction, node_id=node_id) self.diagram_graph.node[inclusive_gateway_id][consts.Consts.default] = default return inclusive_gateway_id, inclusive_gateway
python
def add_inclusive_gateway_to_diagram(self, process_id, gateway_name="", gateway_direction="Unspecified", default=None, node_id=None): inclusive_gateway_id, inclusive_gateway = self.add_gateway_to_diagram(process_id, consts.Consts.inclusive_gateway, gateway_name=gateway_name, gateway_direction=gateway_direction, node_id=node_id) self.diagram_graph.node[inclusive_gateway_id][consts.Consts.default] = default return inclusive_gateway_id, inclusive_gateway
[ "def", "add_inclusive_gateway_to_diagram", "(", "self", ",", "process_id", ",", "gateway_name", "=", "\"\"", ",", "gateway_direction", "=", "\"Unspecified\"", ",", "default", "=", "None", ",", "node_id", "=", "None", ")", ":", "inclusive_gateway_id", ",", "inclusi...
Adds an inclusiveGateway element to BPMN diagram. :param process_id: string object. ID of parent process, :param gateway_name: string object. Name of inclusive gateway, :param gateway_direction: string object. Accepted values - "Unspecified", "Converging", "Diverging", "Mixed". Default value - "Unspecified", :param default: string object. ID of flow node, target of gateway default path. Default value - None, :param node_id: string object. ID of node. Default value - None. :return: a tuple, where first value is inclusiveGateway ID, second a reference to created object.
[ "Adds", "an", "inclusiveGateway", "element", "to", "BPMN", "diagram", "." ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_rep.py#L459-L479
20,665
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_rep.py
BpmnDiagramGraph.add_parallel_gateway_to_diagram
def add_parallel_gateway_to_diagram(self, process_id, gateway_name="", gateway_direction="Unspecified", node_id=None): """ Adds an parallelGateway element to BPMN diagram. :param process_id: string object. ID of parent process, :param gateway_name: string object. Name of inclusive gateway, :param gateway_direction: string object. Accepted values - "Unspecified", "Converging", "Diverging", "Mixed". Default value - "Unspecified", :param node_id: string object. ID of node. Default value - None. :return: a tuple, where first value is parallelGateway ID, second a reference to created object. """ parallel_gateway_id, parallel_gateway = self.add_gateway_to_diagram(process_id, consts.Consts.parallel_gateway, gateway_name=gateway_name, gateway_direction=gateway_direction, node_id=node_id) return parallel_gateway_id, parallel_gateway
python
def add_parallel_gateway_to_diagram(self, process_id, gateway_name="", gateway_direction="Unspecified", node_id=None): parallel_gateway_id, parallel_gateway = self.add_gateway_to_diagram(process_id, consts.Consts.parallel_gateway, gateway_name=gateway_name, gateway_direction=gateway_direction, node_id=node_id) return parallel_gateway_id, parallel_gateway
[ "def", "add_parallel_gateway_to_diagram", "(", "self", ",", "process_id", ",", "gateway_name", "=", "\"\"", ",", "gateway_direction", "=", "\"Unspecified\"", ",", "node_id", "=", "None", ")", ":", "parallel_gateway_id", ",", "parallel_gateway", "=", "self", ".", "...
Adds an parallelGateway element to BPMN diagram. :param process_id: string object. ID of parent process, :param gateway_name: string object. Name of inclusive gateway, :param gateway_direction: string object. Accepted values - "Unspecified", "Converging", "Diverging", "Mixed". Default value - "Unspecified", :param node_id: string object. ID of node. Default value - None. :return: a tuple, where first value is parallelGateway ID, second a reference to created object.
[ "Adds", "an", "parallelGateway", "element", "to", "BPMN", "diagram", "." ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_rep.py#L481-L499
20,666
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_rep.py
BpmnDiagramGraph.get_nodes_positions
def get_nodes_positions(self): """ Getter method for nodes positions. :return: A dictionary with nodes as keys and positions as values """ nodes = self.get_nodes() output = {} for node in nodes: output[node[0]] = (float(node[1][consts.Consts.x]), float(node[1][consts.Consts.y])) return output
python
def get_nodes_positions(self): nodes = self.get_nodes() output = {} for node in nodes: output[node[0]] = (float(node[1][consts.Consts.x]), float(node[1][consts.Consts.y])) return output
[ "def", "get_nodes_positions", "(", "self", ")", ":", "nodes", "=", "self", ".", "get_nodes", "(", ")", "output", "=", "{", "}", "for", "node", "in", "nodes", ":", "output", "[", "node", "[", "0", "]", "]", "=", "(", "float", "(", "node", "[", "1"...
Getter method for nodes positions. :return: A dictionary with nodes as keys and positions as values
[ "Getter", "method", "for", "nodes", "positions", "." ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_rep.py#L539-L549
20,667
benhoyt/scandir
benchmark.py
create_tree
def create_tree(path, depth=DEPTH): """Create a directory tree at path with given depth, and NUM_DIRS and NUM_FILES at each level. """ os.mkdir(path) for i in range(NUM_FILES): filename = os.path.join(path, 'file{0:03}.txt'.format(i)) with open(filename, 'wb') as f: f.write(b'foo') if depth <= 1: return for i in range(NUM_DIRS): dirname = os.path.join(path, 'dir{0:03}'.format(i)) create_tree(dirname, depth - 1)
python
def create_tree(path, depth=DEPTH): os.mkdir(path) for i in range(NUM_FILES): filename = os.path.join(path, 'file{0:03}.txt'.format(i)) with open(filename, 'wb') as f: f.write(b'foo') if depth <= 1: return for i in range(NUM_DIRS): dirname = os.path.join(path, 'dir{0:03}'.format(i)) create_tree(dirname, depth - 1)
[ "def", "create_tree", "(", "path", ",", "depth", "=", "DEPTH", ")", ":", "os", ".", "mkdir", "(", "path", ")", "for", "i", "in", "range", "(", "NUM_FILES", ")", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'file{0:03}.tx...
Create a directory tree at path with given depth, and NUM_DIRS and NUM_FILES at each level.
[ "Create", "a", "directory", "tree", "at", "path", "with", "given", "depth", "and", "NUM_DIRS", "and", "NUM_FILES", "at", "each", "level", "." ]
982e6ba60e7165ef965567eacd7138149c9ce292
https://github.com/benhoyt/scandir/blob/982e6ba60e7165ef965567eacd7138149c9ce292/benchmark.py#L47-L60
20,668
benhoyt/scandir
benchmark.py
get_tree_size
def get_tree_size(path): """Return total size of all files in directory tree at path.""" size = 0 try: for entry in scandir.scandir(path): if entry.is_symlink(): pass elif entry.is_dir(): size += get_tree_size(os.path.join(path, entry.name)) else: size += entry.stat().st_size except OSError: pass return size
python
def get_tree_size(path): size = 0 try: for entry in scandir.scandir(path): if entry.is_symlink(): pass elif entry.is_dir(): size += get_tree_size(os.path.join(path, entry.name)) else: size += entry.stat().st_size except OSError: pass return size
[ "def", "get_tree_size", "(", "path", ")", ":", "size", "=", "0", "try", ":", "for", "entry", "in", "scandir", ".", "scandir", "(", "path", ")", ":", "if", "entry", ".", "is_symlink", "(", ")", ":", "pass", "elif", "entry", ".", "is_dir", "(", ")", ...
Return total size of all files in directory tree at path.
[ "Return", "total", "size", "of", "all", "files", "in", "directory", "tree", "at", "path", "." ]
982e6ba60e7165ef965567eacd7138149c9ce292
https://github.com/benhoyt/scandir/blob/982e6ba60e7165ef965567eacd7138149c9ce292/benchmark.py#L63-L76
20,669
ahwillia/tensortools
tensortools/operations.py
unfold
def unfold(tensor, mode): """Returns the mode-`mode` unfolding of `tensor`. Parameters ---------- tensor : ndarray mode : int Returns ------- ndarray unfolded_tensor of shape ``(tensor.shape[mode], -1)`` Author ------ Jean Kossaifi <https://github.com/tensorly> """ return np.moveaxis(tensor, mode, 0).reshape((tensor.shape[mode], -1))
python
def unfold(tensor, mode): return np.moveaxis(tensor, mode, 0).reshape((tensor.shape[mode], -1))
[ "def", "unfold", "(", "tensor", ",", "mode", ")", ":", "return", "np", ".", "moveaxis", "(", "tensor", ",", "mode", ",", "0", ")", ".", "reshape", "(", "(", "tensor", ".", "shape", "[", "mode", "]", ",", "-", "1", ")", ")" ]
Returns the mode-`mode` unfolding of `tensor`. Parameters ---------- tensor : ndarray mode : int Returns ------- ndarray unfolded_tensor of shape ``(tensor.shape[mode], -1)`` Author ------ Jean Kossaifi <https://github.com/tensorly>
[ "Returns", "the", "mode", "-", "mode", "unfolding", "of", "tensor", "." ]
f375633ec621caa96665a56205dcf932590d4a6e
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/operations.py#L11-L28
20,670
ahwillia/tensortools
tensortools/operations.py
khatri_rao
def khatri_rao(matrices): """Khatri-Rao product of a list of matrices. Parameters ---------- matrices : list of ndarray Returns ------- khatri_rao_product: matrix of shape ``(prod(n_i), m)`` where ``prod(n_i) = prod([m.shape[0] for m in matrices])`` i.e. the product of the number of rows of all the matrices in the product. Author ------ Jean Kossaifi <https://github.com/tensorly> """ n_columns = matrices[0].shape[1] n_factors = len(matrices) start = ord('a') common_dim = 'z' target = ''.join(chr(start + i) for i in range(n_factors)) source = ','.join(i+common_dim for i in target) operation = source+'->'+target+common_dim return np.einsum(operation, *matrices).reshape((-1, n_columns))
python
def khatri_rao(matrices): n_columns = matrices[0].shape[1] n_factors = len(matrices) start = ord('a') common_dim = 'z' target = ''.join(chr(start + i) for i in range(n_factors)) source = ','.join(i+common_dim for i in target) operation = source+'->'+target+common_dim return np.einsum(operation, *matrices).reshape((-1, n_columns))
[ "def", "khatri_rao", "(", "matrices", ")", ":", "n_columns", "=", "matrices", "[", "0", "]", ".", "shape", "[", "1", "]", "n_factors", "=", "len", "(", "matrices", ")", "start", "=", "ord", "(", "'a'", ")", "common_dim", "=", "'z'", "target", "=", ...
Khatri-Rao product of a list of matrices. Parameters ---------- matrices : list of ndarray Returns ------- khatri_rao_product: matrix of shape ``(prod(n_i), m)`` where ``prod(n_i) = prod([m.shape[0] for m in matrices])`` i.e. the product of the number of rows of all the matrices in the product. Author ------ Jean Kossaifi <https://github.com/tensorly>
[ "Khatri", "-", "Rao", "product", "of", "a", "list", "of", "matrices", "." ]
f375633ec621caa96665a56205dcf932590d4a6e
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/operations.py#L31-L58
20,671
ahwillia/tensortools
tensortools/utils.py
soft_cluster_factor
def soft_cluster_factor(factor): """Returns soft-clustering of data based on CP decomposition results. Parameters ---------- data : ndarray, N x R matrix of nonnegative data Datapoints are held in rows, features are held in columns Returns ------- cluster_ids : ndarray, vector of N integers in range(0, R) List of soft cluster assignments for each row of data matrix perm : ndarray, vector of N integers Permutation / ordering of the rows of data induced by the soft clustering. """ # copy factor of interest f = np.copy(factor) # cluster based on score of maximum absolute value cluster_ids = np.argmax(np.abs(f), axis=1) scores = f[range(f.shape[0]), cluster_ids] # resort within each cluster perm = [] for cluster in np.unique(cluster_ids): idx = np.where(cluster_ids == cluster)[0] perm += list(idx[np.argsort(scores[idx])][::-1]) return cluster_ids, perm
python
def soft_cluster_factor(factor): # copy factor of interest f = np.copy(factor) # cluster based on score of maximum absolute value cluster_ids = np.argmax(np.abs(f), axis=1) scores = f[range(f.shape[0]), cluster_ids] # resort within each cluster perm = [] for cluster in np.unique(cluster_ids): idx = np.where(cluster_ids == cluster)[0] perm += list(idx[np.argsort(scores[idx])][::-1]) return cluster_ids, perm
[ "def", "soft_cluster_factor", "(", "factor", ")", ":", "# copy factor of interest", "f", "=", "np", ".", "copy", "(", "factor", ")", "# cluster based on score of maximum absolute value", "cluster_ids", "=", "np", ".", "argmax", "(", "np", ".", "abs", "(", "f", "...
Returns soft-clustering of data based on CP decomposition results. Parameters ---------- data : ndarray, N x R matrix of nonnegative data Datapoints are held in rows, features are held in columns Returns ------- cluster_ids : ndarray, vector of N integers in range(0, R) List of soft cluster assignments for each row of data matrix perm : ndarray, vector of N integers Permutation / ordering of the rows of data induced by the soft clustering.
[ "Returns", "soft", "-", "clustering", "of", "data", "based", "on", "CP", "decomposition", "results", "." ]
f375633ec621caa96665a56205dcf932590d4a6e
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/utils.py#L12-L42
20,672
ahwillia/tensortools
tensortools/utils.py
hclust_linearize
def hclust_linearize(U): """Sorts the rows of a matrix by hierarchical clustering. Parameters: U (ndarray) : matrix of data Returns: prm (ndarray) : permutation of the rows """ from scipy.cluster import hierarchy Z = hierarchy.ward(U) return hierarchy.leaves_list(hierarchy.optimal_leaf_ordering(Z, U))
python
def hclust_linearize(U): from scipy.cluster import hierarchy Z = hierarchy.ward(U) return hierarchy.leaves_list(hierarchy.optimal_leaf_ordering(Z, U))
[ "def", "hclust_linearize", "(", "U", ")", ":", "from", "scipy", ".", "cluster", "import", "hierarchy", "Z", "=", "hierarchy", ".", "ward", "(", "U", ")", "return", "hierarchy", ".", "leaves_list", "(", "hierarchy", ".", "optimal_leaf_ordering", "(", "Z", "...
Sorts the rows of a matrix by hierarchical clustering. Parameters: U (ndarray) : matrix of data Returns: prm (ndarray) : permutation of the rows
[ "Sorts", "the", "rows", "of", "a", "matrix", "by", "hierarchical", "clustering", "." ]
f375633ec621caa96665a56205dcf932590d4a6e
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/utils.py#L84-L96
20,673
ahwillia/tensortools
tensortools/utils.py
reverse_segment
def reverse_segment(path, n1, n2): """Reverse the nodes between n1 and n2. """ q = path.copy() if n2 > n1: q[n1:(n2+1)] = path[n1:(n2+1)][::-1] return q else: seg = np.hstack((path[n1:], path[:(n2+1)]))[::-1] brk = len(q) - n1 q[n1:] = seg[:brk] q[:(n2+1)] = seg[brk:] return q
python
def reverse_segment(path, n1, n2): q = path.copy() if n2 > n1: q[n1:(n2+1)] = path[n1:(n2+1)][::-1] return q else: seg = np.hstack((path[n1:], path[:(n2+1)]))[::-1] brk = len(q) - n1 q[n1:] = seg[:brk] q[:(n2+1)] = seg[brk:] return q
[ "def", "reverse_segment", "(", "path", ",", "n1", ",", "n2", ")", ":", "q", "=", "path", ".", "copy", "(", ")", "if", "n2", ">", "n1", ":", "q", "[", "n1", ":", "(", "n2", "+", "1", ")", "]", "=", "path", "[", "n1", ":", "(", "n2", "+", ...
Reverse the nodes between n1 and n2.
[ "Reverse", "the", "nodes", "between", "n1", "and", "n2", "." ]
f375633ec621caa96665a56205dcf932590d4a6e
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/utils.py#L99-L111
20,674
ahwillia/tensortools
tensortools/tensors.py
KTensor.full
def full(self): """Converts KTensor to a dense ndarray.""" # Compute tensor unfolding along first mode unf = sci.dot(self.factors[0], khatri_rao(self.factors[1:]).T) # Inverse unfolding along first mode return sci.reshape(unf, self.shape)
python
def full(self): # Compute tensor unfolding along first mode unf = sci.dot(self.factors[0], khatri_rao(self.factors[1:]).T) # Inverse unfolding along first mode return sci.reshape(unf, self.shape)
[ "def", "full", "(", "self", ")", ":", "# Compute tensor unfolding along first mode", "unf", "=", "sci", ".", "dot", "(", "self", ".", "factors", "[", "0", "]", ",", "khatri_rao", "(", "self", ".", "factors", "[", "1", ":", "]", ")", ".", "T", ")", "#...
Converts KTensor to a dense ndarray.
[ "Converts", "KTensor", "to", "a", "dense", "ndarray", "." ]
f375633ec621caa96665a56205dcf932590d4a6e
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/tensors.py#L41-L48
20,675
ahwillia/tensortools
tensortools/tensors.py
KTensor.rebalance
def rebalance(self): """Rescales factors across modes so that all norms match. """ # Compute norms along columns for each factor matrix norms = [sci.linalg.norm(f, axis=0) for f in self.factors] # Multiply norms across all modes lam = sci.multiply.reduce(norms) ** (1/self.ndim) # Update factors self.factors = [f * (lam / fn) for f, fn in zip(self.factors, norms)] return self
python
def rebalance(self): # Compute norms along columns for each factor matrix norms = [sci.linalg.norm(f, axis=0) for f in self.factors] # Multiply norms across all modes lam = sci.multiply.reduce(norms) ** (1/self.ndim) # Update factors self.factors = [f * (lam / fn) for f, fn in zip(self.factors, norms)] return self
[ "def", "rebalance", "(", "self", ")", ":", "# Compute norms along columns for each factor matrix", "norms", "=", "[", "sci", ".", "linalg", ".", "norm", "(", "f", ",", "axis", "=", "0", ")", "for", "f", "in", "self", ".", "factors", "]", "# Multiply norms ac...
Rescales factors across modes so that all norms match.
[ "Rescales", "factors", "across", "modes", "so", "that", "all", "norms", "match", "." ]
f375633ec621caa96665a56205dcf932590d4a6e
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/tensors.py#L50-L62
20,676
ahwillia/tensortools
tensortools/tensors.py
KTensor.permute
def permute(self, idx): """Permutes the columns of the factor matrices inplace """ # Check that input is a true permutation if set(idx) != set(range(self.rank)): raise ValueError('Invalid permutation specified.') # Update factors self.factors = [f[:, idx] for f in self.factors] return self.factors
python
def permute(self, idx): # Check that input is a true permutation if set(idx) != set(range(self.rank)): raise ValueError('Invalid permutation specified.') # Update factors self.factors = [f[:, idx] for f in self.factors] return self.factors
[ "def", "permute", "(", "self", ",", "idx", ")", ":", "# Check that input is a true permutation", "if", "set", "(", "idx", ")", "!=", "set", "(", "range", "(", "self", ".", "rank", ")", ")", ":", "raise", "ValueError", "(", "'Invalid permutation specified.'", ...
Permutes the columns of the factor matrices inplace
[ "Permutes", "the", "columns", "of", "the", "factor", "matrices", "inplace" ]
f375633ec621caa96665a56205dcf932590d4a6e
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/tensors.py#L64-L74
20,677
ahwillia/tensortools
tensortools/diagnostics.py
kruskal_align
def kruskal_align(U, V, permute_U=False, permute_V=False): """Aligns two KTensors and returns a similarity score. Parameters ---------- U : KTensor First kruskal tensor to align. V : KTensor Second kruskal tensor to align. permute_U : bool If True, modifies 'U' to align the KTensors (default is False). permute_V : bool If True, modifies 'V' to align the KTensors (default is False). Notes ----- If both `permute_U` and `permute_V` are both set to True, then the factors are ordered from most to least similar. If only one is True then the factors on the modified KTensor are re-ordered to match the factors in the un-aligned KTensor. Returns ------- similarity : float Similarity score between zero and one. """ # Compute similarity matrices. unrm = [f / np.linalg.norm(f, axis=0) for f in U.factors] vnrm = [f / np.linalg.norm(f, axis=0) for f in V.factors] sim_matrices = [np.dot(u.T, v) for u, v in zip(unrm, vnrm)] cost = 1 - np.mean(np.abs(sim_matrices), axis=0) # Solve matching problem via Hungarian algorithm. indices = Munkres().compute(cost.copy()) prmU, prmV = zip(*indices) # Compute mean factor similarity given the optimal matching. similarity = np.mean(1 - cost[prmU, prmV]) # If U and V are of different ranks, identify unmatched factors. unmatched_U = list(set(range(U.rank)) - set(prmU)) unmatched_V = list(set(range(V.rank)) - set(prmV)) # If permuting both U and V, order factors from most to least similar. if permute_U and permute_V: idx = np.argsort(cost[prmU, prmV]) # If permute_U is False, then order the factors such that the ordering # for U is unchanged. elif permute_V: idx = np.argsort(prmU) # If permute_V is False, then order the factors such that the ordering # for V is unchanged. elif permute_U: idx = np.argsort(prmV) # If permute_U and permute_V are both False, then we are done and can # simply return the similarity. else: return similarity # Re-order the factor permutations. prmU = [prmU[i] for i in idx] prmV = [prmV[i] for i in idx] # Permute the factors. if permute_U: U.permute(prmU) if permute_V: V.permute(prmV) # Flip the signs of factors. flips = np.sign([F[prmU, prmV] for F in sim_matrices]) flips[0] *= np.prod(flips, axis=0) # always flip an even number of factors if permute_U: for i, f in enumerate(flips): U.factors[i] *= f elif permute_V: for i, f in enumerate(flips): V.factors[i] *= f # Return the similarity score return similarity
python
def kruskal_align(U, V, permute_U=False, permute_V=False): # Compute similarity matrices. unrm = [f / np.linalg.norm(f, axis=0) for f in U.factors] vnrm = [f / np.linalg.norm(f, axis=0) for f in V.factors] sim_matrices = [np.dot(u.T, v) for u, v in zip(unrm, vnrm)] cost = 1 - np.mean(np.abs(sim_matrices), axis=0) # Solve matching problem via Hungarian algorithm. indices = Munkres().compute(cost.copy()) prmU, prmV = zip(*indices) # Compute mean factor similarity given the optimal matching. similarity = np.mean(1 - cost[prmU, prmV]) # If U and V are of different ranks, identify unmatched factors. unmatched_U = list(set(range(U.rank)) - set(prmU)) unmatched_V = list(set(range(V.rank)) - set(prmV)) # If permuting both U and V, order factors from most to least similar. if permute_U and permute_V: idx = np.argsort(cost[prmU, prmV]) # If permute_U is False, then order the factors such that the ordering # for U is unchanged. elif permute_V: idx = np.argsort(prmU) # If permute_V is False, then order the factors such that the ordering # for V is unchanged. elif permute_U: idx = np.argsort(prmV) # If permute_U and permute_V are both False, then we are done and can # simply return the similarity. else: return similarity # Re-order the factor permutations. prmU = [prmU[i] for i in idx] prmV = [prmV[i] for i in idx] # Permute the factors. if permute_U: U.permute(prmU) if permute_V: V.permute(prmV) # Flip the signs of factors. flips = np.sign([F[prmU, prmV] for F in sim_matrices]) flips[0] *= np.prod(flips, axis=0) # always flip an even number of factors if permute_U: for i, f in enumerate(flips): U.factors[i] *= f elif permute_V: for i, f in enumerate(flips): V.factors[i] *= f # Return the similarity score return similarity
[ "def", "kruskal_align", "(", "U", ",", "V", ",", "permute_U", "=", "False", ",", "permute_V", "=", "False", ")", ":", "# Compute similarity matrices.", "unrm", "=", "[", "f", "/", "np", ".", "linalg", ".", "norm", "(", "f", ",", "axis", "=", "0", ")"...
Aligns two KTensors and returns a similarity score. Parameters ---------- U : KTensor First kruskal tensor to align. V : KTensor Second kruskal tensor to align. permute_U : bool If True, modifies 'U' to align the KTensors (default is False). permute_V : bool If True, modifies 'V' to align the KTensors (default is False). Notes ----- If both `permute_U` and `permute_V` are both set to True, then the factors are ordered from most to least similar. If only one is True then the factors on the modified KTensor are re-ordered to match the factors in the un-aligned KTensor. Returns ------- similarity : float Similarity score between zero and one.
[ "Aligns", "two", "KTensors", "and", "returns", "a", "similarity", "score", "." ]
f375633ec621caa96665a56205dcf932590d4a6e
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/diagnostics.py#L9-L95
20,678
ahwillia/tensortools
tensortools/visualization.py
plot_objective
def plot_objective(ensemble, partition='train', ax=None, jitter=0.1, scatter_kw=dict(), line_kw=dict()): """Plots objective function as a function of model rank. Parameters ---------- ensemble : Ensemble object holds optimization results across a range of model ranks partition : string, one of: {'train', 'test'} specifies whether to plot the objective function on the training data or the held-out test set. ax : matplotlib axis (optional) axis to plot on (defaults to current axis object) jitter : float (optional) amount of horizontal jitter added to scatterpoints (default=0.1) scatter_kw : dict (optional) keyword arguments for styling the scatterpoints line_kw : dict (optional) keyword arguments for styling the line """ if ax is None: ax = plt.gca() if partition == 'train': pass elif partition == 'test': raise NotImplementedError('Cross-validation is on the TODO list.') else: raise ValueError("partition must be 'train' or 'test'.") # compile statistics for plotting x, obj, min_obj = [], [], [] for rank in sorted(ensemble.results): # reconstruction errors for rank-r models o = ensemble.objectives(rank) obj.extend(o) x.extend(np.full(len(o), rank)) min_obj.append(min(o)) # add horizontal jitter ux = np.unique(x) x = np.array(x) + (np.random.rand(len(x))-0.5)*jitter # make plot ax.scatter(x, obj, **scatter_kw) ax.plot(ux, min_obj, **line_kw) ax.set_xlabel('model rank') ax.set_ylabel('objective') return ax
python
def plot_objective(ensemble, partition='train', ax=None, jitter=0.1, scatter_kw=dict(), line_kw=dict()): if ax is None: ax = plt.gca() if partition == 'train': pass elif partition == 'test': raise NotImplementedError('Cross-validation is on the TODO list.') else: raise ValueError("partition must be 'train' or 'test'.") # compile statistics for plotting x, obj, min_obj = [], [], [] for rank in sorted(ensemble.results): # reconstruction errors for rank-r models o = ensemble.objectives(rank) obj.extend(o) x.extend(np.full(len(o), rank)) min_obj.append(min(o)) # add horizontal jitter ux = np.unique(x) x = np.array(x) + (np.random.rand(len(x))-0.5)*jitter # make plot ax.scatter(x, obj, **scatter_kw) ax.plot(ux, min_obj, **line_kw) ax.set_xlabel('model rank') ax.set_ylabel('objective') return ax
[ "def", "plot_objective", "(", "ensemble", ",", "partition", "=", "'train'", ",", "ax", "=", "None", ",", "jitter", "=", "0.1", ",", "scatter_kw", "=", "dict", "(", ")", ",", "line_kw", "=", "dict", "(", ")", ")", ":", "if", "ax", "is", "None", ":",...
Plots objective function as a function of model rank. Parameters ---------- ensemble : Ensemble object holds optimization results across a range of model ranks partition : string, one of: {'train', 'test'} specifies whether to plot the objective function on the training data or the held-out test set. ax : matplotlib axis (optional) axis to plot on (defaults to current axis object) jitter : float (optional) amount of horizontal jitter added to scatterpoints (default=0.1) scatter_kw : dict (optional) keyword arguments for styling the scatterpoints line_kw : dict (optional) keyword arguments for styling the line
[ "Plots", "objective", "function", "as", "a", "function", "of", "model", "rank", "." ]
f375633ec621caa96665a56205dcf932590d4a6e
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/visualization.py#L11-L61
20,679
ahwillia/tensortools
tensortools/visualization.py
plot_similarity
def plot_similarity(ensemble, ax=None, jitter=0.1, scatter_kw=dict(), line_kw=dict()): """Plots similarity across optimization runs as a function of model rank. Parameters ---------- ensemble : Ensemble object holds optimization results across a range of model ranks ax : matplotlib axis (optional) axis to plot on (defaults to current axis object) jitter : float (optional) amount of horizontal jitter added to scatterpoints (default=0.1) scatter_kw : dict (optional) keyword arguments for styling the scatterpoints line_kw : dict (optional) keyword arguments for styling the line References ---------- Ulrike von Luxburg (2010). Clustering Stability: An Overview. Foundations and Trends in Machine Learning. https://arxiv.org/abs/1007.1075 """ if ax is None: ax = plt.gca() # compile statistics for plotting x, sim, mean_sim = [], [], [] for rank in sorted(ensemble.results): # reconstruction errors for rank-r models s = ensemble.similarities(rank)[1:] sim.extend(s) x.extend(np.full(len(s), rank)) mean_sim.append(np.mean(s)) # add horizontal jitter ux = np.unique(x) x = np.array(x) + (np.random.rand(len(x))-0.5)*jitter # make plot ax.scatter(x, sim, **scatter_kw) ax.plot(ux, mean_sim, **line_kw) ax.set_xlabel('model rank') ax.set_ylabel('model similarity') ax.set_ylim([0, 1.1]) return ax
python
def plot_similarity(ensemble, ax=None, jitter=0.1, scatter_kw=dict(), line_kw=dict()): if ax is None: ax = plt.gca() # compile statistics for plotting x, sim, mean_sim = [], [], [] for rank in sorted(ensemble.results): # reconstruction errors for rank-r models s = ensemble.similarities(rank)[1:] sim.extend(s) x.extend(np.full(len(s), rank)) mean_sim.append(np.mean(s)) # add horizontal jitter ux = np.unique(x) x = np.array(x) + (np.random.rand(len(x))-0.5)*jitter # make plot ax.scatter(x, sim, **scatter_kw) ax.plot(ux, mean_sim, **line_kw) ax.set_xlabel('model rank') ax.set_ylabel('model similarity') ax.set_ylim([0, 1.1]) return ax
[ "def", "plot_similarity", "(", "ensemble", ",", "ax", "=", "None", ",", "jitter", "=", "0.1", ",", "scatter_kw", "=", "dict", "(", ")", ",", "line_kw", "=", "dict", "(", ")", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", ...
Plots similarity across optimization runs as a function of model rank. Parameters ---------- ensemble : Ensemble object holds optimization results across a range of model ranks ax : matplotlib axis (optional) axis to plot on (defaults to current axis object) jitter : float (optional) amount of horizontal jitter added to scatterpoints (default=0.1) scatter_kw : dict (optional) keyword arguments for styling the scatterpoints line_kw : dict (optional) keyword arguments for styling the line References ---------- Ulrike von Luxburg (2010). Clustering Stability: An Overview. Foundations and Trends in Machine Learning. https://arxiv.org/abs/1007.1075
[ "Plots", "similarity", "across", "optimization", "runs", "as", "a", "function", "of", "model", "rank", "." ]
f375633ec621caa96665a56205dcf932590d4a6e
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/visualization.py#L64-L113
20,680
ahwillia/tensortools
tensortools/visualization.py
_broadcast_arg
def _broadcast_arg(U, arg, argtype, name): """Broadcasts plotting option `arg` to all factors. Args: U : KTensor arg : argument provided by the user argtype : expected type for arg name : name of the variable, used for error handling Returns: iterable version of arg of length U.ndim """ # if input is not iterable, broadcast it all dimensions of the tensor if arg is None or isinstance(arg, argtype): return [arg for _ in range(U.ndim)] # check if iterable input is valid elif np.iterable(arg): if len(arg) != U.ndim: raise ValueError('Parameter {} was specified as a sequence of ' 'incorrect length. The length must match the ' 'number of tensor dimensions ' '(U.ndim={})'.format(name, U.ndim)) elif not all([isinstance(a, argtype) for a in arg]): raise TypeError('Parameter {} specified as a sequence of ' 'incorrect type. ' 'Expected {}.'.format(name, argtype)) else: return arg # input is not iterable and is not the corrent type. else: raise TypeError('Parameter {} specified as a {}.' ' Expected {}.'.format(name, type(arg), argtype))
python
def _broadcast_arg(U, arg, argtype, name): # if input is not iterable, broadcast it all dimensions of the tensor if arg is None or isinstance(arg, argtype): return [arg for _ in range(U.ndim)] # check if iterable input is valid elif np.iterable(arg): if len(arg) != U.ndim: raise ValueError('Parameter {} was specified as a sequence of ' 'incorrect length. The length must match the ' 'number of tensor dimensions ' '(U.ndim={})'.format(name, U.ndim)) elif not all([isinstance(a, argtype) for a in arg]): raise TypeError('Parameter {} specified as a sequence of ' 'incorrect type. ' 'Expected {}.'.format(name, argtype)) else: return arg # input is not iterable and is not the corrent type. else: raise TypeError('Parameter {} specified as a {}.' ' Expected {}.'.format(name, type(arg), argtype))
[ "def", "_broadcast_arg", "(", "U", ",", "arg", ",", "argtype", ",", "name", ")", ":", "# if input is not iterable, broadcast it all dimensions of the tensor", "if", "arg", "is", "None", "or", "isinstance", "(", "arg", ",", "argtype", ")", ":", "return", "[", "ar...
Broadcasts plotting option `arg` to all factors. Args: U : KTensor arg : argument provided by the user argtype : expected type for arg name : name of the variable, used for error handling Returns: iterable version of arg of length U.ndim
[ "Broadcasts", "plotting", "option", "arg", "to", "all", "factors", "." ]
f375633ec621caa96665a56205dcf932590d4a6e
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/visualization.py#L248-L282
20,681
ahwillia/tensortools
tensortools/optimize/optim_utils.py
_check_cpd_inputs
def _check_cpd_inputs(X, rank): """Checks that inputs to optimization function are appropriate. Parameters ---------- X : ndarray Tensor used for fitting CP decomposition. rank : int Rank of low rank decomposition. Raises ------ ValueError: If inputs are not suited for CP decomposition. """ if X.ndim < 3: raise ValueError("Array with X.ndim > 2 expected.") if rank <= 0 or not isinstance(rank, int): raise ValueError("Rank is invalid.")
python
def _check_cpd_inputs(X, rank): if X.ndim < 3: raise ValueError("Array with X.ndim > 2 expected.") if rank <= 0 or not isinstance(rank, int): raise ValueError("Rank is invalid.")
[ "def", "_check_cpd_inputs", "(", "X", ",", "rank", ")", ":", "if", "X", ".", "ndim", "<", "3", ":", "raise", "ValueError", "(", "\"Array with X.ndim > 2 expected.\"", ")", "if", "rank", "<=", "0", "or", "not", "isinstance", "(", "rank", ",", "int", ")", ...
Checks that inputs to optimization function are appropriate. Parameters ---------- X : ndarray Tensor used for fitting CP decomposition. rank : int Rank of low rank decomposition. Raises ------ ValueError: If inputs are not suited for CP decomposition.
[ "Checks", "that", "inputs", "to", "optimization", "function", "are", "appropriate", "." ]
f375633ec621caa96665a56205dcf932590d4a6e
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/optimize/optim_utils.py#L11-L28
20,682
ahwillia/tensortools
tensortools/data/random_tensor.py
_check_random_state
def _check_random_state(random_state): """Checks and processes user input for seeding random numbers. Parameters ---------- random_state : int, RandomState instance or None If int, a RandomState instance is created with this integer seed. If RandomState instance, random_state is returned; If None, a RandomState instance is created with arbitrary seed. Returns ------- scipy.random.RandomState instance Raises ------ TypeError If ``random_state`` is not appropriately set. """ if random_state is None or isinstance(random_state, int): return sci.random.RandomState(random_state) elif isinstance(random_state, sci.random.RandomState): return random_state else: raise TypeError('Seed should be None, int or np.random.RandomState')
python
def _check_random_state(random_state): if random_state is None or isinstance(random_state, int): return sci.random.RandomState(random_state) elif isinstance(random_state, sci.random.RandomState): return random_state else: raise TypeError('Seed should be None, int or np.random.RandomState')
[ "def", "_check_random_state", "(", "random_state", ")", ":", "if", "random_state", "is", "None", "or", "isinstance", "(", "random_state", ",", "int", ")", ":", "return", "sci", ".", "random", ".", "RandomState", "(", "random_state", ")", "elif", "isinstance", ...
Checks and processes user input for seeding random numbers. Parameters ---------- random_state : int, RandomState instance or None If int, a RandomState instance is created with this integer seed. If RandomState instance, random_state is returned; If None, a RandomState instance is created with arbitrary seed. Returns ------- scipy.random.RandomState instance Raises ------ TypeError If ``random_state`` is not appropriately set.
[ "Checks", "and", "processes", "user", "input", "for", "seeding", "random", "numbers", "." ]
f375633ec621caa96665a56205dcf932590d4a6e
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/data/random_tensor.py#L10-L34
20,683
ahwillia/tensortools
tensortools/data/random_tensor.py
randn_ktensor
def randn_ktensor(shape, rank, norm=None, random_state=None): """ Generates a random N-way tensor with rank R, where the entries are drawn from the standard normal distribution. Parameters ---------- shape : tuple shape of the tensor rank : integer rank of the tensor norm : float or None, optional (defaults: None) If not None, the factor matrices are rescaled so that the Frobenius norm of the returned tensor is equal to ``norm``. random_state : integer, RandomState instance or None, optional (default ``None``) If integer, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random. Returns ------- X : (I_1, ..., I_N) array_like N-way tensor with rank R. Example ------- >>> # Create a rank-2 tensor of dimension 5x5x5: >>> import tensortools as tt >>> X = tt.randn_tensor((5,5,5), rank=2) """ # Check input. rns = _check_random_state(random_state) # Draw low-rank factor matrices with i.i.d. Gaussian elements. factors = KTensor([rns.standard_normal((i, rank)) for i in shape]) return _rescale_tensor(factors, norm)
python
def randn_ktensor(shape, rank, norm=None, random_state=None): # Check input. rns = _check_random_state(random_state) # Draw low-rank factor matrices with i.i.d. Gaussian elements. factors = KTensor([rns.standard_normal((i, rank)) for i in shape]) return _rescale_tensor(factors, norm)
[ "def", "randn_ktensor", "(", "shape", ",", "rank", ",", "norm", "=", "None", ",", "random_state", "=", "None", ")", ":", "# Check input.", "rns", "=", "_check_random_state", "(", "random_state", ")", "# Draw low-rank factor matrices with i.i.d. Gaussian elements.", "f...
Generates a random N-way tensor with rank R, where the entries are drawn from the standard normal distribution. Parameters ---------- shape : tuple shape of the tensor rank : integer rank of the tensor norm : float or None, optional (defaults: None) If not None, the factor matrices are rescaled so that the Frobenius norm of the returned tensor is equal to ``norm``. random_state : integer, RandomState instance or None, optional (default ``None``) If integer, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random. Returns ------- X : (I_1, ..., I_N) array_like N-way tensor with rank R. Example ------- >>> # Create a rank-2 tensor of dimension 5x5x5: >>> import tensortools as tt >>> X = tt.randn_tensor((5,5,5), rank=2)
[ "Generates", "a", "random", "N", "-", "way", "tensor", "with", "rank", "R", "where", "the", "entries", "are", "drawn", "from", "the", "standard", "normal", "distribution", "." ]
f375633ec621caa96665a56205dcf932590d4a6e
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/data/random_tensor.py#L47-L88
20,684
ahwillia/tensortools
tensortools/ensemble.py
Ensemble.fit
def fit(self, X, ranks, replicates=1, verbose=True): """ Fits CP tensor decompositions for different choices of rank. Parameters ---------- X : array_like Real tensor ranks : int, or iterable iterable specifying number of components in each model replicates: int number of models to fit at each rank verbose : bool If True, prints summaries and optimization progress. """ # Make ranks iterable if necessary. if not isinstance(ranks, collections.Iterable): ranks = (ranks,) # Iterate over model ranks, optimize multiple replicates at each rank. for r in ranks: # Initialize storage if r not in self.results: self.results[r] = [] # Display fitting progress. if verbose: itr = trange(replicates, desc='Fitting rank-{} models'.format(r), leave=False) else: itr = range(replicates) # Fit replicates. for i in itr: model_fit = self._fit_method(X, r, **self._fit_options) self.results[r].append(model_fit) # Print summary of results. if verbose: min_obj = min([res.obj for res in self.results[r]]) max_obj = max([res.obj for res in self.results[r]]) elapsed = sum([res.total_time for res in self.results[r]]) print('Rank-{} models: min obj, {:.2f}; ' 'max obj, {:.2f}; time to fit, ' '{:.1f}s'.format(r, min_obj, max_obj, elapsed)) # Sort results from lowest to largest loss. for r in ranks: idx = np.argsort([result.obj for result in self.results[r]]) self.results[r] = [self.results[r][i] for i in idx] # Align best model within each rank to best model of next larger rank. # Here r0 is the rank of the lower-dimensional model and r1 is the rank # of the high-dimensional model. for i in reversed(range(1, len(ranks))): r0, r1 = ranks[i-1], ranks[i] U = self.results[r0][0].factors V = self.results[r1][0].factors kruskal_align(U, V, permute_U=True) # For each rank, align everything to the best model for r in ranks: # store best factors U = self.results[r][0].factors # best model factors self.results[r][0].similarity = 1.0 # similarity to itself # align lesser fit models to best models for res in self.results[r][1:]: res.similarity = kruskal_align(U, res.factors, permute_V=True)
python
def fit(self, X, ranks, replicates=1, verbose=True): # Make ranks iterable if necessary. if not isinstance(ranks, collections.Iterable): ranks = (ranks,) # Iterate over model ranks, optimize multiple replicates at each rank. for r in ranks: # Initialize storage if r not in self.results: self.results[r] = [] # Display fitting progress. if verbose: itr = trange(replicates, desc='Fitting rank-{} models'.format(r), leave=False) else: itr = range(replicates) # Fit replicates. for i in itr: model_fit = self._fit_method(X, r, **self._fit_options) self.results[r].append(model_fit) # Print summary of results. if verbose: min_obj = min([res.obj for res in self.results[r]]) max_obj = max([res.obj for res in self.results[r]]) elapsed = sum([res.total_time for res in self.results[r]]) print('Rank-{} models: min obj, {:.2f}; ' 'max obj, {:.2f}; time to fit, ' '{:.1f}s'.format(r, min_obj, max_obj, elapsed)) # Sort results from lowest to largest loss. for r in ranks: idx = np.argsort([result.obj for result in self.results[r]]) self.results[r] = [self.results[r][i] for i in idx] # Align best model within each rank to best model of next larger rank. # Here r0 is the rank of the lower-dimensional model and r1 is the rank # of the high-dimensional model. for i in reversed(range(1, len(ranks))): r0, r1 = ranks[i-1], ranks[i] U = self.results[r0][0].factors V = self.results[r1][0].factors kruskal_align(U, V, permute_U=True) # For each rank, align everything to the best model for r in ranks: # store best factors U = self.results[r][0].factors # best model factors self.results[r][0].similarity = 1.0 # similarity to itself # align lesser fit models to best models for res in self.results[r][1:]: res.similarity = kruskal_align(U, res.factors, permute_V=True)
[ "def", "fit", "(", "self", ",", "X", ",", "ranks", ",", "replicates", "=", "1", ",", "verbose", "=", "True", ")", ":", "# Make ranks iterable if necessary.", "if", "not", "isinstance", "(", "ranks", ",", "collections", ".", "Iterable", ")", ":", "ranks", ...
Fits CP tensor decompositions for different choices of rank. Parameters ---------- X : array_like Real tensor ranks : int, or iterable iterable specifying number of components in each model replicates: int number of models to fit at each rank verbose : bool If True, prints summaries and optimization progress.
[ "Fits", "CP", "tensor", "decompositions", "for", "different", "choices", "of", "rank", "." ]
f375633ec621caa96665a56205dcf932590d4a6e
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/ensemble.py#L57-L128
20,685
ahwillia/tensortools
tensortools/ensemble.py
Ensemble.objectives
def objectives(self, rank): """Returns objective values of models with specified rank. """ self._check_rank(rank) return [result.obj for result in self.results[rank]]
python
def objectives(self, rank): self._check_rank(rank) return [result.obj for result in self.results[rank]]
[ "def", "objectives", "(", "self", ",", "rank", ")", ":", "self", ".", "_check_rank", "(", "rank", ")", "return", "[", "result", ".", "obj", "for", "result", "in", "self", ".", "results", "[", "rank", "]", "]" ]
Returns objective values of models with specified rank.
[ "Returns", "objective", "values", "of", "models", "with", "specified", "rank", "." ]
f375633ec621caa96665a56205dcf932590d4a6e
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/ensemble.py#L130-L134
20,686
ahwillia/tensortools
tensortools/ensemble.py
Ensemble.similarities
def similarities(self, rank): """Returns similarity scores for models with specified rank. """ self._check_rank(rank) return [result.similarity for result in self.results[rank]]
python
def similarities(self, rank): self._check_rank(rank) return [result.similarity for result in self.results[rank]]
[ "def", "similarities", "(", "self", ",", "rank", ")", ":", "self", ".", "_check_rank", "(", "rank", ")", "return", "[", "result", ".", "similarity", "for", "result", "in", "self", ".", "results", "[", "rank", "]", "]" ]
Returns similarity scores for models with specified rank.
[ "Returns", "similarity", "scores", "for", "models", "with", "specified", "rank", "." ]
f375633ec621caa96665a56205dcf932590d4a6e
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/ensemble.py#L136-L140
20,687
ahwillia/tensortools
tensortools/ensemble.py
Ensemble.factors
def factors(self, rank): """Returns KTensor factors for models with specified rank. """ self._check_rank(rank) return [result.factors for result in self.results[rank]]
python
def factors(self, rank): self._check_rank(rank) return [result.factors for result in self.results[rank]]
[ "def", "factors", "(", "self", ",", "rank", ")", ":", "self", ".", "_check_rank", "(", "rank", ")", "return", "[", "result", ".", "factors", "for", "result", "in", "self", ".", "results", "[", "rank", "]", "]" ]
Returns KTensor factors for models with specified rank.
[ "Returns", "KTensor", "factors", "for", "models", "with", "specified", "rank", "." ]
f375633ec621caa96665a56205dcf932590d4a6e
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/ensemble.py#L142-L146
20,688
OCA/odoorpc
odoorpc/env.py
Environment._create_model_class
def _create_model_class(self, model): """Generate the model proxy class. :return: a :class:`odoorpc.models.Model` class """ cls_name = model.replace('.', '_') # Hack for Python 2 (no need to do this for Python 3) if sys.version_info[0] < 3: if isinstance(cls_name, unicode): cls_name = cls_name.encode('utf-8') # Retrieve server fields info and generate corresponding local fields attrs = { '_env': self, '_odoo': self._odoo, '_name': model, '_columns': {}, } fields_get = self._odoo.execute(model, 'fields_get') for field_name, field_data in fields_get.items(): if field_name not in FIELDS_RESERVED: Field = fields.generate_field(field_name, field_data) attrs['_columns'][field_name] = Field attrs[field_name] = Field # Case where no field 'name' exists, we generate one (which will be # in readonly mode) in purpose to be filled with the 'name_get' method if 'name' not in attrs['_columns']: field_data = {'type': 'text', 'string': 'Name', 'readonly': True} Field = fields.generate_field('name', field_data) attrs['_columns']['name'] = Field attrs['name'] = Field return type(cls_name, (Model,), attrs)
python
def _create_model_class(self, model): cls_name = model.replace('.', '_') # Hack for Python 2 (no need to do this for Python 3) if sys.version_info[0] < 3: if isinstance(cls_name, unicode): cls_name = cls_name.encode('utf-8') # Retrieve server fields info and generate corresponding local fields attrs = { '_env': self, '_odoo': self._odoo, '_name': model, '_columns': {}, } fields_get = self._odoo.execute(model, 'fields_get') for field_name, field_data in fields_get.items(): if field_name not in FIELDS_RESERVED: Field = fields.generate_field(field_name, field_data) attrs['_columns'][field_name] = Field attrs[field_name] = Field # Case where no field 'name' exists, we generate one (which will be # in readonly mode) in purpose to be filled with the 'name_get' method if 'name' not in attrs['_columns']: field_data = {'type': 'text', 'string': 'Name', 'readonly': True} Field = fields.generate_field('name', field_data) attrs['_columns']['name'] = Field attrs['name'] = Field return type(cls_name, (Model,), attrs)
[ "def", "_create_model_class", "(", "self", ",", "model", ")", ":", "cls_name", "=", "model", ".", "replace", "(", "'.'", ",", "'_'", ")", "# Hack for Python 2 (no need to do this for Python 3)", "if", "sys", ".", "version_info", "[", "0", "]", "<", "3", ":", ...
Generate the model proxy class. :return: a :class:`odoorpc.models.Model` class
[ "Generate", "the", "model", "proxy", "class", "." ]
d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/env.py#L313-L343
20,689
OCA/odoorpc
odoorpc/session.py
get_all
def get_all(rc_file='~/.odoorpcrc'): """Return all session configurations from the `rc_file` file. >>> import odoorpc >>> from pprint import pprint as pp >>> pp(odoorpc.session.get_all()) # doctest: +SKIP {'foo': {'database': 'db_name', 'host': 'localhost', 'passwd': 'password', 'port': 8069, 'protocol': 'jsonrpc', 'timeout': 120, 'type': 'ODOO', 'user': 'admin'}, ...} .. doctest:: :hide: >>> import odoorpc >>> session = '%s_session' % DB >>> odoo.save(session) >>> data = odoorpc.session.get_all() >>> data[session]['host'] == HOST True >>> data[session]['protocol'] == PROTOCOL True >>> data[session]['port'] == int(PORT) True >>> data[session]['database'] == DB True >>> data[session]['user'] == USER True >>> data[session]['passwd'] == PWD True >>> data[session]['type'] == 'ODOO' True """ conf = ConfigParser() conf.read([os.path.expanduser(rc_file)]) sessions = {} for name in conf.sections(): sessions[name] = { 'type': conf.get(name, 'type'), 'host': conf.get(name, 'host'), 'protocol': conf.get(name, 'protocol'), 'port': conf.getint(name, 'port'), 'timeout': conf.getfloat(name, 'timeout'), 'user': conf.get(name, 'user'), 'passwd': conf.get(name, 'passwd'), 'database': conf.get(name, 'database'), } return sessions
python
def get_all(rc_file='~/.odoorpcrc'): conf = ConfigParser() conf.read([os.path.expanduser(rc_file)]) sessions = {} for name in conf.sections(): sessions[name] = { 'type': conf.get(name, 'type'), 'host': conf.get(name, 'host'), 'protocol': conf.get(name, 'protocol'), 'port': conf.getint(name, 'port'), 'timeout': conf.getfloat(name, 'timeout'), 'user': conf.get(name, 'user'), 'passwd': conf.get(name, 'passwd'), 'database': conf.get(name, 'database'), } return sessions
[ "def", "get_all", "(", "rc_file", "=", "'~/.odoorpcrc'", ")", ":", "conf", "=", "ConfigParser", "(", ")", "conf", ".", "read", "(", "[", "os", ".", "path", ".", "expanduser", "(", "rc_file", ")", "]", ")", "sessions", "=", "{", "}", "for", "name", ...
Return all session configurations from the `rc_file` file. >>> import odoorpc >>> from pprint import pprint as pp >>> pp(odoorpc.session.get_all()) # doctest: +SKIP {'foo': {'database': 'db_name', 'host': 'localhost', 'passwd': 'password', 'port': 8069, 'protocol': 'jsonrpc', 'timeout': 120, 'type': 'ODOO', 'user': 'admin'}, ...} .. doctest:: :hide: >>> import odoorpc >>> session = '%s_session' % DB >>> odoo.save(session) >>> data = odoorpc.session.get_all() >>> data[session]['host'] == HOST True >>> data[session]['protocol'] == PROTOCOL True >>> data[session]['port'] == int(PORT) True >>> data[session]['database'] == DB True >>> data[session]['user'] == USER True >>> data[session]['passwd'] == PWD True >>> data[session]['type'] == 'ODOO' True
[ "Return", "all", "session", "configurations", "from", "the", "rc_file", "file", "." ]
d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/session.py#L35-L87
20,690
OCA/odoorpc
odoorpc/session.py
get
def get(name, rc_file='~/.odoorpcrc'): """Return the session configuration identified by `name` from the `rc_file` file. >>> import odoorpc >>> from pprint import pprint as pp >>> pp(odoorpc.session.get('foo')) # doctest: +SKIP {'database': 'db_name', 'host': 'localhost', 'passwd': 'password', 'port': 8069, 'protocol': 'jsonrpc', 'timeout': 120, 'type': 'ODOO', 'user': 'admin'} .. doctest:: :hide: >>> import odoorpc >>> session = '%s_session' % DB >>> odoo.save(session) >>> data = odoorpc.session.get(session) >>> data['host'] == HOST True >>> data['protocol'] == PROTOCOL True >>> data['port'] == int(PORT) True >>> data['database'] == DB True >>> data['user'] == USER True >>> data['passwd'] == PWD True >>> data['type'] == 'ODOO' True :raise: `ValueError` (wrong session name) """ conf = ConfigParser() conf.read([os.path.expanduser(rc_file)]) if not conf.has_section(name): raise ValueError( "'%s' session does not exist in %s" % (name, rc_file)) return { 'type': conf.get(name, 'type'), 'host': conf.get(name, 'host'), 'protocol': conf.get(name, 'protocol'), 'port': conf.getint(name, 'port'), 'timeout': conf.getfloat(name, 'timeout'), 'user': conf.get(name, 'user'), 'passwd': conf.get(name, 'passwd'), 'database': conf.get(name, 'database'), }
python
def get(name, rc_file='~/.odoorpcrc'): conf = ConfigParser() conf.read([os.path.expanduser(rc_file)]) if not conf.has_section(name): raise ValueError( "'%s' session does not exist in %s" % (name, rc_file)) return { 'type': conf.get(name, 'type'), 'host': conf.get(name, 'host'), 'protocol': conf.get(name, 'protocol'), 'port': conf.getint(name, 'port'), 'timeout': conf.getfloat(name, 'timeout'), 'user': conf.get(name, 'user'), 'passwd': conf.get(name, 'passwd'), 'database': conf.get(name, 'database'), }
[ "def", "get", "(", "name", ",", "rc_file", "=", "'~/.odoorpcrc'", ")", ":", "conf", "=", "ConfigParser", "(", ")", "conf", ".", "read", "(", "[", "os", ".", "path", ".", "expanduser", "(", "rc_file", ")", "]", ")", "if", "not", "conf", ".", "has_se...
Return the session configuration identified by `name` from the `rc_file` file. >>> import odoorpc >>> from pprint import pprint as pp >>> pp(odoorpc.session.get('foo')) # doctest: +SKIP {'database': 'db_name', 'host': 'localhost', 'passwd': 'password', 'port': 8069, 'protocol': 'jsonrpc', 'timeout': 120, 'type': 'ODOO', 'user': 'admin'} .. doctest:: :hide: >>> import odoorpc >>> session = '%s_session' % DB >>> odoo.save(session) >>> data = odoorpc.session.get(session) >>> data['host'] == HOST True >>> data['protocol'] == PROTOCOL True >>> data['port'] == int(PORT) True >>> data['database'] == DB True >>> data['user'] == USER True >>> data['passwd'] == PWD True >>> data['type'] == 'ODOO' True :raise: `ValueError` (wrong session name)
[ "Return", "the", "session", "configuration", "identified", "by", "name", "from", "the", "rc_file", "file", "." ]
d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/session.py#L90-L144
20,691
OCA/odoorpc
odoorpc/session.py
save
def save(name, data, rc_file='~/.odoorpcrc'): """Save the `data` session configuration under the name `name` in the `rc_file` file. >>> import odoorpc >>> odoorpc.session.save( ... 'foo', ... {'type': 'ODOO', 'host': 'localhost', 'protocol': 'jsonrpc', ... 'port': 8069, 'timeout': 120, 'database': 'db_name' ... 'user': 'admin', 'passwd': 'password'}) # doctest: +SKIP .. doctest:: :hide: >>> import odoorpc >>> session = '%s_session' % DB >>> odoorpc.session.save( ... session, ... {'type': 'ODOO', 'host': HOST, 'protocol': PROTOCOL, ... 'port': PORT, 'timeout': 120, 'database': DB, ... 'user': USER, 'passwd': PWD}) """ conf = ConfigParser() conf.read([os.path.expanduser(rc_file)]) if not conf.has_section(name): conf.add_section(name) for key in data: value = data[key] conf.set(name, key, str(value)) with open(os.path.expanduser(rc_file), 'w') as file_: os.chmod(os.path.expanduser(rc_file), stat.S_IREAD | stat.S_IWRITE) conf.write(file_)
python
def save(name, data, rc_file='~/.odoorpcrc'): conf = ConfigParser() conf.read([os.path.expanduser(rc_file)]) if not conf.has_section(name): conf.add_section(name) for key in data: value = data[key] conf.set(name, key, str(value)) with open(os.path.expanduser(rc_file), 'w') as file_: os.chmod(os.path.expanduser(rc_file), stat.S_IREAD | stat.S_IWRITE) conf.write(file_)
[ "def", "save", "(", "name", ",", "data", ",", "rc_file", "=", "'~/.odoorpcrc'", ")", ":", "conf", "=", "ConfigParser", "(", ")", "conf", ".", "read", "(", "[", "os", ".", "path", ".", "expanduser", "(", "rc_file", ")", "]", ")", "if", "not", "conf"...
Save the `data` session configuration under the name `name` in the `rc_file` file. >>> import odoorpc >>> odoorpc.session.save( ... 'foo', ... {'type': 'ODOO', 'host': 'localhost', 'protocol': 'jsonrpc', ... 'port': 8069, 'timeout': 120, 'database': 'db_name' ... 'user': 'admin', 'passwd': 'password'}) # doctest: +SKIP .. doctest:: :hide: >>> import odoorpc >>> session = '%s_session' % DB >>> odoorpc.session.save( ... session, ... {'type': 'ODOO', 'host': HOST, 'protocol': PROTOCOL, ... 'port': PORT, 'timeout': 120, 'database': DB, ... 'user': USER, 'passwd': PWD})
[ "Save", "the", "data", "session", "configuration", "under", "the", "name", "name", "in", "the", "rc_file", "file", "." ]
d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/session.py#L147-L178
20,692
OCA/odoorpc
odoorpc/session.py
remove
def remove(name, rc_file='~/.odoorpcrc'): """Remove the session configuration identified by `name` from the `rc_file` file. >>> import odoorpc >>> odoorpc.session.remove('foo') # doctest: +SKIP .. doctest:: :hide: >>> import odoorpc >>> session = '%s_session' % DB >>> odoorpc.session.remove(session) :raise: `ValueError` (wrong session name) """ conf = ConfigParser() conf.read([os.path.expanduser(rc_file)]) if not conf.has_section(name): raise ValueError( "'%s' session does not exist in %s" % (name, rc_file)) conf.remove_section(name) with open(os.path.expanduser(rc_file), 'wb') as file_: conf.write(file_)
python
def remove(name, rc_file='~/.odoorpcrc'): conf = ConfigParser() conf.read([os.path.expanduser(rc_file)]) if not conf.has_section(name): raise ValueError( "'%s' session does not exist in %s" % (name, rc_file)) conf.remove_section(name) with open(os.path.expanduser(rc_file), 'wb') as file_: conf.write(file_)
[ "def", "remove", "(", "name", ",", "rc_file", "=", "'~/.odoorpcrc'", ")", ":", "conf", "=", "ConfigParser", "(", ")", "conf", ".", "read", "(", "[", "os", ".", "path", ".", "expanduser", "(", "rc_file", ")", "]", ")", "if", "not", "conf", ".", "has...
Remove the session configuration identified by `name` from the `rc_file` file. >>> import odoorpc >>> odoorpc.session.remove('foo') # doctest: +SKIP .. doctest:: :hide: >>> import odoorpc >>> session = '%s_session' % DB >>> odoorpc.session.remove(session) :raise: `ValueError` (wrong session name)
[ "Remove", "the", "session", "configuration", "identified", "by", "name", "from", "the", "rc_file", "file", "." ]
d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/session.py#L181-L204
20,693
OCA/odoorpc
odoorpc/rpc/jsonrpclib.py
get_json_log_data
def get_json_log_data(data): """Returns a new `data` dictionary with hidden params for log purpose. """ log_data = data for param in LOG_HIDDEN_JSON_PARAMS: if param in data['params']: if log_data is data: log_data = copy.deepcopy(data) log_data['params'][param] = "**********" return log_data
python
def get_json_log_data(data): log_data = data for param in LOG_HIDDEN_JSON_PARAMS: if param in data['params']: if log_data is data: log_data = copy.deepcopy(data) log_data['params'][param] = "**********" return log_data
[ "def", "get_json_log_data", "(", "data", ")", ":", "log_data", "=", "data", "for", "param", "in", "LOG_HIDDEN_JSON_PARAMS", ":", "if", "param", "in", "data", "[", "'params'", "]", ":", "if", "log_data", "is", "data", ":", "log_data", "=", "copy", ".", "d...
Returns a new `data` dictionary with hidden params for log purpose.
[ "Returns", "a", "new", "data", "dictionary", "with", "hidden", "params", "for", "log", "purpose", "." ]
d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/rpc/jsonrpclib.py#L61-L71
20,694
OCA/odoorpc
odoorpc/odoo.py
ODOO.http
def http(self, url, data=None, headers=None): """Low level method to execute raw HTTP queries. .. note:: For low level JSON-RPC queries, see the more convenient :func:`odoorpc.ODOO.json` method instead. You have to know the names of each POST parameter required by the URL, and set them in the `data` string/buffer. The `data` argument must be built by yourself, following the expected URL parameters (with :func:`urllib.urlencode` function for simple parameters, or multipart/form-data structure to handle file upload). E.g., the HTTP raw query to get the company logo on `Odoo 12.0`: .. doctest:: >>> response = odoo.http('web/binary/company_logo') >>> binary_data = response.read() *Python 2:* :return: `urllib.addinfourl` :raise: `urllib2.HTTPError` :raise: `urllib2.URLError` (connection error) *Python 3:* :return: `http.client.HTTPResponse` :raise: `urllib.error.HTTPError` :raise: `urllib.error.URLError` (connection error) """ return self._connector.proxy_http(url, data, headers)
python
def http(self, url, data=None, headers=None): return self._connector.proxy_http(url, data, headers)
[ "def", "http", "(", "self", ",", "url", ",", "data", "=", "None", ",", "headers", "=", "None", ")", ":", "return", "self", ".", "_connector", ".", "proxy_http", "(", "url", ",", "data", ",", "headers", ")" ]
Low level method to execute raw HTTP queries. .. note:: For low level JSON-RPC queries, see the more convenient :func:`odoorpc.ODOO.json` method instead. You have to know the names of each POST parameter required by the URL, and set them in the `data` string/buffer. The `data` argument must be built by yourself, following the expected URL parameters (with :func:`urllib.urlencode` function for simple parameters, or multipart/form-data structure to handle file upload). E.g., the HTTP raw query to get the company logo on `Odoo 12.0`: .. doctest:: >>> response = odoo.http('web/binary/company_logo') >>> binary_data = response.read() *Python 2:* :return: `urllib.addinfourl` :raise: `urllib2.HTTPError` :raise: `urllib2.URLError` (connection error) *Python 3:* :return: `http.client.HTTPResponse` :raise: `urllib.error.HTTPError` :raise: `urllib.error.URLError` (connection error)
[ "Low", "level", "method", "to", "execute", "raw", "HTTP", "queries", "." ]
d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/odoo.py#L288-L321
20,695
OCA/odoorpc
odoorpc/odoo.py
ODOO._check_logged_user
def _check_logged_user(self): """Check if a user is logged. Otherwise, an error is raised.""" if not self._env or not self._password or not self._login: raise error.InternalError("Login required")
python
def _check_logged_user(self): if not self._env or not self._password or not self._login: raise error.InternalError("Login required")
[ "def", "_check_logged_user", "(", "self", ")", ":", "if", "not", "self", ".", "_env", "or", "not", "self", ".", "_password", "or", "not", "self", ".", "_login", ":", "raise", "error", ".", "InternalError", "(", "\"Login required\"", ")" ]
Check if a user is logged. Otherwise, an error is raised.
[ "Check", "if", "a", "user", "is", "logged", ".", "Otherwise", "an", "error", "is", "raised", "." ]
d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/odoo.py#L326-L329
20,696
OCA/odoorpc
odoorpc/odoo.py
ODOO.login
def login(self, db, login='admin', password='admin'): """Log in as the given `user` with the password `passwd` on the database `db`. .. doctest:: :options: +SKIP >>> odoo.login('db_name', 'admin', 'admin') >>> odoo.env.user.name 'Administrator' *Python 2:* :raise: :class:`odoorpc.error.RPCError` :raise: `urllib2.URLError` (connection error) *Python 3:* :raise: :class:`odoorpc.error.RPCError` :raise: `urllib.error.URLError` (connection error) """ # Get the user's ID and generate the corresponding user record data = self.json( '/web/session/authenticate', {'db': db, 'login': login, 'password': password}) uid = data['result']['uid'] if uid: context = data['result']['user_context'] self._env = Environment(self, db, uid, context=context) self._login = login self._password = password else: raise error.RPCError("Wrong login ID or password")
python
def login(self, db, login='admin', password='admin'): # Get the user's ID and generate the corresponding user record data = self.json( '/web/session/authenticate', {'db': db, 'login': login, 'password': password}) uid = data['result']['uid'] if uid: context = data['result']['user_context'] self._env = Environment(self, db, uid, context=context) self._login = login self._password = password else: raise error.RPCError("Wrong login ID or password")
[ "def", "login", "(", "self", ",", "db", ",", "login", "=", "'admin'", ",", "password", "=", "'admin'", ")", ":", "# Get the user's ID and generate the corresponding user record", "data", "=", "self", ".", "json", "(", "'/web/session/authenticate'", ",", "{", "'db'...
Log in as the given `user` with the password `passwd` on the database `db`. .. doctest:: :options: +SKIP >>> odoo.login('db_name', 'admin', 'admin') >>> odoo.env.user.name 'Administrator' *Python 2:* :raise: :class:`odoorpc.error.RPCError` :raise: `urllib2.URLError` (connection error) *Python 3:* :raise: :class:`odoorpc.error.RPCError` :raise: `urllib.error.URLError` (connection error)
[ "Log", "in", "as", "the", "given", "user", "with", "the", "password", "passwd", "on", "the", "database", "db", "." ]
d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/odoo.py#L331-L363
20,697
OCA/odoorpc
odoorpc/odoo.py
ODOO.exec_workflow
def exec_workflow(self, model, record_id, signal): """Execute the workflow `signal` on the instance having the ID `record_id` of `model`. *Python 2:* :raise: :class:`odoorpc.error.RPCError` :raise: :class:`odoorpc.error.InternalError` (if not logged) :raise: `urllib2.URLError` (connection error) *Python 3:* :raise: :class:`odoorpc.error.RPCError` :raise: :class:`odoorpc.error.InternalError` (if not logged) :raise: `urllib.error.URLError` (connection error) """ if tools.v(self.version)[0] >= 11: raise DeprecationWarning( u"Workflows have been removed in Odoo >= 11.0") self._check_logged_user() # Execute the workflow query args_to_send = [self.env.db, self.env.uid, self._password, model, signal, record_id] data = self.json( '/jsonrpc', {'service': 'object', 'method': 'exec_workflow', 'args': args_to_send}) return data.get('result')
python
def exec_workflow(self, model, record_id, signal): if tools.v(self.version)[0] >= 11: raise DeprecationWarning( u"Workflows have been removed in Odoo >= 11.0") self._check_logged_user() # Execute the workflow query args_to_send = [self.env.db, self.env.uid, self._password, model, signal, record_id] data = self.json( '/jsonrpc', {'service': 'object', 'method': 'exec_workflow', 'args': args_to_send}) return data.get('result')
[ "def", "exec_workflow", "(", "self", ",", "model", ",", "record_id", ",", "signal", ")", ":", "if", "tools", ".", "v", "(", "self", ".", "version", ")", "[", "0", "]", ">=", "11", ":", "raise", "DeprecationWarning", "(", "u\"Workflows have been removed in ...
Execute the workflow `signal` on the instance having the ID `record_id` of `model`. *Python 2:* :raise: :class:`odoorpc.error.RPCError` :raise: :class:`odoorpc.error.InternalError` (if not logged) :raise: `urllib2.URLError` (connection error) *Python 3:* :raise: :class:`odoorpc.error.RPCError` :raise: :class:`odoorpc.error.InternalError` (if not logged) :raise: `urllib.error.URLError` (connection error)
[ "Execute", "the", "workflow", "signal", "on", "the", "instance", "having", "the", "ID", "record_id", "of", "model", "." ]
d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/odoo.py#L489-L517
20,698
OCA/odoorpc
odoorpc/db.py
DB.create
def create(self, password, db, demo=False, lang='en_US', admin_password='admin'): """Request the server to create a new database named `db` which will have `admin_password` as administrator password and localized with the `lang` parameter. You have to set the flag `demo` to `True` in order to insert demonstration data. >>> odoo.db.create('super_admin_passwd', 'prod', False, 'fr_FR', 'my_admin_passwd') # doctest: +SKIP If you get a timeout error, increase this one before performing the request: >>> timeout_backup = odoo.config['timeout'] >>> odoo.config['timeout'] = 600 # Timeout set to 10 minutes >>> odoo.db.create('super_admin_passwd', 'prod', False, 'fr_FR', 'my_admin_passwd') # doctest: +SKIP >>> odoo.config['timeout'] = timeout_backup The super administrator password is required to perform this method. *Python 2:* :raise: :class:`odoorpc.error.RPCError` (access denied) :raise: `urllib2.URLError` (connection error) *Python 3:* :raise: :class:`odoorpc.error.RPCError` (access denied) :raise: `urllib.error.URLError` (connection error) """ self._odoo.json( '/jsonrpc', {'service': 'db', 'method': 'create_database', 'args': [password, db, demo, lang, admin_password]})
python
def create(self, password, db, demo=False, lang='en_US', admin_password='admin'): self._odoo.json( '/jsonrpc', {'service': 'db', 'method': 'create_database', 'args': [password, db, demo, lang, admin_password]})
[ "def", "create", "(", "self", ",", "password", ",", "db", ",", "demo", "=", "False", ",", "lang", "=", "'en_US'", ",", "admin_password", "=", "'admin'", ")", ":", "self", ".", "_odoo", ".", "json", "(", "'/jsonrpc'", ",", "{", "'service'", ":", "'db'...
Request the server to create a new database named `db` which will have `admin_password` as administrator password and localized with the `lang` parameter. You have to set the flag `demo` to `True` in order to insert demonstration data. >>> odoo.db.create('super_admin_passwd', 'prod', False, 'fr_FR', 'my_admin_passwd') # doctest: +SKIP If you get a timeout error, increase this one before performing the request: >>> timeout_backup = odoo.config['timeout'] >>> odoo.config['timeout'] = 600 # Timeout set to 10 minutes >>> odoo.db.create('super_admin_passwd', 'prod', False, 'fr_FR', 'my_admin_passwd') # doctest: +SKIP >>> odoo.config['timeout'] = timeout_backup The super administrator password is required to perform this method. *Python 2:* :raise: :class:`odoorpc.error.RPCError` (access denied) :raise: `urllib2.URLError` (connection error) *Python 3:* :raise: :class:`odoorpc.error.RPCError` (access denied) :raise: `urllib.error.URLError` (connection error)
[ "Request", "the", "server", "to", "create", "a", "new", "database", "named", "db", "which", "will", "have", "admin_password", "as", "administrator", "password", "and", "localized", "with", "the", "lang", "parameter", ".", "You", "have", "to", "set", "the", "...
d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/db.py#L167-L200
20,699
OCA/odoorpc
odoorpc/db.py
DB.duplicate
def duplicate(self, password, db, new_db): """Duplicate `db' as `new_db`. >>> odoo.db.duplicate('super_admin_passwd', 'prod', 'test') # doctest: +SKIP The super administrator password is required to perform this method. *Python 2:* :raise: :class:`odoorpc.error.RPCError` (access denied / wrong database) :raise: `urllib2.URLError` (connection error) *Python 3:* :raise: :class:`odoorpc.error.RPCError` (access denied / wrong database) :raise: `urllib.error.URLError` (connection error) """ self._odoo.json( '/jsonrpc', {'service': 'db', 'method': 'duplicate_database', 'args': [password, db, new_db]})
python
def duplicate(self, password, db, new_db): self._odoo.json( '/jsonrpc', {'service': 'db', 'method': 'duplicate_database', 'args': [password, db, new_db]})
[ "def", "duplicate", "(", "self", ",", "password", ",", "db", ",", "new_db", ")", ":", "self", ".", "_odoo", ".", "json", "(", "'/jsonrpc'", ",", "{", "'service'", ":", "'db'", ",", "'method'", ":", "'duplicate_database'", ",", "'args'", ":", "[", "pass...
Duplicate `db' as `new_db`. >>> odoo.db.duplicate('super_admin_passwd', 'prod', 'test') # doctest: +SKIP The super administrator password is required to perform this method. *Python 2:* :raise: :class:`odoorpc.error.RPCError` (access denied / wrong database) :raise: `urllib2.URLError` (connection error) *Python 3:* :raise: :class:`odoorpc.error.RPCError` (access denied / wrong database) :raise: `urllib.error.URLError` (connection error)
[ "Duplicate", "db", "as", "new_db", "." ]
d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/db.py#L233-L254