repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
last-partizan/pytils
pytils/numeral.py
_sum_string_fn
def _sum_string_fn(into, tmp_val, gender, items=None): """ Make in-words representation of single order @param into: in-words representation of lower orders @type into: C{unicode} @param tmp_val: temporary value without lower orders @type tmp_val: C{integer types} @param gender: gender (MALE, FEMALE or NEUTER) @type gender: C{int} @param items: variants of objects @type items: 3-element C{sequence} of C{unicode} @return: new into and tmp_val @rtype: C{tuple} @raise ValueError: tmp_val is negative """ if items is None: items = (u"", u"", u"") one_item, two_items, five_items = items check_positive(tmp_val) if tmp_val == 0: return into, tmp_val words = [] rest = tmp_val % 1000 tmp_val = tmp_val // 1000 if rest == 0: # последние три знака нулевые if into == u"": into = u"%s " % five_items return into, tmp_val # начинаем подсчет с rest end_word = five_items # сотни words.append(HUNDREDS[rest // 100]) # десятки rest = rest % 100 rest1 = rest // 10 # особый случай -- tens=1 tens = rest1 == 1 and TENS[rest] or TENS[rest1] words.append(tens) # единицы if rest1 < 1 or rest1 > 1: amount = rest % 10 end_word = choose_plural(amount, items) words.append(ONES[amount][gender-1]) words.append(end_word) # добавляем то, что уже было words.append(into) # убираем пустые подстроки words = filter(lambda x: len(x) > 0, words) # склеиваем и отдаем return u" ".join(words).strip(), tmp_val
python
def _sum_string_fn(into, tmp_val, gender, items=None): """ Make in-words representation of single order @param into: in-words representation of lower orders @type into: C{unicode} @param tmp_val: temporary value without lower orders @type tmp_val: C{integer types} @param gender: gender (MALE, FEMALE or NEUTER) @type gender: C{int} @param items: variants of objects @type items: 3-element C{sequence} of C{unicode} @return: new into and tmp_val @rtype: C{tuple} @raise ValueError: tmp_val is negative """ if items is None: items = (u"", u"", u"") one_item, two_items, five_items = items check_positive(tmp_val) if tmp_val == 0: return into, tmp_val words = [] rest = tmp_val % 1000 tmp_val = tmp_val // 1000 if rest == 0: # последние три знака нулевые if into == u"": into = u"%s " % five_items return into, tmp_val # начинаем подсчет с rest end_word = five_items # сотни words.append(HUNDREDS[rest // 100]) # десятки rest = rest % 100 rest1 = rest // 10 # особый случай -- tens=1 tens = rest1 == 1 and TENS[rest] or TENS[rest1] words.append(tens) # единицы if rest1 < 1 or rest1 > 1: amount = rest % 10 end_word = choose_plural(amount, items) words.append(ONES[amount][gender-1]) words.append(end_word) # добавляем то, что уже было words.append(into) # убираем пустые подстроки words = filter(lambda x: len(x) > 0, words) # склеиваем и отдаем return u" ".join(words).strip(), tmp_val
[ "def", "_sum_string_fn", "(", "into", ",", "tmp_val", ",", "gender", ",", "items", "=", "None", ")", ":", "if", "items", "is", "None", ":", "items", "=", "(", "u\"\"", ",", "u\"\"", ",", "u\"\"", ")", "one_item", ",", "two_items", ",", "five_items", "=", "items", "check_positive", "(", "tmp_val", ")", "if", "tmp_val", "==", "0", ":", "return", "into", ",", "tmp_val", "words", "=", "[", "]", "rest", "=", "tmp_val", "%", "1000", "tmp_val", "=", "tmp_val", "//", "1000", "if", "rest", "==", "0", ":", "# последние три знака нулевые", "if", "into", "==", "u\"\"", ":", "into", "=", "u\"%s \"", "%", "five_items", "return", "into", ",", "tmp_val", "# начинаем подсчет с rest", "end_word", "=", "five_items", "# сотни", "words", ".", "append", "(", "HUNDREDS", "[", "rest", "//", "100", "]", ")", "# десятки", "rest", "=", "rest", "%", "100", "rest1", "=", "rest", "//", "10", "# особый случай -- tens=1", "tens", "=", "rest1", "==", "1", "and", "TENS", "[", "rest", "]", "or", "TENS", "[", "rest1", "]", "words", ".", "append", "(", "tens", ")", "# единицы", "if", "rest1", "<", "1", "or", "rest1", ">", "1", ":", "amount", "=", "rest", "%", "10", "end_word", "=", "choose_plural", "(", "amount", ",", "items", ")", "words", ".", "append", "(", "ONES", "[", "amount", "]", "[", "gender", "-", "1", "]", ")", "words", ".", "append", "(", "end_word", ")", "# добавляем то, что уже было", "words", ".", "append", "(", "into", ")", "# убираем пустые подстроки", "words", "=", "filter", "(", "lambda", "x", ":", "len", "(", "x", ")", ">", "0", ",", "words", ")", "# склеиваем и отдаем", "return", "u\" \"", ".", "join", "(", "words", ")", ".", "strip", "(", ")", ",", "tmp_val" ]
Make in-words representation of single order @param into: in-words representation of lower orders @type into: C{unicode} @param tmp_val: temporary value without lower orders @type tmp_val: C{integer types} @param gender: gender (MALE, FEMALE or NEUTER) @type gender: C{int} @param items: variants of objects @type items: 3-element C{sequence} of C{unicode} @return: new into and tmp_val @rtype: C{tuple} @raise ValueError: tmp_val is negative
[ "Make", "in", "-", "words", "representation", "of", "single", "order" ]
1c570a32b15e564bc68587b8207e32d464e61d08
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/numeral.py#L388-L455
train
last-partizan/pytils
pytils/utils.py
check_length
def check_length(value, length): """ Checks length of value @param value: value to check @type value: C{str} @param length: length checking for @type length: C{int} @return: None when check successful @raise ValueError: check failed """ _length = len(value) if _length != length: raise ValueError("length must be %d, not %d" % \ (length, _length))
python
def check_length(value, length): """ Checks length of value @param value: value to check @type value: C{str} @param length: length checking for @type length: C{int} @return: None when check successful @raise ValueError: check failed """ _length = len(value) if _length != length: raise ValueError("length must be %d, not %d" % \ (length, _length))
[ "def", "check_length", "(", "value", ",", "length", ")", ":", "_length", "=", "len", "(", "value", ")", "if", "_length", "!=", "length", ":", "raise", "ValueError", "(", "\"length must be %d, not %d\"", "%", "(", "length", ",", "_length", ")", ")" ]
Checks length of value @param value: value to check @type value: C{str} @param length: length checking for @type length: C{int} @return: None when check successful @raise ValueError: check failed
[ "Checks", "length", "of", "value" ]
1c570a32b15e564bc68587b8207e32d464e61d08
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/utils.py#L10-L27
train
last-partizan/pytils
pytils/utils.py
check_positive
def check_positive(value, strict=False): """ Checks if variable is positive @param value: value to check @type value: C{integer types}, C{float} or C{Decimal} @return: None when check successful @raise ValueError: check failed """ if not strict and value < 0: raise ValueError("Value must be positive or zero, not %s" % str(value)) if strict and value <= 0: raise ValueError("Value must be positive, not %s" % str(value))
python
def check_positive(value, strict=False): """ Checks if variable is positive @param value: value to check @type value: C{integer types}, C{float} or C{Decimal} @return: None when check successful @raise ValueError: check failed """ if not strict and value < 0: raise ValueError("Value must be positive or zero, not %s" % str(value)) if strict and value <= 0: raise ValueError("Value must be positive, not %s" % str(value))
[ "def", "check_positive", "(", "value", ",", "strict", "=", "False", ")", ":", "if", "not", "strict", "and", "value", "<", "0", ":", "raise", "ValueError", "(", "\"Value must be positive or zero, not %s\"", "%", "str", "(", "value", ")", ")", "if", "strict", "and", "value", "<=", "0", ":", "raise", "ValueError", "(", "\"Value must be positive, not %s\"", "%", "str", "(", "value", ")", ")" ]
Checks if variable is positive @param value: value to check @type value: C{integer types}, C{float} or C{Decimal} @return: None when check successful @raise ValueError: check failed
[ "Checks", "if", "variable", "is", "positive" ]
1c570a32b15e564bc68587b8207e32d464e61d08
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/utils.py#L30-L44
train
last-partizan/pytils
pytils/templatetags/pytils_translit.py
detranslify
def detranslify(text): """Detranslify russian text""" try: res = translit.detranslify(text) except Exception as err: # because filter must die silently res = default_value % {'error': err, 'value': text} return res
python
def detranslify(text): """Detranslify russian text""" try: res = translit.detranslify(text) except Exception as err: # because filter must die silently res = default_value % {'error': err, 'value': text} return res
[ "def", "detranslify", "(", "text", ")", ":", "try", ":", "res", "=", "translit", ".", "detranslify", "(", "text", ")", "except", "Exception", "as", "err", ":", "# because filter must die silently", "res", "=", "default_value", "%", "{", "'error'", ":", "err", ",", "'value'", ":", "text", "}", "return", "res" ]
Detranslify russian text
[ "Detranslify", "russian", "text" ]
1c570a32b15e564bc68587b8207e32d464e61d08
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/templatetags/pytils_translit.py#L36-L43
train
larsyencken/csvdiff
csvdiff/patch.py
apply
def apply(diff, recs, strict=True): """ Transform the records with the patch. May fail if the records do not match those expected in the patch. """ index_columns = diff['_index'] indexed = records.index(copy.deepcopy(list(recs)), index_columns) _add_records(indexed, diff['added'], index_columns, strict=strict) _remove_records(indexed, diff['removed'], index_columns, strict=strict) _update_records(indexed, diff['changed'], strict=strict) return records.sort(indexed.values())
python
def apply(diff, recs, strict=True): """ Transform the records with the patch. May fail if the records do not match those expected in the patch. """ index_columns = diff['_index'] indexed = records.index(copy.deepcopy(list(recs)), index_columns) _add_records(indexed, diff['added'], index_columns, strict=strict) _remove_records(indexed, diff['removed'], index_columns, strict=strict) _update_records(indexed, diff['changed'], strict=strict) return records.sort(indexed.values())
[ "def", "apply", "(", "diff", ",", "recs", ",", "strict", "=", "True", ")", ":", "index_columns", "=", "diff", "[", "'_index'", "]", "indexed", "=", "records", ".", "index", "(", "copy", ".", "deepcopy", "(", "list", "(", "recs", ")", ")", ",", "index_columns", ")", "_add_records", "(", "indexed", ",", "diff", "[", "'added'", "]", ",", "index_columns", ",", "strict", "=", "strict", ")", "_remove_records", "(", "indexed", ",", "diff", "[", "'removed'", "]", ",", "index_columns", ",", "strict", "=", "strict", ")", "_update_records", "(", "indexed", ",", "diff", "[", "'changed'", "]", ",", "strict", "=", "strict", ")", "return", "records", ".", "sort", "(", "indexed", ".", "values", "(", ")", ")" ]
Transform the records with the patch. May fail if the records do not match those expected in the patch.
[ "Transform", "the", "records", "with", "the", "patch", ".", "May", "fail", "if", "the", "records", "do", "not", "match", "those", "expected", "in", "the", "patch", "." ]
163dd9da676a8e5f926a935803726340261f03ae
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L106-L116
train
larsyencken/csvdiff
csvdiff/patch.py
load
def load(istream, strict=True): "Deserialize a patch object." try: diff = json.load(istream) if strict: jsonschema.validate(diff, SCHEMA) except ValueError: raise InvalidPatchError('patch is not valid JSON') except jsonschema.exceptions.ValidationError as e: raise InvalidPatchError(e.message) return diff
python
def load(istream, strict=True): "Deserialize a patch object." try: diff = json.load(istream) if strict: jsonschema.validate(diff, SCHEMA) except ValueError: raise InvalidPatchError('patch is not valid JSON') except jsonschema.exceptions.ValidationError as e: raise InvalidPatchError(e.message) return diff
[ "def", "load", "(", "istream", ",", "strict", "=", "True", ")", ":", "try", ":", "diff", "=", "json", ".", "load", "(", "istream", ")", "if", "strict", ":", "jsonschema", ".", "validate", "(", "diff", ",", "SCHEMA", ")", "except", "ValueError", ":", "raise", "InvalidPatchError", "(", "'patch is not valid JSON'", ")", "except", "jsonschema", ".", "exceptions", ".", "ValidationError", "as", "e", ":", "raise", "InvalidPatchError", "(", "e", ".", "message", ")", "return", "diff" ]
Deserialize a patch object.
[ "Deserialize", "a", "patch", "object", "." ]
163dd9da676a8e5f926a935803726340261f03ae
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L175-L187
train
larsyencken/csvdiff
csvdiff/patch.py
save
def save(diff, stream=sys.stdout, compact=False): "Serialize a patch object." flags = {'sort_keys': True} if not compact: flags['indent'] = 2 json.dump(diff, stream, **flags)
python
def save(diff, stream=sys.stdout, compact=False): "Serialize a patch object." flags = {'sort_keys': True} if not compact: flags['indent'] = 2 json.dump(diff, stream, **flags)
[ "def", "save", "(", "diff", ",", "stream", "=", "sys", ".", "stdout", ",", "compact", "=", "False", ")", ":", "flags", "=", "{", "'sort_keys'", ":", "True", "}", "if", "not", "compact", ":", "flags", "[", "'indent'", "]", "=", "2", "json", ".", "dump", "(", "diff", ",", "stream", ",", "*", "*", "flags", ")" ]
Serialize a patch object.
[ "Serialize", "a", "patch", "object", "." ]
163dd9da676a8e5f926a935803726340261f03ae
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L190-L196
train
larsyencken/csvdiff
csvdiff/patch.py
create
def create(from_records, to_records, index_columns, ignore_columns=None): """ Diff two sets of records, using the index columns as the primary key for both datasets. """ from_indexed = records.index(from_records, index_columns) to_indexed = records.index(to_records, index_columns) if ignore_columns is not None: from_indexed = records.filter_ignored(from_indexed, ignore_columns) to_indexed = records.filter_ignored(to_indexed, ignore_columns) return create_indexed(from_indexed, to_indexed, index_columns)
python
def create(from_records, to_records, index_columns, ignore_columns=None): """ Diff two sets of records, using the index columns as the primary key for both datasets. """ from_indexed = records.index(from_records, index_columns) to_indexed = records.index(to_records, index_columns) if ignore_columns is not None: from_indexed = records.filter_ignored(from_indexed, ignore_columns) to_indexed = records.filter_ignored(to_indexed, ignore_columns) return create_indexed(from_indexed, to_indexed, index_columns)
[ "def", "create", "(", "from_records", ",", "to_records", ",", "index_columns", ",", "ignore_columns", "=", "None", ")", ":", "from_indexed", "=", "records", ".", "index", "(", "from_records", ",", "index_columns", ")", "to_indexed", "=", "records", ".", "index", "(", "to_records", ",", "index_columns", ")", "if", "ignore_columns", "is", "not", "None", ":", "from_indexed", "=", "records", ".", "filter_ignored", "(", "from_indexed", ",", "ignore_columns", ")", "to_indexed", "=", "records", ".", "filter_ignored", "(", "to_indexed", ",", "ignore_columns", ")", "return", "create_indexed", "(", "from_indexed", ",", "to_indexed", ",", "index_columns", ")" ]
Diff two sets of records, using the index columns as the primary key for both datasets.
[ "Diff", "two", "sets", "of", "records", "using", "the", "index", "columns", "as", "the", "primary", "key", "for", "both", "datasets", "." ]
163dd9da676a8e5f926a935803726340261f03ae
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L199-L211
train
larsyencken/csvdiff
csvdiff/patch.py
_compare_rows
def _compare_rows(from_recs, to_recs, keys): "Return the set of keys which have changed." return set( k for k in keys if sorted(from_recs[k].items()) != sorted(to_recs[k].items()) )
python
def _compare_rows(from_recs, to_recs, keys): "Return the set of keys which have changed." return set( k for k in keys if sorted(from_recs[k].items()) != sorted(to_recs[k].items()) )
[ "def", "_compare_rows", "(", "from_recs", ",", "to_recs", ",", "keys", ")", ":", "return", "set", "(", "k", "for", "k", "in", "keys", "if", "sorted", "(", "from_recs", "[", "k", "]", ".", "items", "(", ")", ")", "!=", "sorted", "(", "to_recs", "[", "k", "]", ".", "items", "(", ")", ")", ")" ]
Return the set of keys which have changed.
[ "Return", "the", "set", "of", "keys", "which", "have", "changed", "." ]
163dd9da676a8e5f926a935803726340261f03ae
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L236-L241
train
larsyencken/csvdiff
csvdiff/patch.py
record_diff
def record_diff(lhs, rhs): "Diff an individual row." delta = {} for k in set(lhs).union(rhs): from_ = lhs[k] to_ = rhs[k] if from_ != to_: delta[k] = {'from': from_, 'to': to_} return delta
python
def record_diff(lhs, rhs): "Diff an individual row." delta = {} for k in set(lhs).union(rhs): from_ = lhs[k] to_ = rhs[k] if from_ != to_: delta[k] = {'from': from_, 'to': to_} return delta
[ "def", "record_diff", "(", "lhs", ",", "rhs", ")", ":", "delta", "=", "{", "}", "for", "k", "in", "set", "(", "lhs", ")", ".", "union", "(", "rhs", ")", ":", "from_", "=", "lhs", "[", "k", "]", "to_", "=", "rhs", "[", "k", "]", "if", "from_", "!=", "to_", ":", "delta", "[", "k", "]", "=", "{", "'from'", ":", "from_", ",", "'to'", ":", "to_", "}", "return", "delta" ]
Diff an individual row.
[ "Diff", "an", "individual", "row", "." ]
163dd9da676a8e5f926a935803726340261f03ae
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L260-L269
train
larsyencken/csvdiff
csvdiff/patch.py
filter_significance
def filter_significance(diff, significance): """ Prune any changes in the patch which are due to numeric changes less than this level of significance. """ changed = diff['changed'] # remove individual field changes that are significant reduced = [{'key': delta['key'], 'fields': {k: v for k, v in delta['fields'].items() if _is_significant(v, significance)}} for delta in changed] # call a key changed only if it still has significant changes filtered = [delta for delta in reduced if delta['fields']] diff = diff.copy() diff['changed'] = filtered return diff
python
def filter_significance(diff, significance): """ Prune any changes in the patch which are due to numeric changes less than this level of significance. """ changed = diff['changed'] # remove individual field changes that are significant reduced = [{'key': delta['key'], 'fields': {k: v for k, v in delta['fields'].items() if _is_significant(v, significance)}} for delta in changed] # call a key changed only if it still has significant changes filtered = [delta for delta in reduced if delta['fields']] diff = diff.copy() diff['changed'] = filtered return diff
[ "def", "filter_significance", "(", "diff", ",", "significance", ")", ":", "changed", "=", "diff", "[", "'changed'", "]", "# remove individual field changes that are significant", "reduced", "=", "[", "{", "'key'", ":", "delta", "[", "'key'", "]", ",", "'fields'", ":", "{", "k", ":", "v", "for", "k", ",", "v", "in", "delta", "[", "'fields'", "]", ".", "items", "(", ")", "if", "_is_significant", "(", "v", ",", "significance", ")", "}", "}", "for", "delta", "in", "changed", "]", "# call a key changed only if it still has significant changes", "filtered", "=", "[", "delta", "for", "delta", "in", "reduced", "if", "delta", "[", "'fields'", "]", "]", "diff", "=", "diff", ".", "copy", "(", ")", "diff", "[", "'changed'", "]", "=", "filtered", "return", "diff" ]
Prune any changes in the patch which are due to numeric changes less than this level of significance.
[ "Prune", "any", "changes", "in", "the", "patch", "which", "are", "due", "to", "numeric", "changes", "less", "than", "this", "level", "of", "significance", "." ]
163dd9da676a8e5f926a935803726340261f03ae
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L304-L323
train
larsyencken/csvdiff
csvdiff/patch.py
_is_significant
def _is_significant(change, significance): """ Return True if a change is genuinely significant given our tolerance. """ try: a = float(change['from']) b = float(change['to']) except ValueError: return True return abs(a - b) > 10 ** (-significance)
python
def _is_significant(change, significance): """ Return True if a change is genuinely significant given our tolerance. """ try: a = float(change['from']) b = float(change['to']) except ValueError: return True return abs(a - b) > 10 ** (-significance)
[ "def", "_is_significant", "(", "change", ",", "significance", ")", ":", "try", ":", "a", "=", "float", "(", "change", "[", "'from'", "]", ")", "b", "=", "float", "(", "change", "[", "'to'", "]", ")", "except", "ValueError", ":", "return", "True", "return", "abs", "(", "a", "-", "b", ")", ">", "10", "**", "(", "-", "significance", ")" ]
Return True if a change is genuinely significant given our tolerance.
[ "Return", "True", "if", "a", "change", "is", "genuinely", "significant", "given", "our", "tolerance", "." ]
163dd9da676a8e5f926a935803726340261f03ae
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L326-L337
train
larsyencken/csvdiff
csvdiff/__init__.py
diff_files
def diff_files(from_file, to_file, index_columns, sep=',', ignored_columns=None): """ Diff two CSV files, returning the patch which transforms one into the other. """ with open(from_file) as from_stream: with open(to_file) as to_stream: from_records = records.load(from_stream, sep=sep) to_records = records.load(to_stream, sep=sep) return patch.create(from_records, to_records, index_columns, ignore_columns=ignored_columns)
python
def diff_files(from_file, to_file, index_columns, sep=',', ignored_columns=None): """ Diff two CSV files, returning the patch which transforms one into the other. """ with open(from_file) as from_stream: with open(to_file) as to_stream: from_records = records.load(from_stream, sep=sep) to_records = records.load(to_stream, sep=sep) return patch.create(from_records, to_records, index_columns, ignore_columns=ignored_columns)
[ "def", "diff_files", "(", "from_file", ",", "to_file", ",", "index_columns", ",", "sep", "=", "','", ",", "ignored_columns", "=", "None", ")", ":", "with", "open", "(", "from_file", ")", "as", "from_stream", ":", "with", "open", "(", "to_file", ")", "as", "to_stream", ":", "from_records", "=", "records", ".", "load", "(", "from_stream", ",", "sep", "=", "sep", ")", "to_records", "=", "records", ".", "load", "(", "to_stream", ",", "sep", "=", "sep", ")", "return", "patch", ".", "create", "(", "from_records", ",", "to_records", ",", "index_columns", ",", "ignore_columns", "=", "ignored_columns", ")" ]
Diff two CSV files, returning the patch which transforms one into the other.
[ "Diff", "two", "CSV", "files", "returning", "the", "patch", "which", "transforms", "one", "into", "the", "other", "." ]
163dd9da676a8e5f926a935803726340261f03ae
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/__init__.py#L28-L38
train
larsyencken/csvdiff
csvdiff/__init__.py
patch_file
def patch_file(patch_stream: TextIO, fromcsv_stream: TextIO, tocsv_stream: TextIO, strict: bool = True, sep: str = ','): """ Apply the patch to the source CSV file, and save the result to the target file. """ diff = patch.load(patch_stream) from_records = records.load(fromcsv_stream, sep=sep) to_records = patch.apply(diff, from_records, strict=strict) # what order should the columns be in? if to_records: # have data, use a nice ordering all_columns = to_records[0].keys() index_columns = diff['_index'] fieldnames = _nice_fieldnames(all_columns, index_columns) else: # no data, use the original order fieldnames = from_records.fieldnames records.save(to_records, fieldnames, tocsv_stream)
python
def patch_file(patch_stream: TextIO, fromcsv_stream: TextIO, tocsv_stream: TextIO, strict: bool = True, sep: str = ','): """ Apply the patch to the source CSV file, and save the result to the target file. """ diff = patch.load(patch_stream) from_records = records.load(fromcsv_stream, sep=sep) to_records = patch.apply(diff, from_records, strict=strict) # what order should the columns be in? if to_records: # have data, use a nice ordering all_columns = to_records[0].keys() index_columns = diff['_index'] fieldnames = _nice_fieldnames(all_columns, index_columns) else: # no data, use the original order fieldnames = from_records.fieldnames records.save(to_records, fieldnames, tocsv_stream)
[ "def", "patch_file", "(", "patch_stream", ":", "TextIO", ",", "fromcsv_stream", ":", "TextIO", ",", "tocsv_stream", ":", "TextIO", ",", "strict", ":", "bool", "=", "True", ",", "sep", ":", "str", "=", "','", ")", ":", "diff", "=", "patch", ".", "load", "(", "patch_stream", ")", "from_records", "=", "records", ".", "load", "(", "fromcsv_stream", ",", "sep", "=", "sep", ")", "to_records", "=", "patch", ".", "apply", "(", "diff", ",", "from_records", ",", "strict", "=", "strict", ")", "# what order should the columns be in?", "if", "to_records", ":", "# have data, use a nice ordering", "all_columns", "=", "to_records", "[", "0", "]", ".", "keys", "(", ")", "index_columns", "=", "diff", "[", "'_index'", "]", "fieldnames", "=", "_nice_fieldnames", "(", "all_columns", ",", "index_columns", ")", "else", ":", "# no data, use the original order", "fieldnames", "=", "from_records", ".", "fieldnames", "records", ".", "save", "(", "to_records", ",", "fieldnames", ",", "tocsv_stream", ")" ]
Apply the patch to the source CSV file, and save the result to the target file.
[ "Apply", "the", "patch", "to", "the", "source", "CSV", "file", "and", "save", "the", "result", "to", "the", "target", "file", "." ]
163dd9da676a8e5f926a935803726340261f03ae
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/__init__.py#L49-L70
train
larsyencken/csvdiff
csvdiff/__init__.py
patch_records
def patch_records(diff, from_records, strict=True): """ Apply the patch to the sequence of records, returning the transformed records. """ return patch.apply(diff, from_records, strict=strict)
python
def patch_records(diff, from_records, strict=True): """ Apply the patch to the sequence of records, returning the transformed records. """ return patch.apply(diff, from_records, strict=strict)
[ "def", "patch_records", "(", "diff", ",", "from_records", ",", "strict", "=", "True", ")", ":", "return", "patch", ".", "apply", "(", "diff", ",", "from_records", ",", "strict", "=", "strict", ")" ]
Apply the patch to the sequence of records, returning the transformed records.
[ "Apply", "the", "patch", "to", "the", "sequence", "of", "records", "returning", "the", "transformed", "records", "." ]
163dd9da676a8e5f926a935803726340261f03ae
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/__init__.py#L73-L78
train
larsyencken/csvdiff
csvdiff/__init__.py
_nice_fieldnames
def _nice_fieldnames(all_columns, index_columns): "Indexes on the left, other fields in alphabetical order on the right." non_index_columns = set(all_columns).difference(index_columns) return index_columns + sorted(non_index_columns)
python
def _nice_fieldnames(all_columns, index_columns): "Indexes on the left, other fields in alphabetical order on the right." non_index_columns = set(all_columns).difference(index_columns) return index_columns + sorted(non_index_columns)
[ "def", "_nice_fieldnames", "(", "all_columns", ",", "index_columns", ")", ":", "non_index_columns", "=", "set", "(", "all_columns", ")", ".", "difference", "(", "index_columns", ")", "return", "index_columns", "+", "sorted", "(", "non_index_columns", ")" ]
Indexes on the left, other fields in alphabetical order on the right.
[ "Indexes", "on", "the", "left", "other", "fields", "in", "alphabetical", "order", "on", "the", "right", "." ]
163dd9da676a8e5f926a935803726340261f03ae
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/__init__.py#L81-L84
train
larsyencken/csvdiff
csvdiff/__init__.py
csvdiff_cmd
def csvdiff_cmd(index_columns, from_csv, to_csv, style=None, output=None, sep=',', quiet=False, ignore_columns=None, significance=None): """ Compare two csv files to see what rows differ between them. The files are each expected to have a header row, and for each row to be uniquely identified by one or more indexing columns. """ if ignore_columns is not None: for i in ignore_columns: if i in index_columns: error.abort("You can't ignore an index column") ostream = (open(output, 'w') if output else io.StringIO() if quiet else sys.stdout) try: if style == 'summary': _diff_and_summarize(from_csv, to_csv, index_columns, ostream, sep=sep, ignored_columns=ignore_columns, significance=significance) else: compact = (style == 'compact') _diff_files_to_stream(from_csv, to_csv, index_columns, ostream, compact=compact, sep=sep, ignored_columns=ignore_columns, significance=significance) except records.InvalidKeyError as e: error.abort(e.args[0]) finally: ostream.close()
python
def csvdiff_cmd(index_columns, from_csv, to_csv, style=None, output=None, sep=',', quiet=False, ignore_columns=None, significance=None): """ Compare two csv files to see what rows differ between them. The files are each expected to have a header row, and for each row to be uniquely identified by one or more indexing columns. """ if ignore_columns is not None: for i in ignore_columns: if i in index_columns: error.abort("You can't ignore an index column") ostream = (open(output, 'w') if output else io.StringIO() if quiet else sys.stdout) try: if style == 'summary': _diff_and_summarize(from_csv, to_csv, index_columns, ostream, sep=sep, ignored_columns=ignore_columns, significance=significance) else: compact = (style == 'compact') _diff_files_to_stream(from_csv, to_csv, index_columns, ostream, compact=compact, sep=sep, ignored_columns=ignore_columns, significance=significance) except records.InvalidKeyError as e: error.abort(e.args[0]) finally: ostream.close()
[ "def", "csvdiff_cmd", "(", "index_columns", ",", "from_csv", ",", "to_csv", ",", "style", "=", "None", ",", "output", "=", "None", ",", "sep", "=", "','", ",", "quiet", "=", "False", ",", "ignore_columns", "=", "None", ",", "significance", "=", "None", ")", ":", "if", "ignore_columns", "is", "not", "None", ":", "for", "i", "in", "ignore_columns", ":", "if", "i", "in", "index_columns", ":", "error", ".", "abort", "(", "\"You can't ignore an index column\"", ")", "ostream", "=", "(", "open", "(", "output", ",", "'w'", ")", "if", "output", "else", "io", ".", "StringIO", "(", ")", "if", "quiet", "else", "sys", ".", "stdout", ")", "try", ":", "if", "style", "==", "'summary'", ":", "_diff_and_summarize", "(", "from_csv", ",", "to_csv", ",", "index_columns", ",", "ostream", ",", "sep", "=", "sep", ",", "ignored_columns", "=", "ignore_columns", ",", "significance", "=", "significance", ")", "else", ":", "compact", "=", "(", "style", "==", "'compact'", ")", "_diff_files_to_stream", "(", "from_csv", ",", "to_csv", ",", "index_columns", ",", "ostream", ",", "compact", "=", "compact", ",", "sep", "=", "sep", ",", "ignored_columns", "=", "ignore_columns", ",", "significance", "=", "significance", ")", "except", "records", ".", "InvalidKeyError", "as", "e", ":", "error", ".", "abort", "(", "e", ".", "args", "[", "0", "]", ")", "finally", ":", "ostream", ".", "close", "(", ")" ]
Compare two csv files to see what rows differ between them. The files are each expected to have a header row, and for each row to be uniquely identified by one or more indexing columns.
[ "Compare", "two", "csv", "files", "to", "see", "what", "rows", "differ", "between", "them", ".", "The", "files", "are", "each", "expected", "to", "have", "a", "header", "row", "and", "for", "each", "row", "to", "be", "uniquely", "identified", "by", "one", "or", "more", "indexing", "columns", "." ]
163dd9da676a8e5f926a935803726340261f03ae
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/__init__.py#L128-L160
train
larsyencken/csvdiff
csvdiff/__init__.py
_diff_and_summarize
def _diff_and_summarize(from_csv, to_csv, index_columns, stream=sys.stdout, sep=',', ignored_columns=None, significance=None): """ Print a summary of the difference between the two files. """ from_records = list(records.load(from_csv, sep=sep)) to_records = records.load(to_csv, sep=sep) diff = patch.create(from_records, to_records, index_columns, ignored_columns) if significance is not None: diff = patch.filter_significance(diff, significance) _summarize_diff(diff, len(from_records), stream=stream) exit_code = (EXIT_SAME if patch.is_empty(diff) else EXIT_DIFFERENT) sys.exit(exit_code)
python
def _diff_and_summarize(from_csv, to_csv, index_columns, stream=sys.stdout, sep=',', ignored_columns=None, significance=None): """ Print a summary of the difference between the two files. """ from_records = list(records.load(from_csv, sep=sep)) to_records = records.load(to_csv, sep=sep) diff = patch.create(from_records, to_records, index_columns, ignored_columns) if significance is not None: diff = patch.filter_significance(diff, significance) _summarize_diff(diff, len(from_records), stream=stream) exit_code = (EXIT_SAME if patch.is_empty(diff) else EXIT_DIFFERENT) sys.exit(exit_code)
[ "def", "_diff_and_summarize", "(", "from_csv", ",", "to_csv", ",", "index_columns", ",", "stream", "=", "sys", ".", "stdout", ",", "sep", "=", "','", ",", "ignored_columns", "=", "None", ",", "significance", "=", "None", ")", ":", "from_records", "=", "list", "(", "records", ".", "load", "(", "from_csv", ",", "sep", "=", "sep", ")", ")", "to_records", "=", "records", ".", "load", "(", "to_csv", ",", "sep", "=", "sep", ")", "diff", "=", "patch", ".", "create", "(", "from_records", ",", "to_records", ",", "index_columns", ",", "ignored_columns", ")", "if", "significance", "is", "not", "None", ":", "diff", "=", "patch", ".", "filter_significance", "(", "diff", ",", "significance", ")", "_summarize_diff", "(", "diff", ",", "len", "(", "from_records", ")", ",", "stream", "=", "stream", ")", "exit_code", "=", "(", "EXIT_SAME", "if", "patch", ".", "is_empty", "(", "diff", ")", "else", "EXIT_DIFFERENT", ")", "sys", ".", "exit", "(", "exit_code", ")" ]
Print a summary of the difference between the two files.
[ "Print", "a", "summary", "of", "the", "difference", "between", "the", "two", "files", "." ]
163dd9da676a8e5f926a935803726340261f03ae
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/__init__.py#L178-L194
train
larsyencken/csvdiff
csvdiff/__init__.py
csvpatch_cmd
def csvpatch_cmd(input_csv, input=None, output=None, strict=True): """ Apply the changes from a csvdiff patch to an existing CSV file. """ patch_stream = (sys.stdin if input is None else open(input)) tocsv_stream = (sys.stdout if output is None else open(output, 'w')) fromcsv_stream = open(input_csv) try: patch_file(patch_stream, fromcsv_stream, tocsv_stream, strict=strict) except patch.InvalidPatchError as e: error.abort('reading patch, {0}'.format(e.args[0])) finally: patch_stream.close() fromcsv_stream.close() tocsv_stream.close()
python
def csvpatch_cmd(input_csv, input=None, output=None, strict=True): """ Apply the changes from a csvdiff patch to an existing CSV file. """ patch_stream = (sys.stdin if input is None else open(input)) tocsv_stream = (sys.stdout if output is None else open(output, 'w')) fromcsv_stream = open(input_csv) try: patch_file(patch_stream, fromcsv_stream, tocsv_stream, strict=strict) except patch.InvalidPatchError as e: error.abort('reading patch, {0}'.format(e.args[0])) finally: patch_stream.close() fromcsv_stream.close() tocsv_stream.close()
[ "def", "csvpatch_cmd", "(", "input_csv", ",", "input", "=", "None", ",", "output", "=", "None", ",", "strict", "=", "True", ")", ":", "patch_stream", "=", "(", "sys", ".", "stdin", "if", "input", "is", "None", "else", "open", "(", "input", ")", ")", "tocsv_stream", "=", "(", "sys", ".", "stdout", "if", "output", "is", "None", "else", "open", "(", "output", ",", "'w'", ")", ")", "fromcsv_stream", "=", "open", "(", "input_csv", ")", "try", ":", "patch_file", "(", "patch_stream", ",", "fromcsv_stream", ",", "tocsv_stream", ",", "strict", "=", "strict", ")", "except", "patch", ".", "InvalidPatchError", "as", "e", ":", "error", ".", "abort", "(", "'reading patch, {0}'", ".", "format", "(", "e", ".", "args", "[", "0", "]", ")", ")", "finally", ":", "patch_stream", ".", "close", "(", ")", "fromcsv_stream", ".", "close", "(", ")", "tocsv_stream", ".", "close", "(", ")" ]
Apply the changes from a csvdiff patch to an existing CSV file.
[ "Apply", "the", "changes", "from", "a", "csvdiff", "patch", "to", "an", "existing", "CSV", "file", "." ]
163dd9da676a8e5f926a935803726340261f03ae
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/__init__.py#L229-L250
train
larsyencken/csvdiff
csvdiff/records.py
sort
def sort(records: Sequence[Record]) -> List[Record]: "Sort records into a canonical order, suitable for comparison." return sorted(records, key=_record_key)
python
def sort(records: Sequence[Record]) -> List[Record]: "Sort records into a canonical order, suitable for comparison." return sorted(records, key=_record_key)
[ "def", "sort", "(", "records", ":", "Sequence", "[", "Record", "]", ")", "->", "List", "[", "Record", "]", ":", "return", "sorted", "(", "records", ",", "key", "=", "_record_key", ")" ]
Sort records into a canonical order, suitable for comparison.
[ "Sort", "records", "into", "a", "canonical", "order", "suitable", "for", "comparison", "." ]
163dd9da676a8e5f926a935803726340261f03ae
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/records.py#L86-L88
train
larsyencken/csvdiff
csvdiff/records.py
_record_key
def _record_key(record: Record) -> List[Tuple[Column, str]]: "An orderable representation of this record." return sorted(record.items())
python
def _record_key(record: Record) -> List[Tuple[Column, str]]: "An orderable representation of this record." return sorted(record.items())
[ "def", "_record_key", "(", "record", ":", "Record", ")", "->", "List", "[", "Tuple", "[", "Column", ",", "str", "]", "]", ":", "return", "sorted", "(", "record", ".", "items", "(", ")", ")" ]
An orderable representation of this record.
[ "An", "orderable", "representation", "of", "this", "record", "." ]
163dd9da676a8e5f926a935803726340261f03ae
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/records.py#L91-L93
train
Stewori/pytypes
pytypes/util.py
getargspecs
def getargspecs(func): """Bridges inspect.getargspec and inspect.getfullargspec. Automatically selects the proper one depending of current Python version. Automatically bypasses wrappers from typechecked- and override-decorators. """ if func is None: raise TypeError('None is not a Python function') if hasattr(func, 'ch_func'): return getargspecs(func.ch_func) elif hasattr(func, 'ov_func'): return getargspecs(func.ov_func) if hasattr(inspect, 'getfullargspec'): return inspect.getfullargspec(func) # Python 3 else: return inspect.getargspec(func)
python
def getargspecs(func): """Bridges inspect.getargspec and inspect.getfullargspec. Automatically selects the proper one depending of current Python version. Automatically bypasses wrappers from typechecked- and override-decorators. """ if func is None: raise TypeError('None is not a Python function') if hasattr(func, 'ch_func'): return getargspecs(func.ch_func) elif hasattr(func, 'ov_func'): return getargspecs(func.ov_func) if hasattr(inspect, 'getfullargspec'): return inspect.getfullargspec(func) # Python 3 else: return inspect.getargspec(func)
[ "def", "getargspecs", "(", "func", ")", ":", "if", "func", "is", "None", ":", "raise", "TypeError", "(", "'None is not a Python function'", ")", "if", "hasattr", "(", "func", ",", "'ch_func'", ")", ":", "return", "getargspecs", "(", "func", ".", "ch_func", ")", "elif", "hasattr", "(", "func", ",", "'ov_func'", ")", ":", "return", "getargspecs", "(", "func", ".", "ov_func", ")", "if", "hasattr", "(", "inspect", ",", "'getfullargspec'", ")", ":", "return", "inspect", ".", "getfullargspec", "(", "func", ")", "# Python 3", "else", ":", "return", "inspect", ".", "getargspec", "(", "func", ")" ]
Bridges inspect.getargspec and inspect.getfullargspec. Automatically selects the proper one depending of current Python version. Automatically bypasses wrappers from typechecked- and override-decorators.
[ "Bridges", "inspect", ".", "getargspec", "and", "inspect", ".", "getfullargspec", ".", "Automatically", "selects", "the", "proper", "one", "depending", "of", "current", "Python", "version", ".", "Automatically", "bypasses", "wrappers", "from", "typechecked", "-", "and", "override", "-", "decorators", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L94-L108
train
Stewori/pytypes
pytypes/util.py
get_required_kwonly_args
def get_required_kwonly_args(argspecs): """Determines whether given argspecs implies required keywords-only args and returns them as a list. Returns empty list if no such args exist. """ try: kwonly = argspecs.kwonlyargs if argspecs.kwonlydefaults is None: return kwonly res = [] for name in kwonly: if not name in argspecs.kwonlydefaults: res.append(name) return res except AttributeError: return []
python
def get_required_kwonly_args(argspecs): """Determines whether given argspecs implies required keywords-only args and returns them as a list. Returns empty list if no such args exist. """ try: kwonly = argspecs.kwonlyargs if argspecs.kwonlydefaults is None: return kwonly res = [] for name in kwonly: if not name in argspecs.kwonlydefaults: res.append(name) return res except AttributeError: return []
[ "def", "get_required_kwonly_args", "(", "argspecs", ")", ":", "try", ":", "kwonly", "=", "argspecs", ".", "kwonlyargs", "if", "argspecs", ".", "kwonlydefaults", "is", "None", ":", "return", "kwonly", "res", "=", "[", "]", "for", "name", "in", "kwonly", ":", "if", "not", "name", "in", "argspecs", ".", "kwonlydefaults", ":", "res", ".", "append", "(", "name", ")", "return", "res", "except", "AttributeError", ":", "return", "[", "]" ]
Determines whether given argspecs implies required keywords-only args and returns them as a list. Returns empty list if no such args exist.
[ "Determines", "whether", "given", "argspecs", "implies", "required", "keywords", "-", "only", "args", "and", "returns", "them", "as", "a", "list", ".", "Returns", "empty", "list", "if", "no", "such", "args", "exist", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L111-L125
train
Stewori/pytypes
pytypes/util.py
getargnames
def getargnames(argspecs, with_unbox=False): """Resembles list of arg-names as would be seen in a function signature, including var-args, var-keywords and keyword-only args. """ # todo: We can maybe make use of inspect.formatargspec args = argspecs.args vargs = argspecs.varargs try: kw = argspecs.keywords except AttributeError: kw = argspecs.varkw try: kwonly = argspecs.kwonlyargs except AttributeError: kwonly = None res = [] if not args is None: res.extend(args) if not vargs is None: res.append('*'+vargs if with_unbox else vargs) if not kwonly is None: res.extend(kwonly) if not kw is None: res.append('**'+kw if with_unbox else kw) return res
python
def getargnames(argspecs, with_unbox=False): """Resembles list of arg-names as would be seen in a function signature, including var-args, var-keywords and keyword-only args. """ # todo: We can maybe make use of inspect.formatargspec args = argspecs.args vargs = argspecs.varargs try: kw = argspecs.keywords except AttributeError: kw = argspecs.varkw try: kwonly = argspecs.kwonlyargs except AttributeError: kwonly = None res = [] if not args is None: res.extend(args) if not vargs is None: res.append('*'+vargs if with_unbox else vargs) if not kwonly is None: res.extend(kwonly) if not kw is None: res.append('**'+kw if with_unbox else kw) return res
[ "def", "getargnames", "(", "argspecs", ",", "with_unbox", "=", "False", ")", ":", "# todo: We can maybe make use of inspect.formatargspec", "args", "=", "argspecs", ".", "args", "vargs", "=", "argspecs", ".", "varargs", "try", ":", "kw", "=", "argspecs", ".", "keywords", "except", "AttributeError", ":", "kw", "=", "argspecs", ".", "varkw", "try", ":", "kwonly", "=", "argspecs", ".", "kwonlyargs", "except", "AttributeError", ":", "kwonly", "=", "None", "res", "=", "[", "]", "if", "not", "args", "is", "None", ":", "res", ".", "extend", "(", "args", ")", "if", "not", "vargs", "is", "None", ":", "res", ".", "append", "(", "'*'", "+", "vargs", "if", "with_unbox", "else", "vargs", ")", "if", "not", "kwonly", "is", "None", ":", "res", ".", "extend", "(", "kwonly", ")", "if", "not", "kw", "is", "None", ":", "res", ".", "append", "(", "'**'", "+", "kw", "if", "with_unbox", "else", "kw", ")", "return", "res" ]
Resembles list of arg-names as would be seen in a function signature, including var-args, var-keywords and keyword-only args.
[ "Resembles", "list", "of", "arg", "-", "names", "as", "would", "be", "seen", "in", "a", "function", "signature", "including", "var", "-", "args", "var", "-", "keywords", "and", "keyword", "-", "only", "args", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L128-L152
train
Stewori/pytypes
pytypes/util.py
get_class_that_defined_method
def get_class_that_defined_method(meth): """Determines the class owning the given method. """ if is_classmethod(meth): return meth.__self__ if hasattr(meth, 'im_class'): return meth.im_class elif hasattr(meth, '__qualname__'): # Python 3 try: cls_names = meth.__qualname__.split('.<locals>', 1)[0].rsplit('.', 1)[0].split('.') cls = inspect.getmodule(meth) for cls_name in cls_names: cls = getattr(cls, cls_name) if isinstance(cls, type): return cls except AttributeError: # If this was called from a decorator and meth is not a method, this # can result in AttributeError, because at decorator-time meth has not # yet been added to module. If it's really a method, its class would be # already in, so no problem in that case. pass raise ValueError(str(meth)+' is not a method.')
python
def get_class_that_defined_method(meth): """Determines the class owning the given method. """ if is_classmethod(meth): return meth.__self__ if hasattr(meth, 'im_class'): return meth.im_class elif hasattr(meth, '__qualname__'): # Python 3 try: cls_names = meth.__qualname__.split('.<locals>', 1)[0].rsplit('.', 1)[0].split('.') cls = inspect.getmodule(meth) for cls_name in cls_names: cls = getattr(cls, cls_name) if isinstance(cls, type): return cls except AttributeError: # If this was called from a decorator and meth is not a method, this # can result in AttributeError, because at decorator-time meth has not # yet been added to module. If it's really a method, its class would be # already in, so no problem in that case. pass raise ValueError(str(meth)+' is not a method.')
[ "def", "get_class_that_defined_method", "(", "meth", ")", ":", "if", "is_classmethod", "(", "meth", ")", ":", "return", "meth", ".", "__self__", "if", "hasattr", "(", "meth", ",", "'im_class'", ")", ":", "return", "meth", ".", "im_class", "elif", "hasattr", "(", "meth", ",", "'__qualname__'", ")", ":", "# Python 3", "try", ":", "cls_names", "=", "meth", ".", "__qualname__", ".", "split", "(", "'.<locals>'", ",", "1", ")", "[", "0", "]", ".", "rsplit", "(", "'.'", ",", "1", ")", "[", "0", "]", ".", "split", "(", "'.'", ")", "cls", "=", "inspect", ".", "getmodule", "(", "meth", ")", "for", "cls_name", "in", "cls_names", ":", "cls", "=", "getattr", "(", "cls", ",", "cls_name", ")", "if", "isinstance", "(", "cls", ",", "type", ")", ":", "return", "cls", "except", "AttributeError", ":", "# If this was called from a decorator and meth is not a method, this", "# can result in AttributeError, because at decorator-time meth has not", "# yet been added to module. If it's really a method, its class would be", "# already in, so no problem in that case.", "pass", "raise", "ValueError", "(", "str", "(", "meth", ")", "+", "' is not a method.'", ")" ]
Determines the class owning the given method.
[ "Determines", "the", "class", "owning", "the", "given", "method", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L415-L437
train
Stewori/pytypes
pytypes/util.py
is_classmethod
def is_classmethod(meth): """Detects if the given callable is a classmethod. """ if inspect.ismethoddescriptor(meth): return isinstance(meth, classmethod) if not inspect.ismethod(meth): return False if not inspect.isclass(meth.__self__): return False if not hasattr(meth.__self__, meth.__name__): return False return meth == getattr(meth.__self__, meth.__name__)
python
def is_classmethod(meth): """Detects if the given callable is a classmethod. """ if inspect.ismethoddescriptor(meth): return isinstance(meth, classmethod) if not inspect.ismethod(meth): return False if not inspect.isclass(meth.__self__): return False if not hasattr(meth.__self__, meth.__name__): return False return meth == getattr(meth.__self__, meth.__name__)
[ "def", "is_classmethod", "(", "meth", ")", ":", "if", "inspect", ".", "ismethoddescriptor", "(", "meth", ")", ":", "return", "isinstance", "(", "meth", ",", "classmethod", ")", "if", "not", "inspect", ".", "ismethod", "(", "meth", ")", ":", "return", "False", "if", "not", "inspect", ".", "isclass", "(", "meth", ".", "__self__", ")", ":", "return", "False", "if", "not", "hasattr", "(", "meth", ".", "__self__", ",", "meth", ".", "__name__", ")", ":", "return", "False", "return", "meth", "==", "getattr", "(", "meth", ".", "__self__", ",", "meth", ".", "__name__", ")" ]
Detects if the given callable is a classmethod.
[ "Detects", "if", "the", "given", "callable", "is", "a", "classmethod", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L463-L474
train
Stewori/pytypes
pytypes/util.py
get_current_args
def get_current_args(caller_level = 0, func = None, argNames = None): """Determines the args of current function call. Use caller_level > 0 to get args of even earlier function calls in current stack. """ if argNames is None: argNames = getargnames(getargspecs(func)) if func is None: func = get_current_function(caller_level+1) if isinstance(func, property): func = func.fget if func.fset is None else func.fset stck = inspect.stack() lcs = stck[1+caller_level][0].f_locals return tuple([lcs[t] for t in argNames])
python
def get_current_args(caller_level = 0, func = None, argNames = None): """Determines the args of current function call. Use caller_level > 0 to get args of even earlier function calls in current stack. """ if argNames is None: argNames = getargnames(getargspecs(func)) if func is None: func = get_current_function(caller_level+1) if isinstance(func, property): func = func.fget if func.fset is None else func.fset stck = inspect.stack() lcs = stck[1+caller_level][0].f_locals return tuple([lcs[t] for t in argNames])
[ "def", "get_current_args", "(", "caller_level", "=", "0", ",", "func", "=", "None", ",", "argNames", "=", "None", ")", ":", "if", "argNames", "is", "None", ":", "argNames", "=", "getargnames", "(", "getargspecs", "(", "func", ")", ")", "if", "func", "is", "None", ":", "func", "=", "get_current_function", "(", "caller_level", "+", "1", ")", "if", "isinstance", "(", "func", ",", "property", ")", ":", "func", "=", "func", ".", "fget", "if", "func", ".", "fset", "is", "None", "else", "func", ".", "fset", "stck", "=", "inspect", ".", "stack", "(", ")", "lcs", "=", "stck", "[", "1", "+", "caller_level", "]", "[", "0", "]", ".", "f_locals", "return", "tuple", "(", "[", "lcs", "[", "t", "]", "for", "t", "in", "argNames", "]", ")" ]
Determines the args of current function call. Use caller_level > 0 to get args of even earlier function calls in current stack.
[ "Determines", "the", "args", "of", "current", "function", "call", ".", "Use", "caller_level", ">", "0", "to", "get", "args", "of", "even", "earlier", "function", "calls", "in", "current", "stack", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L531-L543
train
Stewori/pytypes
pytypes/util.py
getmodule
def getmodule(code): """More robust variant of inspect.getmodule. E.g. has less issues on Jython. """ try: md = inspect.getmodule(code, code.co_filename) except AttributeError: return inspect.getmodule(code) if md is None: # Jython-specific: # This is currently just a crutch; todo: resolve __pyclasspath__ properly! cfname = code.co_filename.replace('__pyclasspath__', os.path.realpath('')+os.sep+'__pyclasspath__') cfname = cfname.replace('$py.class', '.py') md = inspect.getmodule(code, cfname) if md is None: md = inspect.getmodule(code) return md
python
def getmodule(code): """More robust variant of inspect.getmodule. E.g. has less issues on Jython. """ try: md = inspect.getmodule(code, code.co_filename) except AttributeError: return inspect.getmodule(code) if md is None: # Jython-specific: # This is currently just a crutch; todo: resolve __pyclasspath__ properly! cfname = code.co_filename.replace('__pyclasspath__', os.path.realpath('')+os.sep+'__pyclasspath__') cfname = cfname.replace('$py.class', '.py') md = inspect.getmodule(code, cfname) if md is None: md = inspect.getmodule(code) return md
[ "def", "getmodule", "(", "code", ")", ":", "try", ":", "md", "=", "inspect", ".", "getmodule", "(", "code", ",", "code", ".", "co_filename", ")", "except", "AttributeError", ":", "return", "inspect", ".", "getmodule", "(", "code", ")", "if", "md", "is", "None", ":", "# Jython-specific:", "# This is currently just a crutch; todo: resolve __pyclasspath__ properly!", "cfname", "=", "code", ".", "co_filename", ".", "replace", "(", "'__pyclasspath__'", ",", "os", ".", "path", ".", "realpath", "(", "''", ")", "+", "os", ".", "sep", "+", "'__pyclasspath__'", ")", "cfname", "=", "cfname", ".", "replace", "(", "'$py.class'", ",", "'.py'", ")", "md", "=", "inspect", ".", "getmodule", "(", "code", ",", "cfname", ")", "if", "md", "is", "None", ":", "md", "=", "inspect", ".", "getmodule", "(", "code", ")", "return", "md" ]
More robust variant of inspect.getmodule. E.g. has less issues on Jython.
[ "More", "robust", "variant", "of", "inspect", ".", "getmodule", ".", "E", ".", "g", ".", "has", "less", "issues", "on", "Jython", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L551-L568
train
Stewori/pytypes
pytypes/util.py
_calc_traceback_limit
def _calc_traceback_limit(tb): """Calculates limit-parameter to strip away pytypes' internals when used with API from traceback module. """ limit = 1 tb2 = tb while not tb2.tb_next is None: try: maybe_pytypes = tb2.tb_next.tb_frame.f_code.co_filename.split(os.sep)[-2] except IndexError: maybe_pytypes = None if maybe_pytypes == 'pytypes' and not \ tb2.tb_next.tb_frame.f_code == pytypes.typechecker._pytypes___import__.__code__: break else: limit += 1 tb2 = tb2.tb_next return limit
python
def _calc_traceback_limit(tb): """Calculates limit-parameter to strip away pytypes' internals when used with API from traceback module. """ limit = 1 tb2 = tb while not tb2.tb_next is None: try: maybe_pytypes = tb2.tb_next.tb_frame.f_code.co_filename.split(os.sep)[-2] except IndexError: maybe_pytypes = None if maybe_pytypes == 'pytypes' and not \ tb2.tb_next.tb_frame.f_code == pytypes.typechecker._pytypes___import__.__code__: break else: limit += 1 tb2 = tb2.tb_next return limit
[ "def", "_calc_traceback_limit", "(", "tb", ")", ":", "limit", "=", "1", "tb2", "=", "tb", "while", "not", "tb2", ".", "tb_next", "is", "None", ":", "try", ":", "maybe_pytypes", "=", "tb2", ".", "tb_next", ".", "tb_frame", ".", "f_code", ".", "co_filename", ".", "split", "(", "os", ".", "sep", ")", "[", "-", "2", "]", "except", "IndexError", ":", "maybe_pytypes", "=", "None", "if", "maybe_pytypes", "==", "'pytypes'", "and", "not", "tb2", ".", "tb_next", ".", "tb_frame", ".", "f_code", "==", "pytypes", ".", "typechecker", ".", "_pytypes___import__", ".", "__code__", ":", "break", "else", ":", "limit", "+=", "1", "tb2", "=", "tb2", ".", "tb_next", "return", "limit" ]
Calculates limit-parameter to strip away pytypes' internals when used with API from traceback module.
[ "Calculates", "limit", "-", "parameter", "to", "strip", "away", "pytypes", "internals", "when", "used", "with", "API", "from", "traceback", "module", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L758-L775
train
Stewori/pytypes
pytypes/util.py
_pytypes_excepthook
def _pytypes_excepthook(exctype, value, tb): """"An excepthook suitable for use as sys.excepthook, that strips away the part of the traceback belonging to pytypes' internals. Can be switched on and off via pytypes.clean_traceback or pytypes.set_clean_traceback. The latter automatically installs this hook in sys.excepthook. """ if pytypes.clean_traceback and issubclass(exctype, TypeError): traceback.print_exception(exctype, value, tb, _calc_traceback_limit(tb)) else: if _sys_excepthook is None: sys.__excepthook__(exctype, value, tb) else: _sys_excepthook(exctype, value, tb)
python
def _pytypes_excepthook(exctype, value, tb): """"An excepthook suitable for use as sys.excepthook, that strips away the part of the traceback belonging to pytypes' internals. Can be switched on and off via pytypes.clean_traceback or pytypes.set_clean_traceback. The latter automatically installs this hook in sys.excepthook. """ if pytypes.clean_traceback and issubclass(exctype, TypeError): traceback.print_exception(exctype, value, tb, _calc_traceback_limit(tb)) else: if _sys_excepthook is None: sys.__excepthook__(exctype, value, tb) else: _sys_excepthook(exctype, value, tb)
[ "def", "_pytypes_excepthook", "(", "exctype", ",", "value", ",", "tb", ")", ":", "if", "pytypes", ".", "clean_traceback", "and", "issubclass", "(", "exctype", ",", "TypeError", ")", ":", "traceback", ".", "print_exception", "(", "exctype", ",", "value", ",", "tb", ",", "_calc_traceback_limit", "(", "tb", ")", ")", "else", ":", "if", "_sys_excepthook", "is", "None", ":", "sys", ".", "__excepthook__", "(", "exctype", ",", "value", ",", "tb", ")", "else", ":", "_sys_excepthook", "(", "exctype", ",", "value", ",", "tb", ")" ]
An excepthook suitable for use as sys.excepthook, that strips away the part of the traceback belonging to pytypes' internals. Can be switched on and off via pytypes.clean_traceback or pytypes.set_clean_traceback. The latter automatically installs this hook in sys.excepthook.
[ "An", "excepthook", "suitable", "for", "use", "as", "sys", ".", "excepthook", "that", "strips", "away", "the", "part", "of", "the", "traceback", "belonging", "to", "pytypes", "internals", ".", "Can", "be", "switched", "on", "and", "off", "via", "pytypes", ".", "clean_traceback", "or", "pytypes", ".", "set_clean_traceback", ".", "The", "latter", "automatically", "installs", "this", "hook", "in", "sys", ".", "excepthook", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L817-L830
train
Stewori/pytypes
pytypes/type_util.py
get_generator_type
def get_generator_type(genr): """Obtains PEP 484 style type of a generator object, i.e. returns a typing.Generator object. """ if genr in _checked_generator_types: return _checked_generator_types[genr] if not genr.gi_frame is None and 'gen_type' in genr.gi_frame.f_locals: return genr.gi_frame.f_locals['gen_type'] else: cllble, nesting, slf = util.get_callable_fq_for_code(genr.gi_code) if cllble is None: return Generator return _funcsigtypes(cllble, slf, nesting[-1] if slf else None, genr.gi_frame.f_globals if not genr.gi_frame is None else None)[1]
python
def get_generator_type(genr): """Obtains PEP 484 style type of a generator object, i.e. returns a typing.Generator object. """ if genr in _checked_generator_types: return _checked_generator_types[genr] if not genr.gi_frame is None and 'gen_type' in genr.gi_frame.f_locals: return genr.gi_frame.f_locals['gen_type'] else: cllble, nesting, slf = util.get_callable_fq_for_code(genr.gi_code) if cllble is None: return Generator return _funcsigtypes(cllble, slf, nesting[-1] if slf else None, genr.gi_frame.f_globals if not genr.gi_frame is None else None)[1]
[ "def", "get_generator_type", "(", "genr", ")", ":", "if", "genr", "in", "_checked_generator_types", ":", "return", "_checked_generator_types", "[", "genr", "]", "if", "not", "genr", ".", "gi_frame", "is", "None", "and", "'gen_type'", "in", "genr", ".", "gi_frame", ".", "f_locals", ":", "return", "genr", ".", "gi_frame", ".", "f_locals", "[", "'gen_type'", "]", "else", ":", "cllble", ",", "nesting", ",", "slf", "=", "util", ".", "get_callable_fq_for_code", "(", "genr", ".", "gi_code", ")", "if", "cllble", "is", "None", ":", "return", "Generator", "return", "_funcsigtypes", "(", "cllble", ",", "slf", ",", "nesting", "[", "-", "1", "]", "if", "slf", "else", "None", ",", "genr", ".", "gi_frame", ".", "f_globals", "if", "not", "genr", ".", "gi_frame", "is", "None", "else", "None", ")", "[", "1", "]" ]
Obtains PEP 484 style type of a generator object, i.e. returns a typing.Generator object.
[ "Obtains", "PEP", "484", "style", "type", "of", "a", "generator", "object", "i", ".", "e", ".", "returns", "a", "typing", ".", "Generator", "object", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L109-L122
train
Stewori/pytypes
pytypes/type_util.py
get_Generic_parameters
def get_Generic_parameters(tp, generic_supertype): """tp must be a subclass of generic_supertype. Retrieves the type values from tp that correspond to parameters defined by generic_supertype. E.g. get_Generic_parameters(tp, typing.Mapping) is equivalent to get_Mapping_key_value(tp) except for the error message. Note that get_Generic_itemtype(tp) is not exactly equal to get_Generic_parameters(tp, typing.Container), as that method additionally contains treatment for typing.Tuple and typing.Iterable. """ try: res = _select_Generic_superclass_parameters(tp, generic_supertype) except TypeError: res = None if res is None: raise TypeError("%s has no proper parameters defined by %s."% (type_str(tp), type_str(generic_supertype))) else: return tuple(res)
python
def get_Generic_parameters(tp, generic_supertype): """tp must be a subclass of generic_supertype. Retrieves the type values from tp that correspond to parameters defined by generic_supertype. E.g. get_Generic_parameters(tp, typing.Mapping) is equivalent to get_Mapping_key_value(tp) except for the error message. Note that get_Generic_itemtype(tp) is not exactly equal to get_Generic_parameters(tp, typing.Container), as that method additionally contains treatment for typing.Tuple and typing.Iterable. """ try: res = _select_Generic_superclass_parameters(tp, generic_supertype) except TypeError: res = None if res is None: raise TypeError("%s has no proper parameters defined by %s."% (type_str(tp), type_str(generic_supertype))) else: return tuple(res)
[ "def", "get_Generic_parameters", "(", "tp", ",", "generic_supertype", ")", ":", "try", ":", "res", "=", "_select_Generic_superclass_parameters", "(", "tp", ",", "generic_supertype", ")", "except", "TypeError", ":", "res", "=", "None", "if", "res", "is", "None", ":", "raise", "TypeError", "(", "\"%s has no proper parameters defined by %s.\"", "%", "(", "type_str", "(", "tp", ")", ",", "type_str", "(", "generic_supertype", ")", ")", ")", "else", ":", "return", "tuple", "(", "res", ")" ]
tp must be a subclass of generic_supertype. Retrieves the type values from tp that correspond to parameters defined by generic_supertype. E.g. get_Generic_parameters(tp, typing.Mapping) is equivalent to get_Mapping_key_value(tp) except for the error message. Note that get_Generic_itemtype(tp) is not exactly equal to get_Generic_parameters(tp, typing.Container), as that method additionally contains treatment for typing.Tuple and typing.Iterable.
[ "tp", "must", "be", "a", "subclass", "of", "generic_supertype", ".", "Retrieves", "the", "type", "values", "from", "tp", "that", "correspond", "to", "parameters", "defined", "by", "generic_supertype", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L218-L238
train
Stewori/pytypes
pytypes/type_util.py
get_Tuple_params
def get_Tuple_params(tpl): """Python version independent function to obtain the parameters of a typing.Tuple object. Omits the ellipsis argument if present. Use is_Tuple_ellipsis for that. Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1. """ try: return tpl.__tuple_params__ except AttributeError: try: if tpl.__args__ is None: return None # Python 3.6 if tpl.__args__[0] == (): return () else: if tpl.__args__[-1] is Ellipsis: return tpl.__args__[:-1] if len(tpl.__args__) > 1 else None else: return tpl.__args__ except AttributeError: return None
python
def get_Tuple_params(tpl): """Python version independent function to obtain the parameters of a typing.Tuple object. Omits the ellipsis argument if present. Use is_Tuple_ellipsis for that. Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1. """ try: return tpl.__tuple_params__ except AttributeError: try: if tpl.__args__ is None: return None # Python 3.6 if tpl.__args__[0] == (): return () else: if tpl.__args__[-1] is Ellipsis: return tpl.__args__[:-1] if len(tpl.__args__) > 1 else None else: return tpl.__args__ except AttributeError: return None
[ "def", "get_Tuple_params", "(", "tpl", ")", ":", "try", ":", "return", "tpl", ".", "__tuple_params__", "except", "AttributeError", ":", "try", ":", "if", "tpl", ".", "__args__", "is", "None", ":", "return", "None", "# Python 3.6", "if", "tpl", ".", "__args__", "[", "0", "]", "==", "(", ")", ":", "return", "(", ")", "else", ":", "if", "tpl", ".", "__args__", "[", "-", "1", "]", "is", "Ellipsis", ":", "return", "tpl", ".", "__args__", "[", ":", "-", "1", "]", "if", "len", "(", "tpl", ".", "__args__", ")", ">", "1", "else", "None", "else", ":", "return", "tpl", ".", "__args__", "except", "AttributeError", ":", "return", "None" ]
Python version independent function to obtain the parameters of a typing.Tuple object. Omits the ellipsis argument if present. Use is_Tuple_ellipsis for that. Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1.
[ "Python", "version", "independent", "function", "to", "obtain", "the", "parameters", "of", "a", "typing", ".", "Tuple", "object", ".", "Omits", "the", "ellipsis", "argument", "if", "present", ".", "Use", "is_Tuple_ellipsis", "for", "that", ".", "Tested", "with", "CPython", "2", ".", "7", "3", ".", "5", "3", ".", "6", "and", "Jython", "2", ".", "7", ".", "1", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L241-L262
train
Stewori/pytypes
pytypes/type_util.py
is_Tuple_ellipsis
def is_Tuple_ellipsis(tpl): """Python version independent function to check if a typing.Tuple object contains an ellipsis.""" try: return tpl.__tuple_use_ellipsis__ except AttributeError: try: if tpl.__args__ is None: return False # Python 3.6 if tpl.__args__[-1] is Ellipsis: return True except AttributeError: pass return False
python
def is_Tuple_ellipsis(tpl): """Python version independent function to check if a typing.Tuple object contains an ellipsis.""" try: return tpl.__tuple_use_ellipsis__ except AttributeError: try: if tpl.__args__ is None: return False # Python 3.6 if tpl.__args__[-1] is Ellipsis: return True except AttributeError: pass return False
[ "def", "is_Tuple_ellipsis", "(", "tpl", ")", ":", "try", ":", "return", "tpl", ".", "__tuple_use_ellipsis__", "except", "AttributeError", ":", "try", ":", "if", "tpl", ".", "__args__", "is", "None", ":", "return", "False", "# Python 3.6", "if", "tpl", ".", "__args__", "[", "-", "1", "]", "is", "Ellipsis", ":", "return", "True", "except", "AttributeError", ":", "pass", "return", "False" ]
Python version independent function to check if a typing.Tuple object contains an ellipsis.
[ "Python", "version", "independent", "function", "to", "check", "if", "a", "typing", ".", "Tuple", "object", "contains", "an", "ellipsis", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L265-L279
train
Stewori/pytypes
pytypes/type_util.py
is_Union
def is_Union(tp): """Python version independent check if a type is typing.Union. Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1. """ if tp is Union: return True try: # Python 3.6 return tp.__origin__ is Union except AttributeError: try: return isinstance(tp, typing.UnionMeta) except AttributeError: return False
python
def is_Union(tp): """Python version independent check if a type is typing.Union. Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1. """ if tp is Union: return True try: # Python 3.6 return tp.__origin__ is Union except AttributeError: try: return isinstance(tp, typing.UnionMeta) except AttributeError: return False
[ "def", "is_Union", "(", "tp", ")", ":", "if", "tp", "is", "Union", ":", "return", "True", "try", ":", "# Python 3.6", "return", "tp", ".", "__origin__", "is", "Union", "except", "AttributeError", ":", "try", ":", "return", "isinstance", "(", "tp", ",", "typing", ".", "UnionMeta", ")", "except", "AttributeError", ":", "return", "False" ]
Python version independent check if a type is typing.Union. Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1.
[ "Python", "version", "independent", "check", "if", "a", "type", "is", "typing", ".", "Union", ".", "Tested", "with", "CPython", "2", ".", "7", "3", ".", "5", "3", ".", "6", "and", "Jython", "2", ".", "7", ".", "1", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L336-L349
train
Stewori/pytypes
pytypes/type_util.py
is_builtin_type
def is_builtin_type(tp): """Checks if the given type is a builtin one. """ return hasattr(__builtins__, tp.__name__) and tp is getattr(__builtins__, tp.__name__)
python
def is_builtin_type(tp): """Checks if the given type is a builtin one. """ return hasattr(__builtins__, tp.__name__) and tp is getattr(__builtins__, tp.__name__)
[ "def", "is_builtin_type", "(", "tp", ")", ":", "return", "hasattr", "(", "__builtins__", ",", "tp", ".", "__name__", ")", "and", "tp", "is", "getattr", "(", "__builtins__", ",", "tp", ".", "__name__", ")" ]
Checks if the given type is a builtin one.
[ "Checks", "if", "the", "given", "type", "is", "a", "builtin", "one", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L533-L536
train
Stewori/pytypes
pytypes/type_util.py
get_types
def get_types(func): """Works like get_type_hints, but returns types as a sequence rather than a dictionary. Types are returned in declaration order of the corresponding arguments. """ return _get_types(func, util.is_classmethod(func), util.is_method(func))
python
def get_types(func): """Works like get_type_hints, but returns types as a sequence rather than a dictionary. Types are returned in declaration order of the corresponding arguments. """ return _get_types(func, util.is_classmethod(func), util.is_method(func))
[ "def", "get_types", "(", "func", ")", ":", "return", "_get_types", "(", "func", ",", "util", ".", "is_classmethod", "(", "func", ")", ",", "util", ".", "is_method", "(", "func", ")", ")" ]
Works like get_type_hints, but returns types as a sequence rather than a dictionary. Types are returned in declaration order of the corresponding arguments.
[ "Works", "like", "get_type_hints", "but", "returns", "types", "as", "a", "sequence", "rather", "than", "a", "dictionary", ".", "Types", "are", "returned", "in", "declaration", "order", "of", "the", "corresponding", "arguments", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L780-L784
train
Stewori/pytypes
pytypes/type_util.py
get_member_types
def get_member_types(obj, member_name, prop_getter = False): """Still experimental, incomplete and hardly tested. Works like get_types, but is also applicable to descriptors. """ cls = obj.__class__ member = getattr(cls, member_name) slf = not (isinstance(member, staticmethod) or isinstance(member, classmethod)) clsm = isinstance(member, classmethod) return _get_types(member, clsm, slf, cls, prop_getter)
python
def get_member_types(obj, member_name, prop_getter = False): """Still experimental, incomplete and hardly tested. Works like get_types, but is also applicable to descriptors. """ cls = obj.__class__ member = getattr(cls, member_name) slf = not (isinstance(member, staticmethod) or isinstance(member, classmethod)) clsm = isinstance(member, classmethod) return _get_types(member, clsm, slf, cls, prop_getter)
[ "def", "get_member_types", "(", "obj", ",", "member_name", ",", "prop_getter", "=", "False", ")", ":", "cls", "=", "obj", ".", "__class__", "member", "=", "getattr", "(", "cls", ",", "member_name", ")", "slf", "=", "not", "(", "isinstance", "(", "member", ",", "staticmethod", ")", "or", "isinstance", "(", "member", ",", "classmethod", ")", ")", "clsm", "=", "isinstance", "(", "member", ",", "classmethod", ")", "return", "_get_types", "(", "member", ",", "clsm", ",", "slf", ",", "cls", ",", "prop_getter", ")" ]
Still experimental, incomplete and hardly tested. Works like get_types, but is also applicable to descriptors.
[ "Still", "experimental", "incomplete", "and", "hardly", "tested", ".", "Works", "like", "get_types", "but", "is", "also", "applicable", "to", "descriptors", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L787-L795
train
Stewori/pytypes
pytypes/type_util.py
_get_types
def _get_types(func, clsm, slf, clss = None, prop_getter = False, unspecified_type = Any, infer_defaults = None): """Helper for get_types and get_member_types. """ func0 = util._actualfunc(func, prop_getter) # check consistency regarding special case with 'self'-keyword if not slf: argNames = util.getargnames(util.getargspecs(func0)) if len(argNames) > 0: if clsm: if argNames[0] != 'cls': util._warn_argname('classmethod using non-idiomatic cls argname', func0, slf, clsm, clss) if clss is None and (slf or clsm): if slf: assert util.is_method(func) or isinstance(func, property) if clsm: assert util.is_classmethod(func) clss = util.get_class_that_defined_method(func) assert hasattr(clss, func.__name__) args, res = _funcsigtypes(func, slf or clsm, clss, None, prop_getter, unspecified_type = unspecified_type, infer_defaults = infer_defaults) return _match_stub_type(args), _match_stub_type(res)
python
def _get_types(func, clsm, slf, clss = None, prop_getter = False, unspecified_type = Any, infer_defaults = None): """Helper for get_types and get_member_types. """ func0 = util._actualfunc(func, prop_getter) # check consistency regarding special case with 'self'-keyword if not slf: argNames = util.getargnames(util.getargspecs(func0)) if len(argNames) > 0: if clsm: if argNames[0] != 'cls': util._warn_argname('classmethod using non-idiomatic cls argname', func0, slf, clsm, clss) if clss is None and (slf or clsm): if slf: assert util.is_method(func) or isinstance(func, property) if clsm: assert util.is_classmethod(func) clss = util.get_class_that_defined_method(func) assert hasattr(clss, func.__name__) args, res = _funcsigtypes(func, slf or clsm, clss, None, prop_getter, unspecified_type = unspecified_type, infer_defaults = infer_defaults) return _match_stub_type(args), _match_stub_type(res)
[ "def", "_get_types", "(", "func", ",", "clsm", ",", "slf", ",", "clss", "=", "None", ",", "prop_getter", "=", "False", ",", "unspecified_type", "=", "Any", ",", "infer_defaults", "=", "None", ")", ":", "func0", "=", "util", ".", "_actualfunc", "(", "func", ",", "prop_getter", ")", "# check consistency regarding special case with 'self'-keyword", "if", "not", "slf", ":", "argNames", "=", "util", ".", "getargnames", "(", "util", ".", "getargspecs", "(", "func0", ")", ")", "if", "len", "(", "argNames", ")", ">", "0", ":", "if", "clsm", ":", "if", "argNames", "[", "0", "]", "!=", "'cls'", ":", "util", ".", "_warn_argname", "(", "'classmethod using non-idiomatic cls argname'", ",", "func0", ",", "slf", ",", "clsm", ",", "clss", ")", "if", "clss", "is", "None", "and", "(", "slf", "or", "clsm", ")", ":", "if", "slf", ":", "assert", "util", ".", "is_method", "(", "func", ")", "or", "isinstance", "(", "func", ",", "property", ")", "if", "clsm", ":", "assert", "util", ".", "is_classmethod", "(", "func", ")", "clss", "=", "util", ".", "get_class_that_defined_method", "(", "func", ")", "assert", "hasattr", "(", "clss", ",", "func", ".", "__name__", ")", "args", ",", "res", "=", "_funcsigtypes", "(", "func", ",", "slf", "or", "clsm", ",", "clss", ",", "None", ",", "prop_getter", ",", "unspecified_type", "=", "unspecified_type", ",", "infer_defaults", "=", "infer_defaults", ")", "return", "_match_stub_type", "(", "args", ")", ",", "_match_stub_type", "(", "res", ")" ]
Helper for get_types and get_member_types.
[ "Helper", "for", "get_types", "and", "get_member_types", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L798-L820
train
Stewori/pytypes
pytypes/type_util.py
_get_type_hints
def _get_type_hints(func, args = None, res = None, infer_defaults = None): """Helper for get_type_hints. """ if args is None or res is None: args2, res2 = _get_types(func, util.is_classmethod(func), util.is_method(func), unspecified_type = type(NotImplemented), infer_defaults = infer_defaults) if args is None: args = args2 if res is None: res = res2 slf = 1 if util.is_method(func) else 0 argNames = util.getargnames(util.getargspecs(util._actualfunc(func))) result = {} if not args is Any: prms = get_Tuple_params(args) for i in range(slf, len(argNames)): if not prms[i-slf] is type(NotImplemented): result[argNames[i]] = prms[i-slf] result['return'] = res return result
python
def _get_type_hints(func, args = None, res = None, infer_defaults = None): """Helper for get_type_hints. """ if args is None or res is None: args2, res2 = _get_types(func, util.is_classmethod(func), util.is_method(func), unspecified_type = type(NotImplemented), infer_defaults = infer_defaults) if args is None: args = args2 if res is None: res = res2 slf = 1 if util.is_method(func) else 0 argNames = util.getargnames(util.getargspecs(util._actualfunc(func))) result = {} if not args is Any: prms = get_Tuple_params(args) for i in range(slf, len(argNames)): if not prms[i-slf] is type(NotImplemented): result[argNames[i]] = prms[i-slf] result['return'] = res return result
[ "def", "_get_type_hints", "(", "func", ",", "args", "=", "None", ",", "res", "=", "None", ",", "infer_defaults", "=", "None", ")", ":", "if", "args", "is", "None", "or", "res", "is", "None", ":", "args2", ",", "res2", "=", "_get_types", "(", "func", ",", "util", ".", "is_classmethod", "(", "func", ")", ",", "util", ".", "is_method", "(", "func", ")", ",", "unspecified_type", "=", "type", "(", "NotImplemented", ")", ",", "infer_defaults", "=", "infer_defaults", ")", "if", "args", "is", "None", ":", "args", "=", "args2", "if", "res", "is", "None", ":", "res", "=", "res2", "slf", "=", "1", "if", "util", ".", "is_method", "(", "func", ")", "else", "0", "argNames", "=", "util", ".", "getargnames", "(", "util", ".", "getargspecs", "(", "util", ".", "_actualfunc", "(", "func", ")", ")", ")", "result", "=", "{", "}", "if", "not", "args", "is", "Any", ":", "prms", "=", "get_Tuple_params", "(", "args", ")", "for", "i", "in", "range", "(", "slf", ",", "len", "(", "argNames", ")", ")", ":", "if", "not", "prms", "[", "i", "-", "slf", "]", "is", "type", "(", "NotImplemented", ")", ":", "result", "[", "argNames", "[", "i", "]", "]", "=", "prms", "[", "i", "-", "slf", "]", "result", "[", "'return'", "]", "=", "res", "return", "result" ]
Helper for get_type_hints.
[ "Helper", "for", "get_type_hints", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L836-L856
train
Stewori/pytypes
pytypes/type_util.py
_issubclass_Mapping_covariant
def _issubclass_Mapping_covariant(subclass, superclass, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): """Helper for _issubclass, a.k.a pytypes.issubtype. This subclass-check treats Mapping-values as covariant. """ if is_Generic(subclass): if subclass.__origin__ is None or not issubclass(subclass.__origin__, Mapping): return _issubclass_Generic(subclass, superclass, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check) if superclass.__args__ is None: if not pytypes.check_unbound_types: raise TypeError("Attempted to check unbound mapping type(superclass): "+ str(superclass)) if pytypes.strict_unknown_check: # Nothing is subtype of unknown type return False super_args = (Any, Any) else: super_args = superclass.__args__ if subclass.__args__ is None: if not pytypes.check_unbound_types: raise TypeError("Attempted to check unbound mapping type(subclass): "+ str(subclass)) if pytypes.strict_unknown_check: # Nothing can subclass unknown type # For value type it would be okay if superclass had Any as value type, # as unknown type is subtype of Any. However, since key type is invariant # and also unknown, it cannot pass. return False sub_args = (Any, Any) else: sub_args = subclass.__args__ if not _issubclass(sub_args[0], super_args[0], bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): return False if not _issubclass(sub_args[1], super_args[1], bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): return False return True return issubclass(subclass, superclass)
python
def _issubclass_Mapping_covariant(subclass, superclass, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): """Helper for _issubclass, a.k.a pytypes.issubtype. This subclass-check treats Mapping-values as covariant. """ if is_Generic(subclass): if subclass.__origin__ is None or not issubclass(subclass.__origin__, Mapping): return _issubclass_Generic(subclass, superclass, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check) if superclass.__args__ is None: if not pytypes.check_unbound_types: raise TypeError("Attempted to check unbound mapping type(superclass): "+ str(superclass)) if pytypes.strict_unknown_check: # Nothing is subtype of unknown type return False super_args = (Any, Any) else: super_args = superclass.__args__ if subclass.__args__ is None: if not pytypes.check_unbound_types: raise TypeError("Attempted to check unbound mapping type(subclass): "+ str(subclass)) if pytypes.strict_unknown_check: # Nothing can subclass unknown type # For value type it would be okay if superclass had Any as value type, # as unknown type is subtype of Any. However, since key type is invariant # and also unknown, it cannot pass. return False sub_args = (Any, Any) else: sub_args = subclass.__args__ if not _issubclass(sub_args[0], super_args[0], bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): return False if not _issubclass(sub_args[1], super_args[1], bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): return False return True return issubclass(subclass, superclass)
[ "def", "_issubclass_Mapping_covariant", "(", "subclass", ",", "superclass", ",", "bound_Generic", ",", "bound_typevars", ",", "bound_typevars_readonly", ",", "follow_fwd_refs", ",", "_recursion_check", ")", ":", "if", "is_Generic", "(", "subclass", ")", ":", "if", "subclass", ".", "__origin__", "is", "None", "or", "not", "issubclass", "(", "subclass", ".", "__origin__", ",", "Mapping", ")", ":", "return", "_issubclass_Generic", "(", "subclass", ",", "superclass", ",", "bound_Generic", ",", "bound_typevars", ",", "bound_typevars_readonly", ",", "follow_fwd_refs", ",", "_recursion_check", ")", "if", "superclass", ".", "__args__", "is", "None", ":", "if", "not", "pytypes", ".", "check_unbound_types", ":", "raise", "TypeError", "(", "\"Attempted to check unbound mapping type(superclass): \"", "+", "str", "(", "superclass", ")", ")", "if", "pytypes", ".", "strict_unknown_check", ":", "# Nothing is subtype of unknown type", "return", "False", "super_args", "=", "(", "Any", ",", "Any", ")", "else", ":", "super_args", "=", "superclass", ".", "__args__", "if", "subclass", ".", "__args__", "is", "None", ":", "if", "not", "pytypes", ".", "check_unbound_types", ":", "raise", "TypeError", "(", "\"Attempted to check unbound mapping type(subclass): \"", "+", "str", "(", "subclass", ")", ")", "if", "pytypes", ".", "strict_unknown_check", ":", "# Nothing can subclass unknown type", "# For value type it would be okay if superclass had Any as value type,", "# as unknown type is subtype of Any. However, since key type is invariant", "# and also unknown, it cannot pass.", "return", "False", "sub_args", "=", "(", "Any", ",", "Any", ")", "else", ":", "sub_args", "=", "subclass", ".", "__args__", "if", "not", "_issubclass", "(", "sub_args", "[", "0", "]", ",", "super_args", "[", "0", "]", ",", "bound_Generic", ",", "bound_typevars", ",", "bound_typevars_readonly", ",", "follow_fwd_refs", ",", "_recursion_check", ")", ":", "return", "False", "if", "not", "_issubclass", "(", "sub_args", "[", "1", "]", ",", "super_args", "[", "1", "]", ",", "bound_Generic", ",", "bound_typevars", ",", "bound_typevars_readonly", ",", "follow_fwd_refs", ",", "_recursion_check", ")", ":", "return", "False", "return", "True", "return", "issubclass", "(", "subclass", ",", "superclass", ")" ]
Helper for _issubclass, a.k.a pytypes.issubtype. This subclass-check treats Mapping-values as covariant.
[ "Helper", "for", "_issubclass", "a", ".", "k", ".", "a", "pytypes", ".", "issubtype", ".", "This", "subclass", "-", "check", "treats", "Mapping", "-", "values", "as", "covariant", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L1104-L1145
train
Stewori/pytypes
pytypes/type_util.py
_issubclass_Union_rec
def _issubclass_Union_rec(subclass, superclass, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): """Helper for _issubclass_Union. """ # this function is partly based on code from typing module 3.5.2.2 super_args = get_Union_params(superclass) if super_args is None: return is_Union(subclass) elif is_Union(subclass): sub_args = get_Union_params(subclass) if sub_args is None: return False return all(_issubclass(c, superclass, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check) \ for c in (sub_args)) elif isinstance(subclass, TypeVar): if subclass in super_args: return True if subclass.__constraints__: return _issubclass(Union[subclass.__constraints__], superclass, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check) return False else: return any(_issubclass(subclass, t, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check) \ for t in super_args)
python
def _issubclass_Union_rec(subclass, superclass, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): """Helper for _issubclass_Union. """ # this function is partly based on code from typing module 3.5.2.2 super_args = get_Union_params(superclass) if super_args is None: return is_Union(subclass) elif is_Union(subclass): sub_args = get_Union_params(subclass) if sub_args is None: return False return all(_issubclass(c, superclass, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check) \ for c in (sub_args)) elif isinstance(subclass, TypeVar): if subclass in super_args: return True if subclass.__constraints__: return _issubclass(Union[subclass.__constraints__], superclass, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check) return False else: return any(_issubclass(subclass, t, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check) \ for t in super_args)
[ "def", "_issubclass_Union_rec", "(", "subclass", ",", "superclass", ",", "bound_Generic", ",", "bound_typevars", ",", "bound_typevars_readonly", ",", "follow_fwd_refs", ",", "_recursion_check", ")", ":", "# this function is partly based on code from typing module 3.5.2.2", "super_args", "=", "get_Union_params", "(", "superclass", ")", "if", "super_args", "is", "None", ":", "return", "is_Union", "(", "subclass", ")", "elif", "is_Union", "(", "subclass", ")", ":", "sub_args", "=", "get_Union_params", "(", "subclass", ")", "if", "sub_args", "is", "None", ":", "return", "False", "return", "all", "(", "_issubclass", "(", "c", ",", "superclass", ",", "bound_Generic", ",", "bound_typevars", ",", "bound_typevars_readonly", ",", "follow_fwd_refs", ",", "_recursion_check", ")", "for", "c", "in", "(", "sub_args", ")", ")", "elif", "isinstance", "(", "subclass", ",", "TypeVar", ")", ":", "if", "subclass", "in", "super_args", ":", "return", "True", "if", "subclass", ".", "__constraints__", ":", "return", "_issubclass", "(", "Union", "[", "subclass", ".", "__constraints__", "]", ",", "superclass", ",", "bound_Generic", ",", "bound_typevars", ",", "bound_typevars_readonly", ",", "follow_fwd_refs", ",", "_recursion_check", ")", "return", "False", "else", ":", "return", "any", "(", "_issubclass", "(", "subclass", ",", "t", ",", "bound_Generic", ",", "bound_typevars", ",", "bound_typevars_readonly", ",", "follow_fwd_refs", ",", "_recursion_check", ")", "for", "t", "in", "super_args", ")" ]
Helper for _issubclass_Union.
[ "Helper", "for", "_issubclass_Union", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L1532-L1558
train
Stewori/pytypes
pytypes/type_util.py
_isinstance
def _isinstance(obj, cls, bound_Generic=None, bound_typevars=None, bound_typevars_readonly=False, follow_fwd_refs=True, _recursion_check=None): """Access this via ``pytypes.is_of_type``. Works like ``isinstance``, but supports PEP 484 style types from ``typing`` module. obj : Any The object to check for being an instance of ``cls``. cls : type The type to check for ``obj`` being an instance of. bound_Generic : Optional[Generic] A type object holding values for unbound typevars occurring in ``cls``. Default: None If ``cls`` contains unbound ``TypeVar``s and ``bound_Generic`` is provided, this function attempts to retrieve corresponding values for the unbound ``TypeVar``s from ``bound_Generic``. In collision case with ``bound_typevars`` the value from ``bound_Generic`` if preferred. bound_typevars : Optional[Dict[typing.TypeVar, type]] A dictionary holding values for unbound typevars occurring in ``cls``. Default: {} Depending on ``bound_typevars_readonly`` pytypes can also bind values to typevars as needed. This is done by inserting according mappings into this dictionary. This can e.g. be useful to infer values for ``TypeVar``s or to consistently check a set of ``TypeVar``s across multiple calls, e.g. when checking all arguments of a function call. In collision case with ``bound_Generic`` the value from ``bound_Generic`` if preferred. bound_typevars_readonly : bool Defines if pytypes is allowed to write into the ``bound_typevars`` dictionary. Default: True If set to False, pytypes cannot assign values to ``TypeVar``s, but only checks regarding values already present in ``bound_typevars`` or ``bound_Generic``. follow_fwd_refs : bool Defines if ``ForwardRef``s should be explored. Default: True If this is set to ``False`` and a ``ForwardRef`` is encountered, pytypes aborts the check raising a ForwardRefError. _recursion_check : Optional[Dict[type, Set[type]]] Internally used for recursion checks. Default: None If ``Union``s and ``ForwardRef``s occur in the same type, recursions can occur. As soon as a ``ForwardRef`` is encountered, pytypes automatically creates this dictionary and continues in recursion-proof manner. """ if bound_typevars is None: bound_typevars = {} # Special treatment if cls is Iterable[...] if is_Generic(cls) and cls.__origin__ is typing.Iterable: if not is_iterable(obj): return False itp = get_iterable_itemtype(obj) if itp is None: return not pytypes.check_iterables else: return _issubclass(itp, cls.__args__[0], bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check) if is_Callable(cls): return _isinstance_Callable(obj, cls, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check) return _issubclass(deep_type(obj), cls, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check)
python
def _isinstance(obj, cls, bound_Generic=None, bound_typevars=None, bound_typevars_readonly=False, follow_fwd_refs=True, _recursion_check=None): """Access this via ``pytypes.is_of_type``. Works like ``isinstance``, but supports PEP 484 style types from ``typing`` module. obj : Any The object to check for being an instance of ``cls``. cls : type The type to check for ``obj`` being an instance of. bound_Generic : Optional[Generic] A type object holding values for unbound typevars occurring in ``cls``. Default: None If ``cls`` contains unbound ``TypeVar``s and ``bound_Generic`` is provided, this function attempts to retrieve corresponding values for the unbound ``TypeVar``s from ``bound_Generic``. In collision case with ``bound_typevars`` the value from ``bound_Generic`` if preferred. bound_typevars : Optional[Dict[typing.TypeVar, type]] A dictionary holding values for unbound typevars occurring in ``cls``. Default: {} Depending on ``bound_typevars_readonly`` pytypes can also bind values to typevars as needed. This is done by inserting according mappings into this dictionary. This can e.g. be useful to infer values for ``TypeVar``s or to consistently check a set of ``TypeVar``s across multiple calls, e.g. when checking all arguments of a function call. In collision case with ``bound_Generic`` the value from ``bound_Generic`` if preferred. bound_typevars_readonly : bool Defines if pytypes is allowed to write into the ``bound_typevars`` dictionary. Default: True If set to False, pytypes cannot assign values to ``TypeVar``s, but only checks regarding values already present in ``bound_typevars`` or ``bound_Generic``. follow_fwd_refs : bool Defines if ``ForwardRef``s should be explored. Default: True If this is set to ``False`` and a ``ForwardRef`` is encountered, pytypes aborts the check raising a ForwardRefError. _recursion_check : Optional[Dict[type, Set[type]]] Internally used for recursion checks. Default: None If ``Union``s and ``ForwardRef``s occur in the same type, recursions can occur. As soon as a ``ForwardRef`` is encountered, pytypes automatically creates this dictionary and continues in recursion-proof manner. """ if bound_typevars is None: bound_typevars = {} # Special treatment if cls is Iterable[...] if is_Generic(cls) and cls.__origin__ is typing.Iterable: if not is_iterable(obj): return False itp = get_iterable_itemtype(obj) if itp is None: return not pytypes.check_iterables else: return _issubclass(itp, cls.__args__[0], bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check) if is_Callable(cls): return _isinstance_Callable(obj, cls, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check) return _issubclass(deep_type(obj), cls, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check)
[ "def", "_isinstance", "(", "obj", ",", "cls", ",", "bound_Generic", "=", "None", ",", "bound_typevars", "=", "None", ",", "bound_typevars_readonly", "=", "False", ",", "follow_fwd_refs", "=", "True", ",", "_recursion_check", "=", "None", ")", ":", "if", "bound_typevars", "is", "None", ":", "bound_typevars", "=", "{", "}", "# Special treatment if cls is Iterable[...]", "if", "is_Generic", "(", "cls", ")", "and", "cls", ".", "__origin__", "is", "typing", ".", "Iterable", ":", "if", "not", "is_iterable", "(", "obj", ")", ":", "return", "False", "itp", "=", "get_iterable_itemtype", "(", "obj", ")", "if", "itp", "is", "None", ":", "return", "not", "pytypes", ".", "check_iterables", "else", ":", "return", "_issubclass", "(", "itp", ",", "cls", ".", "__args__", "[", "0", "]", ",", "bound_Generic", ",", "bound_typevars", ",", "bound_typevars_readonly", ",", "follow_fwd_refs", ",", "_recursion_check", ")", "if", "is_Callable", "(", "cls", ")", ":", "return", "_isinstance_Callable", "(", "obj", ",", "cls", ",", "bound_Generic", ",", "bound_typevars", ",", "bound_typevars_readonly", ",", "follow_fwd_refs", ",", "_recursion_check", ")", "return", "_issubclass", "(", "deep_type", "(", "obj", ")", ",", "cls", ",", "bound_Generic", ",", "bound_typevars", ",", "bound_typevars_readonly", ",", "follow_fwd_refs", ",", "_recursion_check", ")" ]
Access this via ``pytypes.is_of_type``. Works like ``isinstance``, but supports PEP 484 style types from ``typing`` module. obj : Any The object to check for being an instance of ``cls``. cls : type The type to check for ``obj`` being an instance of. bound_Generic : Optional[Generic] A type object holding values for unbound typevars occurring in ``cls``. Default: None If ``cls`` contains unbound ``TypeVar``s and ``bound_Generic`` is provided, this function attempts to retrieve corresponding values for the unbound ``TypeVar``s from ``bound_Generic``. In collision case with ``bound_typevars`` the value from ``bound_Generic`` if preferred. bound_typevars : Optional[Dict[typing.TypeVar, type]] A dictionary holding values for unbound typevars occurring in ``cls``. Default: {} Depending on ``bound_typevars_readonly`` pytypes can also bind values to typevars as needed. This is done by inserting according mappings into this dictionary. This can e.g. be useful to infer values for ``TypeVar``s or to consistently check a set of ``TypeVar``s across multiple calls, e.g. when checking all arguments of a function call. In collision case with ``bound_Generic`` the value from ``bound_Generic`` if preferred. bound_typevars_readonly : bool Defines if pytypes is allowed to write into the ``bound_typevars`` dictionary. Default: True If set to False, pytypes cannot assign values to ``TypeVar``s, but only checks regarding values already present in ``bound_typevars`` or ``bound_Generic``. follow_fwd_refs : bool Defines if ``ForwardRef``s should be explored. Default: True If this is set to ``False`` and a ``ForwardRef`` is encountered, pytypes aborts the check raising a ForwardRefError. _recursion_check : Optional[Dict[type, Set[type]]] Internally used for recursion checks. Default: None If ``Union``s and ``ForwardRef``s occur in the same type, recursions can occur. As soon as a ``ForwardRef`` is encountered, pytypes automatically creates this dictionary and continues in recursion-proof manner.
[ "Access", "this", "via", "pytypes", ".", "is_of_type", ".", "Works", "like", "isinstance", "but", "supports", "PEP", "484", "style", "types", "from", "typing", "module", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L1847-L1909
train
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): """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
[ "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", "]", ")", "# \t\t\t\t\traise pytypes.ReturnTypeError(_make_generator_error_message(deep_type(a), gen,", "# \t\t\t\t\t\t\tgen_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", "]", ")", "# \t\t\t\traise pytypes.InputTypeError(_make_generator_error_message(deep_type(sn), gen,", "# \t\t\t\t\t\tgen_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", "]", ")", "# \t\t\traise pytypes.ReturnTypeError(_make_generator_error_message(sttp, gen,", "# \t\t\t\t\tgen_type.__args__[2], 'has incompatible return type'))", "raise", "st" ]
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
train
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): """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])
[ "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", "]", ")", "# \t\t\t\traise pytypes.ReturnTypeError(_make_generator_error_message(tpa, gen,", "# \t\t\t\t\t\tgen_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", "]", ")" ]
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
train
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): """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
[ "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" ]
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
train
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): """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
[ "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" ]
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
train
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): """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
[ "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" ]
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
train
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): """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
[ "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" ]
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
train
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): """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)
[ "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", ")" ]
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
train
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): """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
[ "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" ]
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
train
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): """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
[ "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" ]
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
train
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): """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
[ "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" ]
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", ".", "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", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/__init__.py#L390-L406
train
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): """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
[ "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" ]
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", "option", ".", "If", "retrospective", "is", "true", "this", "will", "also", "affect", "already", "imported", "modules", "not", "only", "future", "imports", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/__init__.py#L409-L422
train
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): """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
[ "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" ]
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", ".", "If", "retrospective", "is", "true", "this", "will", "also", "affect", "already", "imported", "modules", "not", "only", "future", "imports", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/__init__.py#L425-L438
train
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): """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
[ "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" ]
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", ".", "If", "retrospective", "is", "true", "this", "will", "also", "affect", "already", "imported", "modules", "not", "only", "future", "imports", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/__init__.py#L441-L454
train
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): """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()
[ "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", "(", ")" ]
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
train
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): """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()
[ "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", "(", ")" ]
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
train
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): """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)
[ "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", ")" ]
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
train
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): """Works like typechecked, but is only applicable to classes. """ 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
train
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): """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
[ "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" ]
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
train
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): """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
[ "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
train
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): """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)
[ "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", ")" ]
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", ".", "type", "hints", "of", "the", "function", "or", "method", "hosting", "the", "call", "to", "check_argument_types", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/typechecker.py#L1167-L1172
train
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): """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)
[ "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", "of", "the", "function", "or", "method", "hosting", "the", "call", "to", "check_return_type", "." ]
b814d38709e84c0e0825caf8b721c20eb5a8ab3b
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/typechecker.py#L1175-L1180
train
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): """ 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)
[ "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", ")" ]
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
train
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): """ 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)
[ "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", ")" ]
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
train
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): """ 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)
[ "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", ")" ]
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
train
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): """ 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}
[ "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", "}" ]
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
train
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): """ 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)
[ "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", ")" ]
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
train
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): """ 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
[ "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" ]
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
train
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): """ 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)
[ "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", ")" ]
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", "needs", "to", "call", "add_flownode_to_graph", "." ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_import.py#L381-L393
train
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): """ 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"
[ "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\"" ]
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
train
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): """ 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)
[ "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", ")" ]
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
train
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): """ 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])
[ "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", "]", ")" ]
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
train
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): """ 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)
[ "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", ")" ]
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
train
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): """ 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])
[ "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", "]", ")" ]
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
train
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): """ 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])
[ "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", "]", ")" ]
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
train
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): """ 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])
[ "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", "]", ")" ]
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
train
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): """ 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])
[ "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", "]", ")" ]
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
train
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): """ 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])
[ "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
train
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): """ 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)
[ "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", ")" ]
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
train
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): """ 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)
[ "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", ")" ]
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
train
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): """ 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)
[ "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", ")" ]
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
train
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): """ 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
[ "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" ]
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
train
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): """ 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)
[ "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", ")" ]
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
train
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): """ 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)
[ "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", ")" ]
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
train
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): """ 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])
[ "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", "]", ")" ]
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
train
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): """ 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])
[ "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", "]", ")" ]
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
train
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): """ 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])
[ "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", "]", ")" ]
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
train
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): """ 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])
[ "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", "]", ")" ]
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
train
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): """ 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
[ "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" ]
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
train
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): """ 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
[ "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" ]
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", "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", "." ]
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_import_utils.py#L39-L114
train
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): """ 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
[ "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" ]
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
train
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): """ 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
[ "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
train
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): """ 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() ])
[ "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", "(", ")", "]", ")" ]
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
train
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): """ 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()
[ "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", "(", ")" ]
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
train
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): """ 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)
[ "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", ")" ]
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
train
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=""): """ 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)
[ "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", ")" ]
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
train
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=""): """ 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
[ "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" ]
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
train
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): """ 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")
[ "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\"", ")" ]
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
train