partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
test
OALParser.p_create_class_event_statement
statement : CREATE EVENT INSTANCE variable_name OF event_specification TO identifier CLASS
bridgepoint/oal.py
def p_create_class_event_statement(self, p): '''statement : CREATE EVENT INSTANCE variable_name OF event_specification TO identifier CLASS''' p[0] = CreateClassEventNode(variable_name=p[4], event_specification=p[6], key_letter=p[8])
def p_create_class_event_statement(self, p): '''statement : CREATE EVENT INSTANCE variable_name OF event_specification TO identifier CLASS''' p[0] = CreateClassEventNode(variable_name=p[4], event_specification=p[6], key_letter=p[8])
[ "statement", ":", "CREATE", "EVENT", "INSTANCE", "variable_name", "OF", "event_specification", "TO", "identifier", "CLASS" ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/oal.py#L1299-L1303
[ "def", "p_create_class_event_statement", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "CreateClassEventNode", "(", "variable_name", "=", "p", "[", "4", "]", ",", "event_specification", "=", "p", "[", "6", "]", ",", "key_letter", "=", "p", "[", "8", "]", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
OALParser.p_create_assigner_event_statement
statement : CREATE EVENT INSTANCE variable_name OF event_specification TO identifier ASSIGNER
bridgepoint/oal.py
def p_create_assigner_event_statement(self, p): '''statement : CREATE EVENT INSTANCE variable_name OF event_specification TO identifier ASSIGNER''' p[0] = CreateClassEventNode(variable_name=p[4], event_specification=p[6], key_letter=p[8])
def p_create_assigner_event_statement(self, p): '''statement : CREATE EVENT INSTANCE variable_name OF event_specification TO identifier ASSIGNER''' p[0] = CreateClassEventNode(variable_name=p[4], event_specification=p[6], key_letter=p[8])
[ "statement", ":", "CREATE", "EVENT", "INSTANCE", "variable_name", "OF", "event_specification", "TO", "identifier", "ASSIGNER" ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/oal.py#L1306-L1310
[ "def", "p_create_assigner_event_statement", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "CreateClassEventNode", "(", "variable_name", "=", "p", "[", "4", "]", ",", "event_specification", "=", "p", "[", "6", "]", ",", "key_letter", "=", "p", "[", "8", "]", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
OALParser.p_create_creator_event_statement
statement : CREATE EVENT INSTANCE variable_name OF event_specification TO identifier CREATOR
bridgepoint/oal.py
def p_create_creator_event_statement(self, p): '''statement : CREATE EVENT INSTANCE variable_name OF event_specification TO identifier CREATOR''' p[0] = CreateCreatorEventNode(variable_name=p[4], event_specification=p[6], key_letter=p[8])
def p_create_creator_event_statement(self, p): '''statement : CREATE EVENT INSTANCE variable_name OF event_specification TO identifier CREATOR''' p[0] = CreateCreatorEventNode(variable_name=p[4], event_specification=p[6], key_letter=p[8])
[ "statement", ":", "CREATE", "EVENT", "INSTANCE", "variable_name", "OF", "event_specification", "TO", "identifier", "CREATOR" ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/oal.py#L1313-L1317
[ "def", "p_create_creator_event_statement", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "CreateCreatorEventNode", "(", "variable_name", "=", "p", "[", "4", "]", ",", "event_specification", "=", "p", "[", "6", "]", ",", "key_letter", "=", "p", "[", "8", "]", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
OALParser.p_create_instance_event_statement_1
statement : CREATE EVENT INSTANCE variable_name OF event_specification TO variable_access
bridgepoint/oal.py
def p_create_instance_event_statement_1(self, p): '''statement : CREATE EVENT INSTANCE variable_name OF event_specification TO variable_access''' p[0] = CreateInstanceEventNode(variable_name=p[4], event_specification=p[6], to_variable_access=p[8])
def p_create_instance_event_statement_1(self, p): '''statement : CREATE EVENT INSTANCE variable_name OF event_specification TO variable_access''' p[0] = CreateInstanceEventNode(variable_name=p[4], event_specification=p[6], to_variable_access=p[8])
[ "statement", ":", "CREATE", "EVENT", "INSTANCE", "variable_name", "OF", "event_specification", "TO", "variable_access" ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/oal.py#L1320-L1324
[ "def", "p_create_instance_event_statement_1", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "CreateInstanceEventNode", "(", "variable_name", "=", "p", "[", "4", "]", ",", "event_specification", "=", "p", "[", "6", "]", ",", "to_variable_access", "=", "p", "[", "8", "]", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
OALParser.p_create_instance_event_statement_2
statement : CREATE EVENT INSTANCE variable_name OF event_specification TO self_access
bridgepoint/oal.py
def p_create_instance_event_statement_2(self, p): '''statement : CREATE EVENT INSTANCE variable_name OF event_specification TO self_access''' p[0] = CreateInstanceEventNode(variable_name=p[4], event_specification=p[6], to_variable_access=p[8])
def p_create_instance_event_statement_2(self, p): '''statement : CREATE EVENT INSTANCE variable_name OF event_specification TO self_access''' p[0] = CreateInstanceEventNode(variable_name=p[4], event_specification=p[6], to_variable_access=p[8])
[ "statement", ":", "CREATE", "EVENT", "INSTANCE", "variable_name", "OF", "event_specification", "TO", "self_access" ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/oal.py#L1327-L1331
[ "def", "p_create_instance_event_statement_2", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "CreateInstanceEventNode", "(", "variable_name", "=", "p", "[", "4", "]", ",", "event_specification", "=", "p", "[", "6", "]", ",", "to_variable_access", "=", "p", "[", "8", "]", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
OALParser.p_event_specification
event_specification : identifier event_meaning event_data
bridgepoint/oal.py
def p_event_specification(self, p): '''event_specification : identifier event_meaning event_data''' p[0] = EventSpecNode(identifier=p[1], meaning=p[2], event_data=p[3])
def p_event_specification(self, p): '''event_specification : identifier event_meaning event_data''' p[0] = EventSpecNode(identifier=p[1], meaning=p[2], event_data=p[3])
[ "event_specification", ":", "identifier", "event_meaning", "event_data" ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/oal.py#L1339-L1343
[ "def", "p_event_specification", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "EventSpecNode", "(", "identifier", "=", "p", "[", "1", "]", ",", "meaning", "=", "p", "[", "2", "]", ",", "event_data", "=", "p", "[", "3", "]", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
OALParser.p_ploymorphic_event_spec
event_specification : identifier TIMES event_meaning event_data
bridgepoint/oal.py
def p_ploymorphic_event_spec(self, p): '''event_specification : identifier TIMES event_meaning event_data''' p[0] = EventSpecNode(identifier=p[1], meaning=p[3], event_data=p[4])
def p_ploymorphic_event_spec(self, p): '''event_specification : identifier TIMES event_meaning event_data''' p[0] = EventSpecNode(identifier=p[1], meaning=p[3], event_data=p[4])
[ "event_specification", ":", "identifier", "TIMES", "event_meaning", "event_data" ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/oal.py#L1346-L1350
[ "def", "p_ploymorphic_event_spec", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "EventSpecNode", "(", "identifier", "=", "p", "[", "1", "]", ",", "meaning", "=", "p", "[", "3", "]", ",", "event_data", "=", "p", "[", "4", "]", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
OALParser.p_for_statement
statement : FOR EACH variable_name IN variable_name block END_FOR
bridgepoint/oal.py
def p_for_statement(self, p): '''statement : FOR EACH variable_name IN variable_name block END_FOR''' p[0] = ForEachNode(instance_variable_name=p[3], set_variable_name=p[5], block=p[6])
def p_for_statement(self, p): '''statement : FOR EACH variable_name IN variable_name block END_FOR''' p[0] = ForEachNode(instance_variable_name=p[3], set_variable_name=p[5], block=p[6])
[ "statement", ":", "FOR", "EACH", "variable_name", "IN", "variable_name", "block", "END_FOR" ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/oal.py#L1421-L1425
[ "def", "p_for_statement", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "ForEachNode", "(", "instance_variable_name", "=", "p", "[", "3", "]", ",", "set_variable_name", "=", "p", "[", "5", "]", ",", "block", "=", "p", "[", "6", "]", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
OALParser.p_if_statement
statement : IF expression block elif_list else_clause END_IF
bridgepoint/oal.py
def p_if_statement(self, p): '''statement : IF expression block elif_list else_clause END_IF''' p[0] = IfNode(expression=p[2], block=p[3], elif_list=p[4], else_clause=p[5])
def p_if_statement(self, p): '''statement : IF expression block elif_list else_clause END_IF''' p[0] = IfNode(expression=p[2], block=p[3], elif_list=p[4], else_clause=p[5])
[ "statement", ":", "IF", "expression", "block", "elif_list", "else_clause", "END_IF" ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/oal.py#L1434-L1439
[ "def", "p_if_statement", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "IfNode", "(", "expression", "=", "p", "[", "2", "]", ",", "block", "=", "p", "[", "3", "]", ",", "elif_list", "=", "p", "[", "4", "]", ",", "else_clause", "=", "p", "[", "5", "]", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
OALParser.p_relate_statement_1
statement : RELATE instance_name TO instance_name ACROSS rel_id
bridgepoint/oal.py
def p_relate_statement_1(self, p): '''statement : RELATE instance_name TO instance_name ACROSS rel_id''' p[0] = RelateNode(from_variable_name=p[2], to_variable_name=p[4], rel_id=p[6], phrase=None)
def p_relate_statement_1(self, p): '''statement : RELATE instance_name TO instance_name ACROSS rel_id''' p[0] = RelateNode(from_variable_name=p[2], to_variable_name=p[4], rel_id=p[6], phrase=None)
[ "statement", ":", "RELATE", "instance_name", "TO", "instance_name", "ACROSS", "rel_id" ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/oal.py#L1473-L1478
[ "def", "p_relate_statement_1", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "RelateNode", "(", "from_variable_name", "=", "p", "[", "2", "]", ",", "to_variable_name", "=", "p", "[", "4", "]", ",", "rel_id", "=", "p", "[", "6", "]", ",", "phrase", "=", "None", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
OALParser.p_relate_statement_2
statement : RELATE instance_name TO instance_name ACROSS rel_id DOT phrase
bridgepoint/oal.py
def p_relate_statement_2(self, p): '''statement : RELATE instance_name TO instance_name ACROSS rel_id DOT phrase''' p[0] = RelateNode(from_variable_name=p[2], to_variable_name=p[4], rel_id=p[6], phrase=p[8])
def p_relate_statement_2(self, p): '''statement : RELATE instance_name TO instance_name ACROSS rel_id DOT phrase''' p[0] = RelateNode(from_variable_name=p[2], to_variable_name=p[4], rel_id=p[6], phrase=p[8])
[ "statement", ":", "RELATE", "instance_name", "TO", "instance_name", "ACROSS", "rel_id", "DOT", "phrase" ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/oal.py#L1481-L1486
[ "def", "p_relate_statement_2", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "RelateNode", "(", "from_variable_name", "=", "p", "[", "2", "]", ",", "to_variable_name", "=", "p", "[", "4", "]", ",", "rel_id", "=", "p", "[", "6", "]", ",", "phrase", "=", "p", "[", "8", "]", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
OALParser.p_relate_using_statement_1
statement : RELATE instance_name TO instance_name ACROSS rel_id USING instance_name
bridgepoint/oal.py
def p_relate_using_statement_1(self, p): '''statement : RELATE instance_name TO instance_name ACROSS rel_id USING instance_name''' p[0] = RelateUsingNode(from_variable_name=p[2], to_variable_name=p[4], rel_id=p[6], phrase=None, using_variable_name=p[8])
def p_relate_using_statement_1(self, p): '''statement : RELATE instance_name TO instance_name ACROSS rel_id USING instance_name''' p[0] = RelateUsingNode(from_variable_name=p[2], to_variable_name=p[4], rel_id=p[6], phrase=None, using_variable_name=p[8])
[ "statement", ":", "RELATE", "instance_name", "TO", "instance_name", "ACROSS", "rel_id", "USING", "instance_name" ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/oal.py#L1489-L1495
[ "def", "p_relate_using_statement_1", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "RelateUsingNode", "(", "from_variable_name", "=", "p", "[", "2", "]", ",", "to_variable_name", "=", "p", "[", "4", "]", ",", "rel_id", "=", "p", "[", "6", "]", ",", "phrase", "=", "None", ",", "using_variable_name", "=", "p", "[", "8", "]", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
OALParser.p_unrelate_statement_1
statement : UNRELATE instance_name FROM instance_name ACROSS rel_id
bridgepoint/oal.py
def p_unrelate_statement_1(self, p): '''statement : UNRELATE instance_name FROM instance_name ACROSS rel_id''' p[0] = UnrelateNode(from_variable_name=p[2], to_variable_name=p[4], rel_id=p[6], phrase=None)
def p_unrelate_statement_1(self, p): '''statement : UNRELATE instance_name FROM instance_name ACROSS rel_id''' p[0] = UnrelateNode(from_variable_name=p[2], to_variable_name=p[4], rel_id=p[6], phrase=None)
[ "statement", ":", "UNRELATE", "instance_name", "FROM", "instance_name", "ACROSS", "rel_id" ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/oal.py#L1507-L1512
[ "def", "p_unrelate_statement_1", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "UnrelateNode", "(", "from_variable_name", "=", "p", "[", "2", "]", ",", "to_variable_name", "=", "p", "[", "4", "]", ",", "rel_id", "=", "p", "[", "6", "]", ",", "phrase", "=", "None", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
OALParser.p_unrelate_statement_2
statement : UNRELATE instance_name FROM instance_name ACROSS rel_id DOT phrase
bridgepoint/oal.py
def p_unrelate_statement_2(self, p): '''statement : UNRELATE instance_name FROM instance_name ACROSS rel_id DOT phrase''' p[0] = UnrelateNode(from_variable_name=p[2], to_variable_name=p[4], rel_id=p[6], phrase=p[8])
def p_unrelate_statement_2(self, p): '''statement : UNRELATE instance_name FROM instance_name ACROSS rel_id DOT phrase''' p[0] = UnrelateNode(from_variable_name=p[2], to_variable_name=p[4], rel_id=p[6], phrase=p[8])
[ "statement", ":", "UNRELATE", "instance_name", "FROM", "instance_name", "ACROSS", "rel_id", "DOT", "phrase" ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/oal.py#L1515-L1520
[ "def", "p_unrelate_statement_2", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "UnrelateNode", "(", "from_variable_name", "=", "p", "[", "2", "]", ",", "to_variable_name", "=", "p", "[", "4", "]", ",", "rel_id", "=", "p", "[", "6", "]", ",", "phrase", "=", "p", "[", "8", "]", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
OALParser.p_unrelate_statement_using_1
statement : UNRELATE instance_name FROM instance_name ACROSS rel_id USING instance_name
bridgepoint/oal.py
def p_unrelate_statement_using_1(self, p): '''statement : UNRELATE instance_name FROM instance_name ACROSS rel_id USING instance_name''' p[0] = UnrelateUsingNode(from_variable_name=p[2], to_variable_name=p[4], rel_id=p[6], phrase=None, using_variable_name=p[8])
def p_unrelate_statement_using_1(self, p): '''statement : UNRELATE instance_name FROM instance_name ACROSS rel_id USING instance_name''' p[0] = UnrelateUsingNode(from_variable_name=p[2], to_variable_name=p[4], rel_id=p[6], phrase=None, using_variable_name=p[8])
[ "statement", ":", "UNRELATE", "instance_name", "FROM", "instance_name", "ACROSS", "rel_id", "USING", "instance_name" ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/oal.py#L1523-L1529
[ "def", "p_unrelate_statement_using_1", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "UnrelateUsingNode", "(", "from_variable_name", "=", "p", "[", "2", "]", ",", "to_variable_name", "=", "p", "[", "4", "]", ",", "rel_id", "=", "p", "[", "6", "]", ",", "phrase", "=", "None", ",", "using_variable_name", "=", "p", "[", "8", "]", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
OALParser.p_select_from_statement_1
statement : SELECT ANY variable_name FROM INSTANCES OF identifier | SELECT MANY variable_name FROM INSTANCES OF identifier
bridgepoint/oal.py
def p_select_from_statement_1(self, p): ''' statement : SELECT ANY variable_name FROM INSTANCES OF identifier | SELECT MANY variable_name FROM INSTANCES OF identifier ''' p[0] = SelectFromNode(cardinality=p[2], variable_name=p[3], key_letter=p[7])
def p_select_from_statement_1(self, p): ''' statement : SELECT ANY variable_name FROM INSTANCES OF identifier | SELECT MANY variable_name FROM INSTANCES OF identifier ''' p[0] = SelectFromNode(cardinality=p[2], variable_name=p[3], key_letter=p[7])
[ "statement", ":", "SELECT", "ANY", "variable_name", "FROM", "INSTANCES", "OF", "identifier", "|", "SELECT", "MANY", "variable_name", "FROM", "INSTANCES", "OF", "identifier" ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/oal.py#L1541-L1548
[ "def", "p_select_from_statement_1", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "SelectFromNode", "(", "cardinality", "=", "p", "[", "2", "]", ",", "variable_name", "=", "p", "[", "3", "]", ",", "key_letter", "=", "p", "[", "7", "]", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
OALParser.p_select_from_statement_2
statement : SELECT ANY variable_name FROM identifier | SELECT MANY variable_name FROM identifier
bridgepoint/oal.py
def p_select_from_statement_2(self, p): ''' statement : SELECT ANY variable_name FROM identifier | SELECT MANY variable_name FROM identifier ''' p[0] = SelectFromNode(cardinality=p[2], variable_name=p[3], key_letter=p[5])
def p_select_from_statement_2(self, p): ''' statement : SELECT ANY variable_name FROM identifier | SELECT MANY variable_name FROM identifier ''' p[0] = SelectFromNode(cardinality=p[2], variable_name=p[3], key_letter=p[5])
[ "statement", ":", "SELECT", "ANY", "variable_name", "FROM", "identifier", "|", "SELECT", "MANY", "variable_name", "FROM", "identifier" ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/oal.py#L1551-L1558
[ "def", "p_select_from_statement_2", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "SelectFromNode", "(", "cardinality", "=", "p", "[", "2", "]", ",", "variable_name", "=", "p", "[", "3", "]", ",", "key_letter", "=", "p", "[", "5", "]", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
OALParser.p_select_from_where_statement_1
statement : SELECT ANY variable_name FROM INSTANCES OF identifier WHERE expression | SELECT MANY variable_name FROM INSTANCES OF identifier WHERE expression
bridgepoint/oal.py
def p_select_from_where_statement_1(self, p): ''' statement : SELECT ANY variable_name FROM INSTANCES OF identifier WHERE expression | SELECT MANY variable_name FROM INSTANCES OF identifier WHERE expression ''' p[0] = SelectFromWhereNode(cardinality=p[2], variable_name=p[3], key_letter=p[7], where_clause=p[9])
def p_select_from_where_statement_1(self, p): ''' statement : SELECT ANY variable_name FROM INSTANCES OF identifier WHERE expression | SELECT MANY variable_name FROM INSTANCES OF identifier WHERE expression ''' p[0] = SelectFromWhereNode(cardinality=p[2], variable_name=p[3], key_letter=p[7], where_clause=p[9])
[ "statement", ":", "SELECT", "ANY", "variable_name", "FROM", "INSTANCES", "OF", "identifier", "WHERE", "expression", "|", "SELECT", "MANY", "variable_name", "FROM", "INSTANCES", "OF", "identifier", "WHERE", "expression" ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/oal.py#L1561-L1569
[ "def", "p_select_from_where_statement_1", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "SelectFromWhereNode", "(", "cardinality", "=", "p", "[", "2", "]", ",", "variable_name", "=", "p", "[", "3", "]", ",", "key_letter", "=", "p", "[", "7", "]", ",", "where_clause", "=", "p", "[", "9", "]", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
OALParser.p_select_from_where_statement_2
statement : SELECT ANY variable_name FROM identifier WHERE expression | SELECT MANY variable_name FROM identifier WHERE expression
bridgepoint/oal.py
def p_select_from_where_statement_2(self, p): ''' statement : SELECT ANY variable_name FROM identifier WHERE expression | SELECT MANY variable_name FROM identifier WHERE expression ''' p[0] = SelectFromWhereNode(cardinality=p[2], variable_name=p[3], key_letter=p[5], where_clause=p[7])
def p_select_from_where_statement_2(self, p): ''' statement : SELECT ANY variable_name FROM identifier WHERE expression | SELECT MANY variable_name FROM identifier WHERE expression ''' p[0] = SelectFromWhereNode(cardinality=p[2], variable_name=p[3], key_letter=p[5], where_clause=p[7])
[ "statement", ":", "SELECT", "ANY", "variable_name", "FROM", "identifier", "WHERE", "expression", "|", "SELECT", "MANY", "variable_name", "FROM", "identifier", "WHERE", "expression" ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/oal.py#L1572-L1580
[ "def", "p_select_from_where_statement_2", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "SelectFromWhereNode", "(", "cardinality", "=", "p", "[", "2", "]", ",", "variable_name", "=", "p", "[", "3", "]", ",", "key_letter", "=", "p", "[", "5", "]", ",", "where_clause", "=", "p", "[", "7", "]", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
OALParser.p_select_related_statement
statement : SELECT ONE variable_name RELATED BY navigation_hook navigation_chain | SELECT ANY variable_name RELATED BY navigation_hook navigation_chain | SELECT MANY variable_name RELATED BY navigation_hook navigation_chain
bridgepoint/oal.py
def p_select_related_statement(self, p): ''' statement : SELECT ONE variable_name RELATED BY navigation_hook navigation_chain | SELECT ANY variable_name RELATED BY navigation_hook navigation_chain | SELECT MANY variable_name RELATED BY navigation_hook navigation_chain ''' p[0] = SelectRelatedNode(cardinality=p[2], variable_name=p[3], handle=p[6], navigation_chain=p[7])
def p_select_related_statement(self, p): ''' statement : SELECT ONE variable_name RELATED BY navigation_hook navigation_chain | SELECT ANY variable_name RELATED BY navigation_hook navigation_chain | SELECT MANY variable_name RELATED BY navigation_hook navigation_chain ''' p[0] = SelectRelatedNode(cardinality=p[2], variable_name=p[3], handle=p[6], navigation_chain=p[7])
[ "statement", ":", "SELECT", "ONE", "variable_name", "RELATED", "BY", "navigation_hook", "navigation_chain", "|", "SELECT", "ANY", "variable_name", "RELATED", "BY", "navigation_hook", "navigation_chain", "|", "SELECT", "MANY", "variable_name", "RELATED", "BY", "navigation_hook", "navigation_chain" ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/oal.py#L1590-L1599
[ "def", "p_select_related_statement", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "SelectRelatedNode", "(", "cardinality", "=", "p", "[", "2", "]", ",", "variable_name", "=", "p", "[", "3", "]", ",", "handle", "=", "p", "[", "6", "]", ",", "navigation_chain", "=", "p", "[", "7", "]", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
OALParser.p_select_related_where_statement
statement : SELECT ONE variable_name RELATED BY navigation_hook navigation_chain WHERE expression | SELECT ANY variable_name RELATED BY navigation_hook navigation_chain WHERE expression | SELECT MANY variable_name RELATED BY navigation_hook navigation_chain WHERE expression
bridgepoint/oal.py
def p_select_related_where_statement(self, p): ''' statement : SELECT ONE variable_name RELATED BY navigation_hook navigation_chain WHERE expression | SELECT ANY variable_name RELATED BY navigation_hook navigation_chain WHERE expression | SELECT MANY variable_name RELATED BY navigation_hook navigation_chain WHERE expression ''' p[0] = SelectRelatedWhereNode(cardinality=p[2], variable_name=p[3], handle=p[6], navigation_chain=p[7], where_clause=p[9])
def p_select_related_where_statement(self, p): ''' statement : SELECT ONE variable_name RELATED BY navigation_hook navigation_chain WHERE expression | SELECT ANY variable_name RELATED BY navigation_hook navigation_chain WHERE expression | SELECT MANY variable_name RELATED BY navigation_hook navigation_chain WHERE expression ''' p[0] = SelectRelatedWhereNode(cardinality=p[2], variable_name=p[3], handle=p[6], navigation_chain=p[7], where_clause=p[9])
[ "statement", ":", "SELECT", "ONE", "variable_name", "RELATED", "BY", "navigation_hook", "navigation_chain", "WHERE", "expression", "|", "SELECT", "ANY", "variable_name", "RELATED", "BY", "navigation_hook", "navigation_chain", "WHERE", "expression", "|", "SELECT", "MANY", "variable_name", "RELATED", "BY", "navigation_hook", "navigation_chain", "WHERE", "expression" ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/oal.py#L1602-L1612
[ "def", "p_select_related_where_statement", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "SelectRelatedWhereNode", "(", "cardinality", "=", "p", "[", "2", "]", ",", "variable_name", "=", "p", "[", "3", "]", ",", "handle", "=", "p", "[", "6", "]", ",", "navigation_chain", "=", "p", "[", "7", "]", ",", "where_clause", "=", "p", "[", "9", "]", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
OALParser.p_navigation_step_1
navigation_step : ARROW identifier LSQBR identifier RSQBR
bridgepoint/oal.py
def p_navigation_step_1(self, p): '''navigation_step : ARROW identifier LSQBR identifier RSQBR''' p[0] = NavigationStepNode(key_letter=p[2], rel_id=p[4], phrase=None)
def p_navigation_step_1(self, p): '''navigation_step : ARROW identifier LSQBR identifier RSQBR''' p[0] = NavigationStepNode(key_letter=p[2], rel_id=p[4], phrase=None)
[ "navigation_step", ":", "ARROW", "identifier", "LSQBR", "identifier", "RSQBR" ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/oal.py#L1627-L1631
[ "def", "p_navigation_step_1", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "NavigationStepNode", "(", "key_letter", "=", "p", "[", "2", "]", ",", "rel_id", "=", "p", "[", "4", "]", ",", "phrase", "=", "None", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
OALParser.p_navigation_step_2
navigation_step : ARROW identifier LSQBR identifier DOT phrase RSQBR
bridgepoint/oal.py
def p_navigation_step_2(self, p): '''navigation_step : ARROW identifier LSQBR identifier DOT phrase RSQBR''' p[0] = NavigationStepNode(key_letter=p[2], rel_id=p[4], phrase=p[6])
def p_navigation_step_2(self, p): '''navigation_step : ARROW identifier LSQBR identifier DOT phrase RSQBR''' p[0] = NavigationStepNode(key_letter=p[2], rel_id=p[4], phrase=p[6])
[ "navigation_step", ":", "ARROW", "identifier", "LSQBR", "identifier", "DOT", "phrase", "RSQBR" ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/oal.py#L1634-L1638
[ "def", "p_navigation_step_2", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "NavigationStepNode", "(", "key_letter", "=", "p", "[", "2", "]", ",", "rel_id", "=", "p", "[", "4", "]", ",", "phrase", "=", "p", "[", "6", "]", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
OALParser.p_implicit_invocation
implicit_invocation : namespace DOUBLECOLON identifier LPAREN parameter_list RPAREN
bridgepoint/oal.py
def p_implicit_invocation(self, p): '''implicit_invocation : namespace DOUBLECOLON identifier LPAREN parameter_list RPAREN''' p[0] = ImplicitInvocationNode(namespace=p[1], action_name=p[3], parameter_list=p[5])
def p_implicit_invocation(self, p): '''implicit_invocation : namespace DOUBLECOLON identifier LPAREN parameter_list RPAREN''' p[0] = ImplicitInvocationNode(namespace=p[1], action_name=p[3], parameter_list=p[5])
[ "implicit_invocation", ":", "namespace", "DOUBLECOLON", "identifier", "LPAREN", "parameter_list", "RPAREN" ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/oal.py#L1650-L1654
[ "def", "p_implicit_invocation", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "ImplicitInvocationNode", "(", "namespace", "=", "p", "[", "1", "]", ",", "action_name", "=", "p", "[", "3", "]", ",", "parameter_list", "=", "p", "[", "5", "]", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
OALParser.p_operation_invocation_1
instance_invocation : structure DOT identifier LPAREN parameter_list RPAREN
bridgepoint/oal.py
def p_operation_invocation_1(self, p): '''instance_invocation : structure DOT identifier LPAREN parameter_list RPAREN''' p[0] = InstanceInvocationNode(handle=p[1], action_name=p[3], parameter_list=p[5])
def p_operation_invocation_1(self, p): '''instance_invocation : structure DOT identifier LPAREN parameter_list RPAREN''' p[0] = InstanceInvocationNode(handle=p[1], action_name=p[3], parameter_list=p[5])
[ "instance_invocation", ":", "structure", "DOT", "identifier", "LPAREN", "parameter_list", "RPAREN" ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/oal.py#L1663-L1667
[ "def", "p_operation_invocation_1", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "InstanceInvocationNode", "(", "handle", "=", "p", "[", "1", "]", ",", "action_name", "=", "p", "[", "3", "]", ",", "parameter_list", "=", "p", "[", "5", "]", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
OALParser.p_arithmetic_expression
expression : expression PLUS expression | expression MINUS expression | expression TIMES expression | expression DIV expression | expression MOD expression
bridgepoint/oal.py
def p_arithmetic_expression(self, p): ''' expression : expression PLUS expression | expression MINUS expression | expression TIMES expression | expression DIV expression | expression MOD expression ''' p[0] = BinaryOperationNode(left=p[1], operator=p[2], right=p[3])
def p_arithmetic_expression(self, p): ''' expression : expression PLUS expression | expression MINUS expression | expression TIMES expression | expression DIV expression | expression MOD expression ''' p[0] = BinaryOperationNode(left=p[1], operator=p[2], right=p[3])
[ "expression", ":", "expression", "PLUS", "expression", "|", "expression", "MINUS", "expression", "|", "expression", "TIMES", "expression", "|", "expression", "DIV", "expression", "|", "expression", "MOD", "expression" ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/oal.py#L1729-L1739
[ "def", "p_arithmetic_expression", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "BinaryOperationNode", "(", "left", "=", "p", "[", "1", "]", ",", "operator", "=", "p", "[", "2", "]", ",", "right", "=", "p", "[", "3", "]", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
OALParser.p_boolean_expression
expression : expression LE expression | expression LESSTHAN expression | expression DOUBLEEQUAL expression | expression NOTEQUAL expression | expression GE expression | expression GT expression | expression AND expression | expression OR expression
bridgepoint/oal.py
def p_boolean_expression(self, p): ''' expression : expression LE expression | expression LESSTHAN expression | expression DOUBLEEQUAL expression | expression NOTEQUAL expression | expression GE expression | expression GT expression | expression AND expression | expression OR expression ''' p[0] = BinaryOperationNode(left=p[1], operator=p[2], right=p[3])
def p_boolean_expression(self, p): ''' expression : expression LE expression | expression LESSTHAN expression | expression DOUBLEEQUAL expression | expression NOTEQUAL expression | expression GE expression | expression GT expression | expression AND expression | expression OR expression ''' p[0] = BinaryOperationNode(left=p[1], operator=p[2], right=p[3])
[ "expression", ":", "expression", "LE", "expression", "|", "expression", "LESSTHAN", "expression", "|", "expression", "DOUBLEEQUAL", "expression", "|", "expression", "NOTEQUAL", "expression", "|", "expression", "GE", "expression", "|", "expression", "GT", "expression", "|", "expression", "AND", "expression", "|", "expression", "OR", "expression" ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/oal.py#L1742-L1755
[ "def", "p_boolean_expression", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "BinaryOperationNode", "(", "left", "=", "p", "[", "1", "]", ",", "operator", "=", "p", "[", "2", "]", ",", "right", "=", "p", "[", "3", "]", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
MalformedMessage.wrap
Wraps exceptions in the context with :exc:`MalformedMessage`.
zeronimo/exceptions.py
def wrap(cls, message_parts): """Wraps exceptions in the context with :exc:`MalformedMessage`.""" try: yield except BaseException as exception: __, __, tb = sys.exc_info() reraise(cls, cls(exception, message_parts), tb)
def wrap(cls, message_parts): """Wraps exceptions in the context with :exc:`MalformedMessage`.""" try: yield except BaseException as exception: __, __, tb = sys.exc_info() reraise(cls, cls(exception, message_parts), tb)
[ "Wraps", "exceptions", "in", "the", "context", "with", ":", "exc", ":", "MalformedMessage", "." ]
sublee/zeronimo
python
https://github.com/sublee/zeronimo/blob/b216638232932718d2cbc5eabd870c8f5b5e83fb/zeronimo/exceptions.py#L76-L82
[ "def", "wrap", "(", "cls", ",", "message_parts", ")", ":", "try", ":", "yield", "except", "BaseException", "as", "exception", ":", "__", ",", "__", ",", "tb", "=", "sys", ".", "exc_info", "(", ")", "reraise", "(", "cls", ",", "cls", "(", "exception", ",", "message_parts", ")", ",", "tb", ")" ]
b216638232932718d2cbc5eabd870c8f5b5e83fb
test
api_crime
Gets the crime nearby to a given postcode. :param request: The aiohttp request. :return: A json representation of the crimes near the postcode.
hyperion/api/crime.py
async def api_crime(request): """ Gets the crime nearby to a given postcode. :param request: The aiohttp request. :return: A json representation of the crimes near the postcode. """ postcode: Optional[str] = request.match_info.get('postcode', None) try: coroutine = get_postcode_random() if postcode == "random" else get_postcode(postcode) postcode: Optional[Postcode] = await coroutine except CachingError as e: return web.Response(body=e.status, status=500) try: crime = await fetch_crime(postcode.lat, postcode.long) except (ApiError, CircuitBreakerError): raise web.HTTPInternalServerError(body=f"Requested crime is not cached, and can't be retrieved.") if crime is None: return web.HTTPNotFound(body="No Police Data") else: return str_json_response(crime)
async def api_crime(request): """ Gets the crime nearby to a given postcode. :param request: The aiohttp request. :return: A json representation of the crimes near the postcode. """ postcode: Optional[str] = request.match_info.get('postcode', None) try: coroutine = get_postcode_random() if postcode == "random" else get_postcode(postcode) postcode: Optional[Postcode] = await coroutine except CachingError as e: return web.Response(body=e.status, status=500) try: crime = await fetch_crime(postcode.lat, postcode.long) except (ApiError, CircuitBreakerError): raise web.HTTPInternalServerError(body=f"Requested crime is not cached, and can't be retrieved.") if crime is None: return web.HTTPNotFound(body="No Police Data") else: return str_json_response(crime)
[ "Gets", "the", "crime", "nearby", "to", "a", "given", "postcode", ".", ":", "param", "request", ":", "The", "aiohttp", "request", ".", ":", "return", ":", "A", "json", "representation", "of", "the", "crimes", "near", "the", "postcode", "." ]
arlyon/hyperion
python
https://github.com/arlyon/hyperion/blob/d8de0388ba98b85ce472e0f49ac18fecb14d3343/hyperion/api/crime.py#L13-L35
[ "async", "def", "api_crime", "(", "request", ")", ":", "postcode", ":", "Optional", "[", "str", "]", "=", "request", ".", "match_info", ".", "get", "(", "'postcode'", ",", "None", ")", "try", ":", "coroutine", "=", "get_postcode_random", "(", ")", "if", "postcode", "==", "\"random\"", "else", "get_postcode", "(", "postcode", ")", "postcode", ":", "Optional", "[", "Postcode", "]", "=", "await", "coroutine", "except", "CachingError", "as", "e", ":", "return", "web", ".", "Response", "(", "body", "=", "e", ".", "status", ",", "status", "=", "500", ")", "try", ":", "crime", "=", "await", "fetch_crime", "(", "postcode", ".", "lat", ",", "postcode", ".", "long", ")", "except", "(", "ApiError", ",", "CircuitBreakerError", ")", ":", "raise", "web", ".", "HTTPInternalServerError", "(", "body", "=", "f\"Requested crime is not cached, and can't be retrieved.\"", ")", "if", "crime", "is", "None", ":", "return", "web", ".", "HTTPNotFound", "(", "body", "=", "\"No Police Data\"", ")", "else", ":", "return", "str_json_response", "(", "crime", ")" ]
d8de0388ba98b85ce472e0f49ac18fecb14d3343
test
api_neighbourhood
Gets police data about a neighbourhood. :param request: The aiohttp request. :return: The police data for that post code.
hyperion/api/crime.py
async def api_neighbourhood(request): """ Gets police data about a neighbourhood. :param request: The aiohttp request. :return: The police data for that post code. """ postcode: Optional[str] = request.match_info.get('postcode', None) try: postcode = (await get_postcode_random()) if postcode == "random" else postcode neighbourhood = await get_neighbourhood(postcode) except CachingError as e: raise web.HTTPInternalServerError(text=e.status) if neighbourhood is None: raise web.HTTPNotFound(text="No Police Data") else: return str_json_response(neighbourhood.serialize())
async def api_neighbourhood(request): """ Gets police data about a neighbourhood. :param request: The aiohttp request. :return: The police data for that post code. """ postcode: Optional[str] = request.match_info.get('postcode', None) try: postcode = (await get_postcode_random()) if postcode == "random" else postcode neighbourhood = await get_neighbourhood(postcode) except CachingError as e: raise web.HTTPInternalServerError(text=e.status) if neighbourhood is None: raise web.HTTPNotFound(text="No Police Data") else: return str_json_response(neighbourhood.serialize())
[ "Gets", "police", "data", "about", "a", "neighbourhood", ".", ":", "param", "request", ":", "The", "aiohttp", "request", ".", ":", "return", ":", "The", "police", "data", "for", "that", "post", "code", "." ]
arlyon/hyperion
python
https://github.com/arlyon/hyperion/blob/d8de0388ba98b85ce472e0f49ac18fecb14d3343/hyperion/api/crime.py#L38-L55
[ "async", "def", "api_neighbourhood", "(", "request", ")", ":", "postcode", ":", "Optional", "[", "str", "]", "=", "request", ".", "match_info", ".", "get", "(", "'postcode'", ",", "None", ")", "try", ":", "postcode", "=", "(", "await", "get_postcode_random", "(", ")", ")", "if", "postcode", "==", "\"random\"", "else", "postcode", "neighbourhood", "=", "await", "get_neighbourhood", "(", "postcode", ")", "except", "CachingError", "as", "e", ":", "raise", "web", ".", "HTTPInternalServerError", "(", "text", "=", "e", ".", "status", ")", "if", "neighbourhood", "is", "None", ":", "raise", "web", ".", "HTTPNotFound", "(", "text", "=", "\"No Police Data\"", ")", "else", ":", "return", "str_json_response", "(", "neighbourhood", ".", "serialize", "(", ")", ")" ]
d8de0388ba98b85ce472e0f49ac18fecb14d3343
test
RequestCmd.create_queue
Create message content and properties to create queue with QMFv2 :param name: Name of queue to create :type name: str :param strict: Whether command should fail when unrecognized properties are provided Not used by QMFv2 Default: True :type strict: bool :param auto_delete: Whether queue should be auto deleted Default: False :type auto_delete: bool :param auto_delete_timeout: Timeout in seconds for auto deleting queue Default: 10 :type auto_delete_timeout: int :returns: Tuple containing content and method properties
brokerlso/qmfv2.py
def create_queue(self, name, strict=True, auto_delete=False, auto_delete_timeout=0): """Create message content and properties to create queue with QMFv2 :param name: Name of queue to create :type name: str :param strict: Whether command should fail when unrecognized properties are provided Not used by QMFv2 Default: True :type strict: bool :param auto_delete: Whether queue should be auto deleted Default: False :type auto_delete: bool :param auto_delete_timeout: Timeout in seconds for auto deleting queue Default: 10 :type auto_delete_timeout: int :returns: Tuple containing content and method properties """ content = {"_object_id": {"_object_name": self.object_name}, "_method_name": "create", "_arguments": {"type": "queue", "name": name, "strict": strict, "properties": {"auto-delete": auto_delete, "qpid.auto_delete_timeout": auto_delete_timeout}}} logger.debug("Message content -> {0}".format(content)) return content, self.method_properties
def create_queue(self, name, strict=True, auto_delete=False, auto_delete_timeout=0): """Create message content and properties to create queue with QMFv2 :param name: Name of queue to create :type name: str :param strict: Whether command should fail when unrecognized properties are provided Not used by QMFv2 Default: True :type strict: bool :param auto_delete: Whether queue should be auto deleted Default: False :type auto_delete: bool :param auto_delete_timeout: Timeout in seconds for auto deleting queue Default: 10 :type auto_delete_timeout: int :returns: Tuple containing content and method properties """ content = {"_object_id": {"_object_name": self.object_name}, "_method_name": "create", "_arguments": {"type": "queue", "name": name, "strict": strict, "properties": {"auto-delete": auto_delete, "qpid.auto_delete_timeout": auto_delete_timeout}}} logger.debug("Message content -> {0}".format(content)) return content, self.method_properties
[ "Create", "message", "content", "and", "properties", "to", "create", "queue", "with", "QMFv2" ]
codeghar/brokerlso
python
https://github.com/codeghar/brokerlso/blob/e110e12502b090e12b06c7615dd0a96a14a92585/brokerlso/qmfv2.py#L18-L45
[ "def", "create_queue", "(", "self", ",", "name", ",", "strict", "=", "True", ",", "auto_delete", "=", "False", ",", "auto_delete_timeout", "=", "0", ")", ":", "content", "=", "{", "\"_object_id\"", ":", "{", "\"_object_name\"", ":", "self", ".", "object_name", "}", ",", "\"_method_name\"", ":", "\"create\"", ",", "\"_arguments\"", ":", "{", "\"type\"", ":", "\"queue\"", ",", "\"name\"", ":", "name", ",", "\"strict\"", ":", "strict", ",", "\"properties\"", ":", "{", "\"auto-delete\"", ":", "auto_delete", ",", "\"qpid.auto_delete_timeout\"", ":", "auto_delete_timeout", "}", "}", "}", "logger", ".", "debug", "(", "\"Message content -> {0}\"", ".", "format", "(", "content", ")", ")", "return", "content", ",", "self", ".", "method_properties" ]
e110e12502b090e12b06c7615dd0a96a14a92585
test
RequestCmd.delete_queue
Create message content and properties to delete queue with QMFv2 :param name: Name of queue to delete :type name: str :returns: Tuple containing content and method properties
brokerlso/qmfv2.py
def delete_queue(self, name): """Create message content and properties to delete queue with QMFv2 :param name: Name of queue to delete :type name: str :returns: Tuple containing content and method properties """ content = {"_object_id": {"_object_name": self.object_name}, "_method_name": "delete", "_arguments": {"type": "queue", "name": name, "options": dict()}} # "A nested map with the key options. This is presently unused." logger.debug("Message content -> {0}".format(content)) return content, self.method_properties
def delete_queue(self, name): """Create message content and properties to delete queue with QMFv2 :param name: Name of queue to delete :type name: str :returns: Tuple containing content and method properties """ content = {"_object_id": {"_object_name": self.object_name}, "_method_name": "delete", "_arguments": {"type": "queue", "name": name, "options": dict()}} # "A nested map with the key options. This is presently unused." logger.debug("Message content -> {0}".format(content)) return content, self.method_properties
[ "Create", "message", "content", "and", "properties", "to", "delete", "queue", "with", "QMFv2" ]
codeghar/brokerlso
python
https://github.com/codeghar/brokerlso/blob/e110e12502b090e12b06c7615dd0a96a14a92585/brokerlso/qmfv2.py#L109-L124
[ "def", "delete_queue", "(", "self", ",", "name", ")", ":", "content", "=", "{", "\"_object_id\"", ":", "{", "\"_object_name\"", ":", "self", ".", "object_name", "}", ",", "\"_method_name\"", ":", "\"delete\"", ",", "\"_arguments\"", ":", "{", "\"type\"", ":", "\"queue\"", ",", "\"name\"", ":", "name", ",", "\"options\"", ":", "dict", "(", ")", "}", "}", "# \"A nested map with the key options. This is presently unused.\"", "logger", ".", "debug", "(", "\"Message content -> {0}\"", ".", "format", "(", "content", ")", ")", "return", "content", ",", "self", ".", "method_properties" ]
e110e12502b090e12b06c7615dd0a96a14a92585
test
RequestCmd.list_queues
Create message content and properties to list all queues with QMFv2 :returns: Tuple containing content and query properties
brokerlso/qmfv2.py
def list_queues(self): """Create message content and properties to list all queues with QMFv2 :returns: Tuple containing content and query properties """ content = {"_what": "OBJECT", "_schema_id": {"_class_name": "queue"}} logger.debug("Message content -> {0}".format(content)) return content, self.query_properties
def list_queues(self): """Create message content and properties to list all queues with QMFv2 :returns: Tuple containing content and query properties """ content = {"_what": "OBJECT", "_schema_id": {"_class_name": "queue"}} logger.debug("Message content -> {0}".format(content)) return content, self.query_properties
[ "Create", "message", "content", "and", "properties", "to", "list", "all", "queues", "with", "QMFv2" ]
codeghar/brokerlso
python
https://github.com/codeghar/brokerlso/blob/e110e12502b090e12b06c7615dd0a96a14a92585/brokerlso/qmfv2.py#L157-L166
[ "def", "list_queues", "(", "self", ")", ":", "content", "=", "{", "\"_what\"", ":", "\"OBJECT\"", ",", "\"_schema_id\"", ":", "{", "\"_class_name\"", ":", "\"queue\"", "}", "}", "logger", ".", "debug", "(", "\"Message content -> {0}\"", ".", "format", "(", "content", ")", ")", "return", "content", ",", "self", ".", "query_properties" ]
e110e12502b090e12b06c7615dd0a96a14a92585
test
RequestCmd.list_exchanges
Create message content and properties to list all exchanges with QMFv2 :returns: Tuple containing content and query properties
brokerlso/qmfv2.py
def list_exchanges(self): """Create message content and properties to list all exchanges with QMFv2 :returns: Tuple containing content and query properties """ content = {"_what": "OBJECT", "_schema_id": {"_class_name": "exchange"}} logger.debug("Message content -> {0}".format(content)) return content, self.query_properties
def list_exchanges(self): """Create message content and properties to list all exchanges with QMFv2 :returns: Tuple containing content and query properties """ content = {"_what": "OBJECT", "_schema_id": {"_class_name": "exchange"}} logger.debug("Message content -> {0}".format(content)) return content, self.query_properties
[ "Create", "message", "content", "and", "properties", "to", "list", "all", "exchanges", "with", "QMFv2" ]
codeghar/brokerlso
python
https://github.com/codeghar/brokerlso/blob/e110e12502b090e12b06c7615dd0a96a14a92585/brokerlso/qmfv2.py#L168-L177
[ "def", "list_exchanges", "(", "self", ")", ":", "content", "=", "{", "\"_what\"", ":", "\"OBJECT\"", ",", "\"_schema_id\"", ":", "{", "\"_class_name\"", ":", "\"exchange\"", "}", "}", "logger", ".", "debug", "(", "\"Message content -> {0}\"", ".", "format", "(", "content", ")", ")", "return", "content", ",", "self", ".", "query_properties" ]
e110e12502b090e12b06c7615dd0a96a14a92585
test
RequestCmd.purge_queue
Create message content and properties to purge queue with QMFv2 :param name: Name of queue to purge :type name: str :returns: Tuple containing content and method properties
brokerlso/qmfv2.py
def purge_queue(self, name): """Create message content and properties to purge queue with QMFv2 :param name: Name of queue to purge :type name: str :returns: Tuple containing content and method properties """ content = {"_object_id": {"_object_name": "org.apache.qpid.broker:queue:{0}".format(name)}, "_method_name": "purge", "_arguments": {"type": "queue", "name": name, "filter": dict()}} logger.debug("Message content -> {0}".format(content)) return content, self.method_properties
def purge_queue(self, name): """Create message content and properties to purge queue with QMFv2 :param name: Name of queue to purge :type name: str :returns: Tuple containing content and method properties """ content = {"_object_id": {"_object_name": "org.apache.qpid.broker:queue:{0}".format(name)}, "_method_name": "purge", "_arguments": {"type": "queue", "name": name, "filter": dict()}} logger.debug("Message content -> {0}".format(content)) return content, self.method_properties
[ "Create", "message", "content", "and", "properties", "to", "purge", "queue", "with", "QMFv2" ]
codeghar/brokerlso
python
https://github.com/codeghar/brokerlso/blob/e110e12502b090e12b06c7615dd0a96a14a92585/brokerlso/qmfv2.py#L179-L194
[ "def", "purge_queue", "(", "self", ",", "name", ")", ":", "content", "=", "{", "\"_object_id\"", ":", "{", "\"_object_name\"", ":", "\"org.apache.qpid.broker:queue:{0}\"", ".", "format", "(", "name", ")", "}", ",", "\"_method_name\"", ":", "\"purge\"", ",", "\"_arguments\"", ":", "{", "\"type\"", ":", "\"queue\"", ",", "\"name\"", ":", "name", ",", "\"filter\"", ":", "dict", "(", ")", "}", "}", "logger", ".", "debug", "(", "\"Message content -> {0}\"", ".", "format", "(", "content", ")", ")", "return", "content", ",", "self", ".", "method_properties" ]
e110e12502b090e12b06c7615dd0a96a14a92585
test
Gmailer._create_msg
attachments should be a list of paths
comdev/gmail_api.py
def _create_msg(self, to, subject, msgHtml, msgPlain, attachments=None): ''' attachments should be a list of paths ''' sender = self.sender if attachments and isinstance(attachments, str): attachments = [attachments] else: attachments = list(attachments or []) msg = MIMEMultipart('alternative') msg['Subject'] = subject msg['From'] = sender msg['To'] = to msg.attach(MIMEText(msgPlain, 'plain')) msg.attach(MIMEText(msgHtml, 'html')) # append attachments if any for path in attachments: _attachment = self._prep_attachment(path) msg.attach(_attachment) raw = base64.urlsafe_b64encode(msg.as_bytes()).decode() #raw = raw.decode() body = {'raw': raw} return body
def _create_msg(self, to, subject, msgHtml, msgPlain, attachments=None): ''' attachments should be a list of paths ''' sender = self.sender if attachments and isinstance(attachments, str): attachments = [attachments] else: attachments = list(attachments or []) msg = MIMEMultipart('alternative') msg['Subject'] = subject msg['From'] = sender msg['To'] = to msg.attach(MIMEText(msgPlain, 'plain')) msg.attach(MIMEText(msgHtml, 'html')) # append attachments if any for path in attachments: _attachment = self._prep_attachment(path) msg.attach(_attachment) raw = base64.urlsafe_b64encode(msg.as_bytes()).decode() #raw = raw.decode() body = {'raw': raw} return body
[ "attachments", "should", "be", "a", "list", "of", "paths" ]
kejbaly2/comdev
python
https://github.com/kejbaly2/comdev/blob/5a9067d3c1ae46eeccb9d36e8c231ea5224b42b4/comdev/gmail_api.py#L127-L152
[ "def", "_create_msg", "(", "self", ",", "to", ",", "subject", ",", "msgHtml", ",", "msgPlain", ",", "attachments", "=", "None", ")", ":", "sender", "=", "self", ".", "sender", "if", "attachments", "and", "isinstance", "(", "attachments", ",", "str", ")", ":", "attachments", "=", "[", "attachments", "]", "else", ":", "attachments", "=", "list", "(", "attachments", "or", "[", "]", ")", "msg", "=", "MIMEMultipart", "(", "'alternative'", ")", "msg", "[", "'Subject'", "]", "=", "subject", "msg", "[", "'From'", "]", "=", "sender", "msg", "[", "'To'", "]", "=", "to", "msg", ".", "attach", "(", "MIMEText", "(", "msgPlain", ",", "'plain'", ")", ")", "msg", ".", "attach", "(", "MIMEText", "(", "msgHtml", ",", "'html'", ")", ")", "# append attachments if any", "for", "path", "in", "attachments", ":", "_attachment", "=", "self", ".", "_prep_attachment", "(", "path", ")", "msg", ".", "attach", "(", "_attachment", ")", "raw", "=", "base64", ".", "urlsafe_b64encode", "(", "msg", ".", "as_bytes", "(", ")", ")", ".", "decode", "(", ")", "#raw = raw.decode()", "body", "=", "{", "'raw'", ":", "raw", "}", "return", "body" ]
5a9067d3c1ae46eeccb9d36e8c231ea5224b42b4
test
RemoteResult.set_remote_exception
Raises an exception as a :exc:`RemoteException`.
zeronimo/results.py
def set_remote_exception(self, remote_exc_info): """Raises an exception as a :exc:`RemoteException`.""" exc_type, exc_str, filename, lineno = remote_exc_info[:4] exc_type = RemoteException.compose(exc_type) exc = exc_type(exc_str, filename, lineno, self.worker_info) if len(remote_exc_info) > 4: state = remote_exc_info[4] exc.__setstate__(state) self.set_exception(exc)
def set_remote_exception(self, remote_exc_info): """Raises an exception as a :exc:`RemoteException`.""" exc_type, exc_str, filename, lineno = remote_exc_info[:4] exc_type = RemoteException.compose(exc_type) exc = exc_type(exc_str, filename, lineno, self.worker_info) if len(remote_exc_info) > 4: state = remote_exc_info[4] exc.__setstate__(state) self.set_exception(exc)
[ "Raises", "an", "exception", "as", "a", ":", "exc", ":", "RemoteException", "." ]
sublee/zeronimo
python
https://github.com/sublee/zeronimo/blob/b216638232932718d2cbc5eabd870c8f5b5e83fb/zeronimo/results.py#L59-L67
[ "def", "set_remote_exception", "(", "self", ",", "remote_exc_info", ")", ":", "exc_type", ",", "exc_str", ",", "filename", ",", "lineno", "=", "remote_exc_info", "[", ":", "4", "]", "exc_type", "=", "RemoteException", ".", "compose", "(", "exc_type", ")", "exc", "=", "exc_type", "(", "exc_str", ",", "filename", ",", "lineno", ",", "self", ".", "worker_info", ")", "if", "len", "(", "remote_exc_info", ")", ">", "4", ":", "state", "=", "remote_exc_info", "[", "4", "]", "exc", ".", "__setstate__", "(", "state", ")", "self", ".", "set_exception", "(", "exc", ")" ]
b216638232932718d2cbc5eabd870c8f5b5e83fb
test
OCR.read
Returns the text from an image at a given url.
zorg_network_camera/ocr.py
def read(self): """ Returns the text from an image at a given url. """ # Only download the image if it has changed if self.connection.has_changed(): image_path = self.connection.download_image() image = Image.open(image_path) self.text_cache = pytesseract.image_to_string(image) image.close() return self.text_cache
def read(self): """ Returns the text from an image at a given url. """ # Only download the image if it has changed if self.connection.has_changed(): image_path = self.connection.download_image() image = Image.open(image_path) self.text_cache = pytesseract.image_to_string(image) image.close() return self.text_cache
[ "Returns", "the", "text", "from", "an", "image", "at", "a", "given", "url", "." ]
zorg/zorg-network-camera
python
https://github.com/zorg/zorg-network-camera/blob/e2d15725e50370e2df0c38be6b039215873e4278/zorg_network_camera/ocr.py#L19-L31
[ "def", "read", "(", "self", ")", ":", "# Only download the image if it has changed", "if", "self", ".", "connection", ".", "has_changed", "(", ")", ":", "image_path", "=", "self", ".", "connection", ".", "download_image", "(", ")", "image", "=", "Image", ".", "open", "(", "image_path", ")", "self", ".", "text_cache", "=", "pytesseract", ".", "image_to_string", "(", "image", ")", "image", ".", "close", "(", ")", "return", "self", ".", "text_cache" ]
e2d15725e50370e2df0c38be6b039215873e4278
test
OCR.text_visible
Returns true or false based on if the OCR process has read actual words. This is needed to prevent non-words from being added to the queue since the ocr process can sometimes return values that are not meaningfull.
zorg_network_camera/ocr.py
def text_visible(self): """ Returns true or false based on if the OCR process has read actual words. This is needed to prevent non-words from being added to the queue since the ocr process can sometimes return values that are not meaningfull. """ # Split the input string at points with any amount of whitespace words = self.read().split() # Light weight check to see if a word exists for word in words: # If the word is a numeric value if word.lstrip('-').replace('.', '', 1).isdigit(): return True # If the word contains only letters with a length from 2 to 20 if word.isalpha() and (len(word) > 1 or len(word) <= 20): return True return False
def text_visible(self): """ Returns true or false based on if the OCR process has read actual words. This is needed to prevent non-words from being added to the queue since the ocr process can sometimes return values that are not meaningfull. """ # Split the input string at points with any amount of whitespace words = self.read().split() # Light weight check to see if a word exists for word in words: # If the word is a numeric value if word.lstrip('-').replace('.', '', 1).isdigit(): return True # If the word contains only letters with a length from 2 to 20 if word.isalpha() and (len(word) > 1 or len(word) <= 20): return True return False
[ "Returns", "true", "or", "false", "based", "on", "if", "the", "OCR", "process", "has", "read", "actual", "words", ".", "This", "is", "needed", "to", "prevent", "non", "-", "words", "from", "being", "added", "to", "the", "queue", "since", "the", "ocr", "process", "can", "sometimes", "return", "values", "that", "are", "not", "meaningfull", "." ]
zorg/zorg-network-camera
python
https://github.com/zorg/zorg-network-camera/blob/e2d15725e50370e2df0c38be6b039215873e4278/zorg_network_camera/ocr.py#L33-L55
[ "def", "text_visible", "(", "self", ")", ":", "# Split the input string at points with any amount of whitespace", "words", "=", "self", ".", "read", "(", ")", ".", "split", "(", ")", "# Light weight check to see if a word exists", "for", "word", "in", "words", ":", "# If the word is a numeric value", "if", "word", ".", "lstrip", "(", "'-'", ")", ".", "replace", "(", "'.'", ",", "''", ",", "1", ")", ".", "isdigit", "(", ")", ":", "return", "True", "# If the word contains only letters with a length from 2 to 20", "if", "word", ".", "isalpha", "(", ")", "and", "(", "len", "(", "word", ")", ">", "1", "or", "len", "(", "word", ")", "<=", "20", ")", ":", "return", "True", "return", "False" ]
e2d15725e50370e2df0c38be6b039215873e4278
test
Bike.get_most_recent_bike
Gets the most recently cached bike from the database. :return: The bike that was cached most recently.
hyperion/models/bike.py
def get_most_recent_bike() -> Optional['Bike']: """ Gets the most recently cached bike from the database. :return: The bike that was cached most recently. """ try: return Bike.select().order_by(Bike.cached_date.desc()).get() except pw.DoesNotExist: return None
def get_most_recent_bike() -> Optional['Bike']: """ Gets the most recently cached bike from the database. :return: The bike that was cached most recently. """ try: return Bike.select().order_by(Bike.cached_date.desc()).get() except pw.DoesNotExist: return None
[ "Gets", "the", "most", "recently", "cached", "bike", "from", "the", "database", ".", ":", "return", ":", "The", "bike", "that", "was", "cached", "most", "recently", "." ]
arlyon/hyperion
python
https://github.com/arlyon/hyperion/blob/d8de0388ba98b85ce472e0f49ac18fecb14d3343/hyperion/models/bike.py#L29-L37
[ "def", "get_most_recent_bike", "(", ")", "->", "Optional", "[", "'Bike'", "]", ":", "try", ":", "return", "Bike", ".", "select", "(", ")", ".", "order_by", "(", "Bike", ".", "cached_date", ".", "desc", "(", ")", ")", ".", "get", "(", ")", "except", "pw", ".", "DoesNotExist", ":", "return", "None" ]
d8de0388ba98b85ce472e0f49ac18fecb14d3343
test
main
Parse command line options and launch the interpreter
bridgepoint/interpret.py
def main(): ''' Parse command line options and launch the interpreter ''' parser = optparse.OptionParser(usage="%prog [options] <model_path> [another_model_path..]", version=xtuml.version.complete_string, formatter=optparse.TitledHelpFormatter()) parser.add_option("-v", "--verbosity", dest='verbosity', action="count", default=1, help="increase debug logging level") parser.add_option("-f", "--function", dest='function', action="store", help="invoke function named NAME", metavar='NAME') parser.add_option("-c", "--component", dest='component', action="store", help="look for the function in a component named NAME", metavar='NAME', default=None) (opts, args) = parser.parse_args() if len(args) == 0 or not opts.function: parser.print_help() sys.exit(1) levels = { 0: logging.ERROR, 1: logging.WARNING, 2: logging.INFO, 3: logging.DEBUG, } logging.basicConfig(level=levels.get(opts.verbosity, logging.DEBUG)) from bridgepoint import ooaofooa mm = ooaofooa.load_metamodel(args) c_c = mm.select_any('C_C', where(Name=opts.component)) domain = ooaofooa.mk_component(mm, c_c, derived_attributes=False) func = domain.find_symbol(opts.function) return func()
def main(): ''' Parse command line options and launch the interpreter ''' parser = optparse.OptionParser(usage="%prog [options] <model_path> [another_model_path..]", version=xtuml.version.complete_string, formatter=optparse.TitledHelpFormatter()) parser.add_option("-v", "--verbosity", dest='verbosity', action="count", default=1, help="increase debug logging level") parser.add_option("-f", "--function", dest='function', action="store", help="invoke function named NAME", metavar='NAME') parser.add_option("-c", "--component", dest='component', action="store", help="look for the function in a component named NAME", metavar='NAME', default=None) (opts, args) = parser.parse_args() if len(args) == 0 or not opts.function: parser.print_help() sys.exit(1) levels = { 0: logging.ERROR, 1: logging.WARNING, 2: logging.INFO, 3: logging.DEBUG, } logging.basicConfig(level=levels.get(opts.verbosity, logging.DEBUG)) from bridgepoint import ooaofooa mm = ooaofooa.load_metamodel(args) c_c = mm.select_any('C_C', where(Name=opts.component)) domain = ooaofooa.mk_component(mm, c_c, derived_attributes=False) func = domain.find_symbol(opts.function) return func()
[ "Parse", "command", "line", "options", "and", "launch", "the", "interpreter" ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/interpret.py#L553-L590
[ "def", "main", "(", ")", ":", "parser", "=", "optparse", ".", "OptionParser", "(", "usage", "=", "\"%prog [options] <model_path> [another_model_path..]\"", ",", "version", "=", "xtuml", ".", "version", ".", "complete_string", ",", "formatter", "=", "optparse", ".", "TitledHelpFormatter", "(", ")", ")", "parser", ".", "add_option", "(", "\"-v\"", ",", "\"--verbosity\"", ",", "dest", "=", "'verbosity'", ",", "action", "=", "\"count\"", ",", "default", "=", "1", ",", "help", "=", "\"increase debug logging level\"", ")", "parser", ".", "add_option", "(", "\"-f\"", ",", "\"--function\"", ",", "dest", "=", "'function'", ",", "action", "=", "\"store\"", ",", "help", "=", "\"invoke function named NAME\"", ",", "metavar", "=", "'NAME'", ")", "parser", ".", "add_option", "(", "\"-c\"", ",", "\"--component\"", ",", "dest", "=", "'component'", ",", "action", "=", "\"store\"", ",", "help", "=", "\"look for the function in a component named NAME\"", ",", "metavar", "=", "'NAME'", ",", "default", "=", "None", ")", "(", "opts", ",", "args", ")", "=", "parser", ".", "parse_args", "(", ")", "if", "len", "(", "args", ")", "==", "0", "or", "not", "opts", ".", "function", ":", "parser", ".", "print_help", "(", ")", "sys", ".", "exit", "(", "1", ")", "levels", "=", "{", "0", ":", "logging", ".", "ERROR", ",", "1", ":", "logging", ".", "WARNING", ",", "2", ":", "logging", ".", "INFO", ",", "3", ":", "logging", ".", "DEBUG", ",", "}", "logging", ".", "basicConfig", "(", "level", "=", "levels", ".", "get", "(", "opts", ".", "verbosity", ",", "logging", ".", "DEBUG", ")", ")", "from", "bridgepoint", "import", "ooaofooa", "mm", "=", "ooaofooa", ".", "load_metamodel", "(", "args", ")", "c_c", "=", "mm", ".", "select_any", "(", "'C_C'", ",", "where", "(", "Name", "=", "opts", ".", "component", ")", ")", "domain", "=", "ooaofooa", ".", "mk_component", "(", "mm", ",", "c_c", ",", "derived_attributes", "=", "False", ")", "func", "=", "domain", ".", "find_symbol", "(", "opts", ".", "function", ")", "return", "func", "(", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
main
Parse argv for options and arguments, and start schema generation.
bridgepoint/gen_sql_schema.py
def main(): ''' Parse argv for options and arguments, and start schema generation. ''' parser = optparse.OptionParser(usage="%prog [options] <model_path> [another_model_path...]", version=xtuml.version.complete_string, formatter=optparse.TitledHelpFormatter()) parser.set_description(__doc__.strip()) parser.add_option("-c", "--component", dest="component", metavar="NAME", help="export sql schema for the component named NAME", action="store", default=None) parser.add_option("-d", "--derived-attributes", dest="derived", help="include derived attributes in the schema", action="store_true", default=False) parser.add_option("-o", "--output", dest='output', metavar="PATH", help="save sql schema to PATH (required)", action="store", default=None) parser.add_option("-v", "--verbosity", dest='verbosity', action="count", help="increase debug logging level", default=2) (opts, args) = parser.parse_args() if len(args) == 0 or opts.output is None: parser.print_help() sys.exit(1) levels = { 0: logging.ERROR, 1: logging.WARNING, 2: logging.INFO, 3: logging.DEBUG, } logging.basicConfig(level=levels.get(opts.verbosity, logging.DEBUG)) loader = ooaofooa.Loader() for filename in args: loader.filename_input(filename) c = loader.build_component(opts.component, opts.derived) xtuml.persist_database(c, opts.output)
def main(): ''' Parse argv for options and arguments, and start schema generation. ''' parser = optparse.OptionParser(usage="%prog [options] <model_path> [another_model_path...]", version=xtuml.version.complete_string, formatter=optparse.TitledHelpFormatter()) parser.set_description(__doc__.strip()) parser.add_option("-c", "--component", dest="component", metavar="NAME", help="export sql schema for the component named NAME", action="store", default=None) parser.add_option("-d", "--derived-attributes", dest="derived", help="include derived attributes in the schema", action="store_true", default=False) parser.add_option("-o", "--output", dest='output', metavar="PATH", help="save sql schema to PATH (required)", action="store", default=None) parser.add_option("-v", "--verbosity", dest='verbosity', action="count", help="increase debug logging level", default=2) (opts, args) = parser.parse_args() if len(args) == 0 or opts.output is None: parser.print_help() sys.exit(1) levels = { 0: logging.ERROR, 1: logging.WARNING, 2: logging.INFO, 3: logging.DEBUG, } logging.basicConfig(level=levels.get(opts.verbosity, logging.DEBUG)) loader = ooaofooa.Loader() for filename in args: loader.filename_input(filename) c = loader.build_component(opts.component, opts.derived) xtuml.persist_database(c, opts.output)
[ "Parse", "argv", "for", "options", "and", "arguments", "and", "start", "schema", "generation", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/gen_sql_schema.py#L38-L82
[ "def", "main", "(", ")", ":", "parser", "=", "optparse", ".", "OptionParser", "(", "usage", "=", "\"%prog [options] <model_path> [another_model_path...]\"", ",", "version", "=", "xtuml", ".", "version", ".", "complete_string", ",", "formatter", "=", "optparse", ".", "TitledHelpFormatter", "(", ")", ")", "parser", ".", "set_description", "(", "__doc__", ".", "strip", "(", ")", ")", "parser", ".", "add_option", "(", "\"-c\"", ",", "\"--component\"", ",", "dest", "=", "\"component\"", ",", "metavar", "=", "\"NAME\"", ",", "help", "=", "\"export sql schema for the component named NAME\"", ",", "action", "=", "\"store\"", ",", "default", "=", "None", ")", "parser", ".", "add_option", "(", "\"-d\"", ",", "\"--derived-attributes\"", ",", "dest", "=", "\"derived\"", ",", "help", "=", "\"include derived attributes in the schema\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ")", "parser", ".", "add_option", "(", "\"-o\"", ",", "\"--output\"", ",", "dest", "=", "'output'", ",", "metavar", "=", "\"PATH\"", ",", "help", "=", "\"save sql schema to PATH (required)\"", ",", "action", "=", "\"store\"", ",", "default", "=", "None", ")", "parser", ".", "add_option", "(", "\"-v\"", ",", "\"--verbosity\"", ",", "dest", "=", "'verbosity'", ",", "action", "=", "\"count\"", ",", "help", "=", "\"increase debug logging level\"", ",", "default", "=", "2", ")", "(", "opts", ",", "args", ")", "=", "parser", ".", "parse_args", "(", ")", "if", "len", "(", "args", ")", "==", "0", "or", "opts", ".", "output", "is", "None", ":", "parser", ".", "print_help", "(", ")", "sys", ".", "exit", "(", "1", ")", "levels", "=", "{", "0", ":", "logging", ".", "ERROR", ",", "1", ":", "logging", ".", "WARNING", ",", "2", ":", "logging", ".", "INFO", ",", "3", ":", "logging", ".", "DEBUG", ",", "}", "logging", ".", "basicConfig", "(", "level", "=", "levels", ".", "get", "(", "opts", ".", "verbosity", ",", "logging", ".", "DEBUG", ")", ")", "loader", "=", "ooaofooa", ".", "Loader", "(", ")", "for", "filename", "in", "args", ":", "loader", ".", "filename_input", "(", "filename", ")", "c", "=", "loader", ".", "build_component", "(", "opts", ".", "component", ",", "opts", ".", "derived", ")", "xtuml", ".", "persist_database", "(", "c", ",", "opts", ".", "output", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
get_token
See: http://nodotcom.org/python-facebook-tutorial.html
comdev/facebook_api.py
def get_token(client_id, client_secret, client_access_token, page=None): """ See: http://nodotcom.org/python-facebook-tutorial.html """ payload = { 'grant_type': 'client_credentials', 'client_id': client_id, 'client_secret': client_secret, } if client_access_token: payload['grant_type'] = 'fb_exchange_token' payload['fb_exchange_token'] = client_access_token # response {"access_token":" ... ", "token_type":"bearer", "expires_in":..} response = requests.post( 'https://graph.facebook.com/oauth/access_token?', params=payload) access_token = response.json()['access_token'] return access_token
def get_token(client_id, client_secret, client_access_token, page=None): """ See: http://nodotcom.org/python-facebook-tutorial.html """ payload = { 'grant_type': 'client_credentials', 'client_id': client_id, 'client_secret': client_secret, } if client_access_token: payload['grant_type'] = 'fb_exchange_token' payload['fb_exchange_token'] = client_access_token # response {"access_token":" ... ", "token_type":"bearer", "expires_in":..} response = requests.post( 'https://graph.facebook.com/oauth/access_token?', params=payload) access_token = response.json()['access_token'] return access_token
[ "See", ":", "http", ":", "//", "nodotcom", ".", "org", "/", "python", "-", "facebook", "-", "tutorial", ".", "html" ]
kejbaly2/comdev
python
https://github.com/kejbaly2/comdev/blob/5a9067d3c1ae46eeccb9d36e8c231ea5224b42b4/comdev/facebook_api.py#L19-L38
[ "def", "get_token", "(", "client_id", ",", "client_secret", ",", "client_access_token", ",", "page", "=", "None", ")", ":", "payload", "=", "{", "'grant_type'", ":", "'client_credentials'", ",", "'client_id'", ":", "client_id", ",", "'client_secret'", ":", "client_secret", ",", "}", "if", "client_access_token", ":", "payload", "[", "'grant_type'", "]", "=", "'fb_exchange_token'", "payload", "[", "'fb_exchange_token'", "]", "=", "client_access_token", "# response {\"access_token\":\" ... \", \"token_type\":\"bearer\", \"expires_in\":..}", "response", "=", "requests", ".", "post", "(", "'https://graph.facebook.com/oauth/access_token?'", ",", "params", "=", "payload", ")", "access_token", "=", "response", ".", "json", "(", ")", "[", "'access_token'", "]", "return", "access_token" ]
5a9067d3c1ae46eeccb9d36e8c231ea5224b42b4
test
get_page_api
You can also skip the above if you get a page token: http://stackoverflow.com/questions/8231877 and make that long-lived token as in Step 3
comdev/facebook_api.py
def get_page_api(client_access_token, page_id): """ You can also skip the above if you get a page token: http://stackoverflow.com/questions/8231877 and make that long-lived token as in Step 3 """ graph = GraphAPI(client_access_token) # Get page token to post as the page. You can skip # the following if you want to post as yourself. resp = graph.get('me/accounts') page_access_token = None for page in resp['data']: if page['id'] == page_id: page_access_token = page['access_token'] break return GraphAPI(page_access_token)
def get_page_api(client_access_token, page_id): """ You can also skip the above if you get a page token: http://stackoverflow.com/questions/8231877 and make that long-lived token as in Step 3 """ graph = GraphAPI(client_access_token) # Get page token to post as the page. You can skip # the following if you want to post as yourself. resp = graph.get('me/accounts') page_access_token = None for page in resp['data']: if page['id'] == page_id: page_access_token = page['access_token'] break return GraphAPI(page_access_token)
[ "You", "can", "also", "skip", "the", "above", "if", "you", "get", "a", "page", "token", ":", "http", ":", "//", "stackoverflow", ".", "com", "/", "questions", "/", "8231877", "and", "make", "that", "long", "-", "lived", "token", "as", "in", "Step", "3" ]
kejbaly2/comdev
python
https://github.com/kejbaly2/comdev/blob/5a9067d3c1ae46eeccb9d36e8c231ea5224b42b4/comdev/facebook_api.py#L41-L58
[ "def", "get_page_api", "(", "client_access_token", ",", "page_id", ")", ":", "graph", "=", "GraphAPI", "(", "client_access_token", ")", "# Get page token to post as the page. You can skip", "# the following if you want to post as yourself.", "resp", "=", "graph", ".", "get", "(", "'me/accounts'", ")", "page_access_token", "=", "None", "for", "page", "in", "resp", "[", "'data'", "]", ":", "if", "page", "[", "'id'", "]", "==", "page_id", ":", "page_access_token", "=", "page", "[", "'access_token'", "]", "break", "return", "GraphAPI", "(", "page_access_token", ")" ]
5a9067d3c1ae46eeccb9d36e8c231ea5224b42b4
test
serialize_value
Serialize a value from an xtuml metamodel instance.
xtuml/persist.py
def serialize_value(value, ty): ''' Serialize a value from an xtuml metamodel instance. ''' ty = ty.upper() null_value = { 'BOOLEAN' : False, 'INTEGER' : 0, 'REAL' : 0.0, 'STRING' : '', 'UNIQUE_ID' : 0 } transfer_fn = { 'BOOLEAN' : lambda v: '%d' % int(v), 'INTEGER' : lambda v: '%d' % v, 'REAL' : lambda v: '%f' % v, 'STRING' : lambda v: "'%s'" % v.replace("'", "''"), 'UNIQUE_ID' : lambda v: '"%s"' % uuid.UUID(int=v) } if value is None: value = null_value[ty] return transfer_fn[ty](value)
def serialize_value(value, ty): ''' Serialize a value from an xtuml metamodel instance. ''' ty = ty.upper() null_value = { 'BOOLEAN' : False, 'INTEGER' : 0, 'REAL' : 0.0, 'STRING' : '', 'UNIQUE_ID' : 0 } transfer_fn = { 'BOOLEAN' : lambda v: '%d' % int(v), 'INTEGER' : lambda v: '%d' % v, 'REAL' : lambda v: '%f' % v, 'STRING' : lambda v: "'%s'" % v.replace("'", "''"), 'UNIQUE_ID' : lambda v: '"%s"' % uuid.UUID(int=v) } if value is None: value = null_value[ty] return transfer_fn[ty](value)
[ "Serialize", "a", "value", "from", "an", "xtuml", "metamodel", "instance", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/persist.py#L32-L57
[ "def", "serialize_value", "(", "value", ",", "ty", ")", ":", "ty", "=", "ty", ".", "upper", "(", ")", "null_value", "=", "{", "'BOOLEAN'", ":", "False", ",", "'INTEGER'", ":", "0", ",", "'REAL'", ":", "0.0", ",", "'STRING'", ":", "''", ",", "'UNIQUE_ID'", ":", "0", "}", "transfer_fn", "=", "{", "'BOOLEAN'", ":", "lambda", "v", ":", "'%d'", "%", "int", "(", "v", ")", ",", "'INTEGER'", ":", "lambda", "v", ":", "'%d'", "%", "v", ",", "'REAL'", ":", "lambda", "v", ":", "'%f'", "%", "v", ",", "'STRING'", ":", "lambda", "v", ":", "\"'%s'\"", "%", "v", ".", "replace", "(", "\"'\"", ",", "\"''\"", ")", ",", "'UNIQUE_ID'", ":", "lambda", "v", ":", "'\"%s\"'", "%", "uuid", ".", "UUID", "(", "int", "=", "v", ")", "}", "if", "value", "is", "None", ":", "value", "=", "null_value", "[", "ty", "]", "return", "transfer_fn", "[", "ty", "]", "(", "value", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
serialize_instance
Serialize an *instance* from a metamodel.
xtuml/persist.py
def serialize_instance(instance): ''' Serialize an *instance* from a metamodel. ''' attr_count = 0 metaclass = xtuml.get_metaclass(instance) s = 'INSERT INTO %s VALUES (' % metaclass.kind for name, ty in metaclass.attributes: value = getattr(instance, name) s += '\n ' s += serialize_value(value, ty) attr_count += 1 if attr_count < len(metaclass.attributes): s += ', -- %s : %s' % (name, ty) else: s += ' -- %s : %s' % (name, ty) s += '\n);\n' return s
def serialize_instance(instance): ''' Serialize an *instance* from a metamodel. ''' attr_count = 0 metaclass = xtuml.get_metaclass(instance) s = 'INSERT INTO %s VALUES (' % metaclass.kind for name, ty in metaclass.attributes: value = getattr(instance, name) s += '\n ' s += serialize_value(value, ty) attr_count += 1 if attr_count < len(metaclass.attributes): s += ', -- %s : %s' % (name, ty) else: s += ' -- %s : %s' % (name, ty) s += '\n);\n' return s
[ "Serialize", "an", "*", "instance", "*", "from", "a", "metamodel", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/persist.py#L60-L81
[ "def", "serialize_instance", "(", "instance", ")", ":", "attr_count", "=", "0", "metaclass", "=", "xtuml", ".", "get_metaclass", "(", "instance", ")", "s", "=", "'INSERT INTO %s VALUES ('", "%", "metaclass", ".", "kind", "for", "name", ",", "ty", "in", "metaclass", ".", "attributes", ":", "value", "=", "getattr", "(", "instance", ",", "name", ")", "s", "+=", "'\\n '", "s", "+=", "serialize_value", "(", "value", ",", "ty", ")", "attr_count", "+=", "1", "if", "attr_count", "<", "len", "(", "metaclass", ".", "attributes", ")", ":", "s", "+=", "', -- %s : %s'", "%", "(", "name", ",", "ty", ")", "else", ":", "s", "+=", "' -- %s : %s'", "%", "(", "name", ",", "ty", ")", "s", "+=", "'\\n);\\n'", "return", "s" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
serialize_instances
Serialize all instances in a *metamodel*.
xtuml/persist.py
def serialize_instances(metamodel): ''' Serialize all instances in a *metamodel*. ''' s = '' for inst in metamodel.instances: s += serialize_instance(inst) return s
def serialize_instances(metamodel): ''' Serialize all instances in a *metamodel*. ''' s = '' for inst in metamodel.instances: s += serialize_instance(inst) return s
[ "Serialize", "all", "instances", "in", "a", "*", "metamodel", "*", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/persist.py#L84-L92
[ "def", "serialize_instances", "(", "metamodel", ")", ":", "s", "=", "''", "for", "inst", "in", "metamodel", ".", "instances", ":", "s", "+=", "serialize_instance", "(", "inst", ")", "return", "s" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
serialize_association
Serialize an xtuml metamodel association.
xtuml/persist.py
def serialize_association(ass): ''' Serialize an xtuml metamodel association. ''' s1 = '%s %s (%s)' % (ass.source_link.cardinality, ass.source_link.to_metaclass.kind, ', '.join(ass.source_keys)) if ass.target_link.phrase: s1 += " PHRASE '%s'" % ass.target_link.phrase s2 = '%s %s (%s)' % (ass.target_link.cardinality, ass.target_link.to_metaclass.kind, ', '.join(ass.target_keys)) if ass.source_link.phrase: s2 += " PHRASE '%s'" % ass.source_link.phrase return 'CREATE ROP REF_ID %s FROM %s TO %s;\n' % (ass.rel_id, s1, s2)
def serialize_association(ass): ''' Serialize an xtuml metamodel association. ''' s1 = '%s %s (%s)' % (ass.source_link.cardinality, ass.source_link.to_metaclass.kind, ', '.join(ass.source_keys)) if ass.target_link.phrase: s1 += " PHRASE '%s'" % ass.target_link.phrase s2 = '%s %s (%s)' % (ass.target_link.cardinality, ass.target_link.to_metaclass.kind, ', '.join(ass.target_keys)) if ass.source_link.phrase: s2 += " PHRASE '%s'" % ass.source_link.phrase return 'CREATE ROP REF_ID %s FROM %s TO %s;\n' % (ass.rel_id, s1, s2)
[ "Serialize", "an", "xtuml", "metamodel", "association", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/persist.py#L95-L115
[ "def", "serialize_association", "(", "ass", ")", ":", "s1", "=", "'%s %s (%s)'", "%", "(", "ass", ".", "source_link", ".", "cardinality", ",", "ass", ".", "source_link", ".", "to_metaclass", ".", "kind", ",", "', '", ".", "join", "(", "ass", ".", "source_keys", ")", ")", "if", "ass", ".", "target_link", ".", "phrase", ":", "s1", "+=", "\" PHRASE '%s'\"", "%", "ass", ".", "target_link", ".", "phrase", "s2", "=", "'%s %s (%s)'", "%", "(", "ass", ".", "target_link", ".", "cardinality", ",", "ass", ".", "target_link", ".", "to_metaclass", ".", "kind", ",", "', '", ".", "join", "(", "ass", ".", "target_keys", ")", ")", "if", "ass", ".", "source_link", ".", "phrase", ":", "s2", "+=", "\" PHRASE '%s'\"", "%", "ass", ".", "source_link", ".", "phrase", "return", "'CREATE ROP REF_ID %s FROM %s TO %s;\\n'", "%", "(", "ass", ".", "rel_id", ",", "s1", ",", "s2", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
serialize_class
Serialize an xtUML metamodel class.
xtuml/persist.py
def serialize_class(Cls): ''' Serialize an xtUML metamodel class. ''' metaclass = xtuml.get_metaclass(Cls) attributes = ['%s %s' % (name, ty.upper()) for name, ty in metaclass.attributes] s = 'CREATE TABLE %s (\n ' % metaclass.kind s += ',\n '.join(attributes) s += '\n);\n' return s
def serialize_class(Cls): ''' Serialize an xtUML metamodel class. ''' metaclass = xtuml.get_metaclass(Cls) attributes = ['%s %s' % (name, ty.upper()) for name, ty in metaclass.attributes] s = 'CREATE TABLE %s (\n ' % metaclass.kind s += ',\n '.join(attributes) s += '\n);\n' return s
[ "Serialize", "an", "xtUML", "metamodel", "class", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/persist.py#L118-L129
[ "def", "serialize_class", "(", "Cls", ")", ":", "metaclass", "=", "xtuml", ".", "get_metaclass", "(", "Cls", ")", "attributes", "=", "[", "'%s %s'", "%", "(", "name", ",", "ty", ".", "upper", "(", ")", ")", "for", "name", ",", "ty", "in", "metaclass", ".", "attributes", "]", "s", "=", "'CREATE TABLE %s (\\n '", "%", "metaclass", ".", "kind", "s", "+=", "',\\n '", ".", "join", "(", "attributes", ")", "s", "+=", "'\\n);\\n'", "return", "s" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
serialize_schema
Serialize all class and association definitions in a *metamodel*.
xtuml/persist.py
def serialize_schema(metamodel): ''' Serialize all class and association definitions in a *metamodel*. ''' s = '' for kind in sorted(metamodel.metaclasses.keys()): s += serialize_class(metamodel.metaclasses[kind].clazz) for ass in sorted(metamodel.associations, key=lambda x: x.rel_id): s += serialize_association(ass) return s
def serialize_schema(metamodel): ''' Serialize all class and association definitions in a *metamodel*. ''' s = '' for kind in sorted(metamodel.metaclasses.keys()): s += serialize_class(metamodel.metaclasses[kind].clazz) for ass in sorted(metamodel.associations, key=lambda x: x.rel_id): s += serialize_association(ass) return s
[ "Serialize", "all", "class", "and", "association", "definitions", "in", "a", "*", "metamodel", "*", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/persist.py#L142-L153
[ "def", "serialize_schema", "(", "metamodel", ")", ":", "s", "=", "''", "for", "kind", "in", "sorted", "(", "metamodel", ".", "metaclasses", ".", "keys", "(", ")", ")", ":", "s", "+=", "serialize_class", "(", "metamodel", ".", "metaclasses", "[", "kind", "]", ".", "clazz", ")", "for", "ass", "in", "sorted", "(", "metamodel", ".", "associations", ",", "key", "=", "lambda", "x", ":", "x", ".", "rel_id", ")", ":", "s", "+=", "serialize_association", "(", "ass", ")", "return", "s" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
serialize_database
Serialize all instances, class definitions, association definitions, and unique identifiers in a *metamodel*.
xtuml/persist.py
def serialize_database(metamodel): ''' Serialize all instances, class definitions, association definitions, and unique identifiers in a *metamodel*. ''' schema = serialize_schema(metamodel) instances = serialize_instances(metamodel) identifiers = serialize_unique_identifiers(metamodel) return ''.join([schema, instances, identifiers])
def serialize_database(metamodel): ''' Serialize all instances, class definitions, association definitions, and unique identifiers in a *metamodel*. ''' schema = serialize_schema(metamodel) instances = serialize_instances(metamodel) identifiers = serialize_unique_identifiers(metamodel) return ''.join([schema, instances, identifiers])
[ "Serialize", "all", "instances", "class", "definitions", "association", "definitions", "and", "unique", "identifiers", "in", "a", "*", "metamodel", "*", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/persist.py#L156-L165
[ "def", "serialize_database", "(", "metamodel", ")", ":", "schema", "=", "serialize_schema", "(", "metamodel", ")", "instances", "=", "serialize_instances", "(", "metamodel", ")", "identifiers", "=", "serialize_unique_identifiers", "(", "metamodel", ")", "return", "''", ".", "join", "(", "[", "schema", ",", "instances", ",", "identifiers", "]", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
serialize
Serialize some xtuml *resource*, e.g. an instance or a complete metamodel.
xtuml/persist.py
def serialize(resource): ''' Serialize some xtuml *resource*, e.g. an instance or a complete metamodel. ''' if isinstance(resource, xtuml.MetaModel): return serialize_database(resource) elif isinstance(resource, type) and issubclass(resource, xtuml.Class): return serialize_class(resource) elif isinstance(resource, xtuml.Association): return serialize_association(resource) elif isinstance(resource, xtuml.Class): return serialize_instance(resource)
def serialize(resource): ''' Serialize some xtuml *resource*, e.g. an instance or a complete metamodel. ''' if isinstance(resource, xtuml.MetaModel): return serialize_database(resource) elif isinstance(resource, type) and issubclass(resource, xtuml.Class): return serialize_class(resource) elif isinstance(resource, xtuml.Association): return serialize_association(resource) elif isinstance(resource, xtuml.Class): return serialize_instance(resource)
[ "Serialize", "some", "xtuml", "*", "resource", "*", "e", ".", "g", ".", "an", "instance", "or", "a", "complete", "metamodel", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/persist.py#L168-L182
[ "def", "serialize", "(", "resource", ")", ":", "if", "isinstance", "(", "resource", ",", "xtuml", ".", "MetaModel", ")", ":", "return", "serialize_database", "(", "resource", ")", "elif", "isinstance", "(", "resource", ",", "type", ")", "and", "issubclass", "(", "resource", ",", "xtuml", ".", "Class", ")", ":", "return", "serialize_class", "(", "resource", ")", "elif", "isinstance", "(", "resource", ",", "xtuml", ".", "Association", ")", ":", "return", "serialize_association", "(", "resource", ")", "elif", "isinstance", "(", "resource", ",", "xtuml", ".", "Class", ")", ":", "return", "serialize_instance", "(", "resource", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
persist_instances
Persist all instances in a *metamodel* by serializing them and saving to a *path* on disk.
xtuml/persist.py
def persist_instances(metamodel, path, mode='w'): ''' Persist all instances in a *metamodel* by serializing them and saving to a *path* on disk. ''' with open(path, mode) as f: for inst in metamodel.instances: s = serialize_instance(inst) f.write(s)
def persist_instances(metamodel, path, mode='w'): ''' Persist all instances in a *metamodel* by serializing them and saving to a *path* on disk. ''' with open(path, mode) as f: for inst in metamodel.instances: s = serialize_instance(inst) f.write(s)
[ "Persist", "all", "instances", "in", "a", "*", "metamodel", "*", "by", "serializing", "them", "and", "saving", "to", "a", "*", "path", "*", "on", "disk", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/persist.py#L185-L193
[ "def", "persist_instances", "(", "metamodel", ",", "path", ",", "mode", "=", "'w'", ")", ":", "with", "open", "(", "path", ",", "mode", ")", "as", "f", ":", "for", "inst", "in", "metamodel", ".", "instances", ":", "s", "=", "serialize_instance", "(", "inst", ")", "f", ".", "write", "(", "s", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
persist_schema
Persist all class and association definitions in a *metamodel* by serializing them and saving to a *path* on disk.
xtuml/persist.py
def persist_schema(metamodel, path, mode='w'): ''' Persist all class and association definitions in a *metamodel* by serializing them and saving to a *path* on disk. ''' with open(path, mode) as f: for kind in sorted(metamodel.metaclasses.keys()): s = serialize_class(metamodel.metaclasses[kind].clazz) f.write(s) for ass in sorted(metamodel.associations, key=lambda x: x.rel_id): s = serialize_association(ass) f.write(s)
def persist_schema(metamodel, path, mode='w'): ''' Persist all class and association definitions in a *metamodel* by serializing them and saving to a *path* on disk. ''' with open(path, mode) as f: for kind in sorted(metamodel.metaclasses.keys()): s = serialize_class(metamodel.metaclasses[kind].clazz) f.write(s) for ass in sorted(metamodel.associations, key=lambda x: x.rel_id): s = serialize_association(ass) f.write(s)
[ "Persist", "all", "class", "and", "association", "definitions", "in", "a", "*", "metamodel", "*", "by", "serializing", "them", "and", "saving", "to", "a", "*", "path", "*", "on", "disk", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/persist.py#L196-L208
[ "def", "persist_schema", "(", "metamodel", ",", "path", ",", "mode", "=", "'w'", ")", ":", "with", "open", "(", "path", ",", "mode", ")", "as", "f", ":", "for", "kind", "in", "sorted", "(", "metamodel", ".", "metaclasses", ".", "keys", "(", ")", ")", ":", "s", "=", "serialize_class", "(", "metamodel", ".", "metaclasses", "[", "kind", "]", ".", "clazz", ")", "f", ".", "write", "(", "s", ")", "for", "ass", "in", "sorted", "(", "metamodel", ".", "associations", ",", "key", "=", "lambda", "x", ":", "x", ".", "rel_id", ")", ":", "s", "=", "serialize_association", "(", "ass", ")", "f", ".", "write", "(", "s", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
persist_unique_identifiers
Persist all unique identifiers in a *metamodel* by serializing them and saving to a *path* on disk.
xtuml/persist.py
def persist_unique_identifiers(metamodel, path, mode='w'): ''' Persist all unique identifiers in a *metamodel* by serializing them and saving to a *path* on disk. ''' with open(path, mode) as f: for metaclass in metamodel.metaclasses.values(): for index_name, attribute_names in metaclass.indices.items(): attribute_names = ', '.join(attribute_names) s = 'CREATE UNIQUE INDEX %s ON %s (%s);\n' % (index_name, metaclass.kind, attribute_names) f.write(s)
def persist_unique_identifiers(metamodel, path, mode='w'): ''' Persist all unique identifiers in a *metamodel* by serializing them and saving to a *path* on disk. ''' with open(path, mode) as f: for metaclass in metamodel.metaclasses.values(): for index_name, attribute_names in metaclass.indices.items(): attribute_names = ', '.join(attribute_names) s = 'CREATE UNIQUE INDEX %s ON %s (%s);\n' % (index_name, metaclass.kind, attribute_names) f.write(s)
[ "Persist", "all", "unique", "identifiers", "in", "a", "*", "metamodel", "*", "by", "serializing", "them", "and", "saving", "to", "a", "*", "path", "*", "on", "disk", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/persist.py#L211-L223
[ "def", "persist_unique_identifiers", "(", "metamodel", ",", "path", ",", "mode", "=", "'w'", ")", ":", "with", "open", "(", "path", ",", "mode", ")", "as", "f", ":", "for", "metaclass", "in", "metamodel", ".", "metaclasses", ".", "values", "(", ")", ":", "for", "index_name", ",", "attribute_names", "in", "metaclass", ".", "indices", ".", "items", "(", ")", ":", "attribute_names", "=", "', '", ".", "join", "(", "attribute_names", ")", "s", "=", "'CREATE UNIQUE INDEX %s ON %s (%s);\\n'", "%", "(", "index_name", ",", "metaclass", ".", "kind", ",", "attribute_names", ")", "f", ".", "write", "(", "s", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
persist_database
Persist all instances, class definitions and association definitions in a *metamodel* by serializing them and saving to a *path* on disk.
xtuml/persist.py
def persist_database(metamodel, path, mode='w'): ''' Persist all instances, class definitions and association definitions in a *metamodel* by serializing them and saving to a *path* on disk. ''' with open(path, mode) as f: for kind in sorted(metamodel.metaclasses.keys()): metaclass = metamodel.metaclasses[kind] s = serialize_class(metaclass.clazz) f.write(s) for index_name, attribute_names in metaclass.indices.items(): attribute_names = ', '.join(attribute_names) s = 'CREATE UNIQUE INDEX %s ON %s (%s);\n' % (index_name, metaclass.kind, attribute_names) f.write(s) for ass in sorted(metamodel.associations, key=lambda x: x.rel_id): s = serialize_association(ass) f.write(s) for inst in metamodel.instances: s = serialize_instance(inst) f.write(s)
def persist_database(metamodel, path, mode='w'): ''' Persist all instances, class definitions and association definitions in a *metamodel* by serializing them and saving to a *path* on disk. ''' with open(path, mode) as f: for kind in sorted(metamodel.metaclasses.keys()): metaclass = metamodel.metaclasses[kind] s = serialize_class(metaclass.clazz) f.write(s) for index_name, attribute_names in metaclass.indices.items(): attribute_names = ', '.join(attribute_names) s = 'CREATE UNIQUE INDEX %s ON %s (%s);\n' % (index_name, metaclass.kind, attribute_names) f.write(s) for ass in sorted(metamodel.associations, key=lambda x: x.rel_id): s = serialize_association(ass) f.write(s) for inst in metamodel.instances: s = serialize_instance(inst) f.write(s)
[ "Persist", "all", "instances", "class", "definitions", "and", "association", "definitions", "in", "a", "*", "metamodel", "*", "by", "serializing", "them", "and", "saving", "to", "a", "*", "path", "*", "on", "disk", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/persist.py#L226-L250
[ "def", "persist_database", "(", "metamodel", ",", "path", ",", "mode", "=", "'w'", ")", ":", "with", "open", "(", "path", ",", "mode", ")", "as", "f", ":", "for", "kind", "in", "sorted", "(", "metamodel", ".", "metaclasses", ".", "keys", "(", ")", ")", ":", "metaclass", "=", "metamodel", ".", "metaclasses", "[", "kind", "]", "s", "=", "serialize_class", "(", "metaclass", ".", "clazz", ")", "f", ".", "write", "(", "s", ")", "for", "index_name", ",", "attribute_names", "in", "metaclass", ".", "indices", ".", "items", "(", ")", ":", "attribute_names", "=", "', '", ".", "join", "(", "attribute_names", ")", "s", "=", "'CREATE UNIQUE INDEX %s ON %s (%s);\\n'", "%", "(", "index_name", ",", "metaclass", ".", "kind", ",", "attribute_names", ")", "f", ".", "write", "(", "s", ")", "for", "ass", "in", "sorted", "(", "metamodel", ".", "associations", ",", "key", "=", "lambda", "x", ":", "x", ".", "rel_id", ")", ":", "s", "=", "serialize_association", "(", "ass", ")", "f", ".", "write", "(", "s", ")", "for", "inst", "in", "metamodel", ".", "instances", ":", "s", "=", "serialize_instance", "(", "inst", ")", "f", ".", "write", "(", "s", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
save
Save variable on given path using Pickle Args: variable: what to save path (str): path of the output
trovotutto/__init__.py
def save(variable, filename): """Save variable on given path using Pickle Args: variable: what to save path (str): path of the output """ fileObj = open(filename, 'wb') pickle.dump(variable, fileObj) fileObj.close()
def save(variable, filename): """Save variable on given path using Pickle Args: variable: what to save path (str): path of the output """ fileObj = open(filename, 'wb') pickle.dump(variable, fileObj) fileObj.close()
[ "Save", "variable", "on", "given", "path", "using", "Pickle", "Args", ":", "variable", ":", "what", "to", "save", "path", "(", "str", ")", ":", "path", "of", "the", "output" ]
tallero/trovotutto
python
https://github.com/tallero/trovotutto/blob/7afcfacf2bb3b642654153630c1ab7447ab10fae/trovotutto/__init__.py#L45-L54
[ "def", "save", "(", "variable", ",", "filename", ")", ":", "fileObj", "=", "open", "(", "filename", ",", "'wb'", ")", "pickle", ".", "dump", "(", "variable", ",", "fileObj", ")", "fileObj", ".", "close", "(", ")" ]
7afcfacf2bb3b642654153630c1ab7447ab10fae
test
load
Load variable from Pickle file Args: path (str): path of the file to load Returns: variable read from path
trovotutto/__init__.py
def load(filename): """Load variable from Pickle file Args: path (str): path of the file to load Returns: variable read from path """ fileObj = open(filename, 'rb') variable = pickle.load(fileObj) fileObj.close() return variable
def load(filename): """Load variable from Pickle file Args: path (str): path of the file to load Returns: variable read from path """ fileObj = open(filename, 'rb') variable = pickle.load(fileObj) fileObj.close() return variable
[ "Load", "variable", "from", "Pickle", "file", "Args", ":", "path", "(", "str", ")", ":", "path", "of", "the", "file", "to", "load" ]
tallero/trovotutto
python
https://github.com/tallero/trovotutto/blob/7afcfacf2bb3b642654153630c1ab7447ab10fae/trovotutto/__init__.py#L56-L68
[ "def", "load", "(", "filename", ")", ":", "fileObj", "=", "open", "(", "filename", ",", "'rb'", ")", "variable", "=", "pickle", ".", "load", "(", "fileObj", ")", "fileObj", ".", "close", "(", ")", "return", "variable" ]
7afcfacf2bb3b642654153630c1ab7447ab10fae
test
main
Function for command line execution
trovotutto/__init__.py
def main(): """Function for command line execution""" parser = ArgumentParser(description="search files using n-grams") parser.add_argument('--path', dest='path', help="where to search", nargs=1, action="store", default=getcwd()) parser.add_argument('--update', dest='update', help="update the index", action='store_true', default=True) parser.add_argument('--filetype', dest='filetype', help="any, images, documents, code, audio, video", nargs=1, action="store", default=["any"]) parser.add_argument('--verbose', dest='verbose', help="extended output", action='store_true', default=False) parser.add_argument('--results', dest='results', help="number of results to display", action="store", default=10) parser.add_argument('query', nargs='+', help="what to search", action="store") args = parser.parse_args() if args.verbose: verbose = 2 pprint(args) else: verbose = 0 query = args.query[0] for arg in args.query[1:]: query = query + " " + arg slb = min([len(w) for w in query.split(" ")]) files = Files(path=args.path, filetype=args.filetype[0], exclude=[], update=args.update, verbose=verbose) index = Index(files, slb=slb, verbose=verbose) results = index.search(query, verbose=verbose) Handler(results, results_number=int(args.results))
def main(): """Function for command line execution""" parser = ArgumentParser(description="search files using n-grams") parser.add_argument('--path', dest='path', help="where to search", nargs=1, action="store", default=getcwd()) parser.add_argument('--update', dest='update', help="update the index", action='store_true', default=True) parser.add_argument('--filetype', dest='filetype', help="any, images, documents, code, audio, video", nargs=1, action="store", default=["any"]) parser.add_argument('--verbose', dest='verbose', help="extended output", action='store_true', default=False) parser.add_argument('--results', dest='results', help="number of results to display", action="store", default=10) parser.add_argument('query', nargs='+', help="what to search", action="store") args = parser.parse_args() if args.verbose: verbose = 2 pprint(args) else: verbose = 0 query = args.query[0] for arg in args.query[1:]: query = query + " " + arg slb = min([len(w) for w in query.split(" ")]) files = Files(path=args.path, filetype=args.filetype[0], exclude=[], update=args.update, verbose=verbose) index = Index(files, slb=slb, verbose=verbose) results = index.search(query, verbose=verbose) Handler(results, results_number=int(args.results))
[ "Function", "for", "command", "line", "execution" ]
tallero/trovotutto
python
https://github.com/tallero/trovotutto/blob/7afcfacf2bb3b642654153630c1ab7447ab10fae/trovotutto/__init__.py#L247-L273
[ "def", "main", "(", ")", ":", "parser", "=", "ArgumentParser", "(", "description", "=", "\"search files using n-grams\"", ")", "parser", ".", "add_argument", "(", "'--path'", ",", "dest", "=", "'path'", ",", "help", "=", "\"where to search\"", ",", "nargs", "=", "1", ",", "action", "=", "\"store\"", ",", "default", "=", "getcwd", "(", ")", ")", "parser", ".", "add_argument", "(", "'--update'", ",", "dest", "=", "'update'", ",", "help", "=", "\"update the index\"", ",", "action", "=", "'store_true'", ",", "default", "=", "True", ")", "parser", ".", "add_argument", "(", "'--filetype'", ",", "dest", "=", "'filetype'", ",", "help", "=", "\"any, images, documents, code, audio, video\"", ",", "nargs", "=", "1", ",", "action", "=", "\"store\"", ",", "default", "=", "[", "\"any\"", "]", ")", "parser", ".", "add_argument", "(", "'--verbose'", ",", "dest", "=", "'verbose'", ",", "help", "=", "\"extended output\"", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ")", "parser", ".", "add_argument", "(", "'--results'", ",", "dest", "=", "'results'", ",", "help", "=", "\"number of results to display\"", ",", "action", "=", "\"store\"", ",", "default", "=", "10", ")", "parser", ".", "add_argument", "(", "'query'", ",", "nargs", "=", "'+'", ",", "help", "=", "\"what to search\"", ",", "action", "=", "\"store\"", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "if", "args", ".", "verbose", ":", "verbose", "=", "2", "pprint", "(", "args", ")", "else", ":", "verbose", "=", "0", "query", "=", "args", ".", "query", "[", "0", "]", "for", "arg", "in", "args", ".", "query", "[", "1", ":", "]", ":", "query", "=", "query", "+", "\" \"", "+", "arg", "slb", "=", "min", "(", "[", "len", "(", "w", ")", "for", "w", "in", "query", ".", "split", "(", "\" \"", ")", "]", ")", "files", "=", "Files", "(", "path", "=", "args", ".", "path", ",", "filetype", "=", "args", ".", "filetype", "[", "0", "]", ",", "exclude", "=", "[", "]", ",", "update", "=", "args", ".", "update", ",", "verbose", "=", "verbose", ")", "index", "=", "Index", "(", "files", ",", "slb", "=", "slb", ",", "verbose", "=", "verbose", ")", "results", "=", "index", ".", "search", "(", "query", ",", "verbose", "=", "verbose", ")", "Handler", "(", "results", ",", "results_number", "=", "int", "(", "args", ".", "results", ")", ")" ]
7afcfacf2bb3b642654153630c1ab7447ab10fae
test
Index.search
Searches files satisfying query It first decompose the query in ngrams, then score each document containing at least one ngram with the number. The ten document having the most ngrams in common with the query are selected. Args: query (str): what to search; results_number (int): number of results to return (default: 10)
trovotutto/__init__.py
def search(self, query, verbose=0): """Searches files satisfying query It first decompose the query in ngrams, then score each document containing at least one ngram with the number. The ten document having the most ngrams in common with the query are selected. Args: query (str): what to search; results_number (int): number of results to return (default: 10) """ if verbose > 0: print("searching " + query) query = query.lower() qgram = ng(query, self.slb) qocument = set() for q in qgram: if q in self.ngrams.keys(): for i in self.ngrams[q]: qocument.add(i) self.qocument = qocument results = {} for i in qocument: for j in self.D[i].keys(): if not j in results.keys(): results[j] = 0 results[j] = results[j] + self.D[i][j] sorted_results = sorted(results.items(), key=operator.itemgetter(1), reverse=True) return [self.elements[f[0]] for f in sorted_results]
def search(self, query, verbose=0): """Searches files satisfying query It first decompose the query in ngrams, then score each document containing at least one ngram with the number. The ten document having the most ngrams in common with the query are selected. Args: query (str): what to search; results_number (int): number of results to return (default: 10) """ if verbose > 0: print("searching " + query) query = query.lower() qgram = ng(query, self.slb) qocument = set() for q in qgram: if q in self.ngrams.keys(): for i in self.ngrams[q]: qocument.add(i) self.qocument = qocument results = {} for i in qocument: for j in self.D[i].keys(): if not j in results.keys(): results[j] = 0 results[j] = results[j] + self.D[i][j] sorted_results = sorted(results.items(), key=operator.itemgetter(1), reverse=True) return [self.elements[f[0]] for f in sorted_results]
[ "Searches", "files", "satisfying", "query" ]
tallero/trovotutto
python
https://github.com/tallero/trovotutto/blob/7afcfacf2bb3b642654153630c1ab7447ab10fae/trovotutto/__init__.py#L201-L229
[ "def", "search", "(", "self", ",", "query", ",", "verbose", "=", "0", ")", ":", "if", "verbose", ">", "0", ":", "print", "(", "\"searching \"", "+", "query", ")", "query", "=", "query", ".", "lower", "(", ")", "qgram", "=", "ng", "(", "query", ",", "self", ".", "slb", ")", "qocument", "=", "set", "(", ")", "for", "q", "in", "qgram", ":", "if", "q", "in", "self", ".", "ngrams", ".", "keys", "(", ")", ":", "for", "i", "in", "self", ".", "ngrams", "[", "q", "]", ":", "qocument", ".", "add", "(", "i", ")", "self", ".", "qocument", "=", "qocument", "results", "=", "{", "}", "for", "i", "in", "qocument", ":", "for", "j", "in", "self", ".", "D", "[", "i", "]", ".", "keys", "(", ")", ":", "if", "not", "j", "in", "results", ".", "keys", "(", ")", ":", "results", "[", "j", "]", "=", "0", "results", "[", "j", "]", "=", "results", "[", "j", "]", "+", "self", ".", "D", "[", "i", "]", "[", "j", "]", "sorted_results", "=", "sorted", "(", "results", ".", "items", "(", ")", ",", "key", "=", "operator", ".", "itemgetter", "(", "1", ")", ",", "reverse", "=", "True", ")", "return", "[", "self", ".", "elements", "[", "f", "[", "0", "]", "]", "for", "f", "in", "sorted_results", "]" ]
7afcfacf2bb3b642654153630c1ab7447ab10fae
test
partition
Partitions a list into two based on a condition.
hyperion/cli/__init__.py
def partition(condition, collection) -> Tuple[List, List]: """Partitions a list into two based on a condition.""" succeed, fail = [], [] for x in collection: if condition(x): succeed.append(x) else: fail.append(x) return succeed, fail
def partition(condition, collection) -> Tuple[List, List]: """Partitions a list into two based on a condition.""" succeed, fail = [], [] for x in collection: if condition(x): succeed.append(x) else: fail.append(x) return succeed, fail
[ "Partitions", "a", "list", "into", "two", "based", "on", "a", "condition", "." ]
arlyon/hyperion
python
https://github.com/arlyon/hyperion/blob/d8de0388ba98b85ce472e0f49ac18fecb14d3343/hyperion/cli/__init__.py#L19-L29
[ "def", "partition", "(", "condition", ",", "collection", ")", "->", "Tuple", "[", "List", ",", "List", "]", ":", "succeed", ",", "fail", "=", "[", "]", ",", "[", "]", "for", "x", "in", "collection", ":", "if", "condition", "(", "x", ")", ":", "succeed", ".", "append", "(", "x", ")", "else", ":", "fail", ".", "append", "(", "x", ")", "return", "succeed", ",", "fail" ]
d8de0388ba98b85ce472e0f49ac18fecb14d3343
test
cli
Runs the CLI app. Tries to execute as many steps as possible to give the user the best understanding of the errors (if there are any). :param location_strings: A list of desired postcodes or coordinates. :param random_postcodes_count: A number of random postcodes to fetch.. :param bikes: A flag to include bikes. :param crime: A flag to include crime. :param nearby: A flag to include nearby. :param as_json: A flag to make json output.
hyperion/cli/__init__.py
async def cli(location_strings: Tuple[str], random_postcodes_count: int, *, bikes: bool = False, crime: bool = False, nearby: bool = False, as_json: bool = False): """ Runs the CLI app. Tries to execute as many steps as possible to give the user the best understanding of the errors (if there are any). :param location_strings: A list of desired postcodes or coordinates. :param random_postcodes_count: A number of random postcodes to fetch.. :param bikes: A flag to include bikes. :param crime: A flag to include crime. :param nearby: A flag to include nearby. :param as_json: A flag to make json output. """ def match_getter(location) -> Optional[PostcodeGetter]: for getter in getters: if getter.can_provide(location): return getter(location) else: return None async def handle_getter(exception_list, getter): try: return await getter.get_postcodes() except (CachingError, ApiError): exception_list.append(f"Could not get data for {getter}") async def handle_datas(exception_list, postcode): postcode_data, new_exceptions = await get_postcode_data(postcode, bikes, crime, nearby) exception_list += new_exceptions return postcode_data exception_list: List[Exception] = [] handle_getter = partial(handle_getter, exception_list) handle_datas = partial(handle_datas, exception_list) postcode_getters = {location: match_getter(location) for location in set(location_strings) | ({random_postcodes_count} if random_postcodes_count > 0 else set())} matched, unmatched = partition(lambda k_v: k_v[1] is not None, postcode_getters.items()) for location, getter in unmatched: echo(f"Invalid input for {location}") postcodes_collection = [await handle_getter(getter) for location, getter in matched] if len(exception_list) > 0: for f in exception_list: echo(str(f)) return 1 postcode_datas = [await handle_datas(postcode) for entry in postcodes_collection for postcode in entry] serializer = (PostcodeSerializerJSON if as_json else PostcodeSerializerHuman)(postcode_datas) echo(serializer.serialize())
async def cli(location_strings: Tuple[str], random_postcodes_count: int, *, bikes: bool = False, crime: bool = False, nearby: bool = False, as_json: bool = False): """ Runs the CLI app. Tries to execute as many steps as possible to give the user the best understanding of the errors (if there are any). :param location_strings: A list of desired postcodes or coordinates. :param random_postcodes_count: A number of random postcodes to fetch.. :param bikes: A flag to include bikes. :param crime: A flag to include crime. :param nearby: A flag to include nearby. :param as_json: A flag to make json output. """ def match_getter(location) -> Optional[PostcodeGetter]: for getter in getters: if getter.can_provide(location): return getter(location) else: return None async def handle_getter(exception_list, getter): try: return await getter.get_postcodes() except (CachingError, ApiError): exception_list.append(f"Could not get data for {getter}") async def handle_datas(exception_list, postcode): postcode_data, new_exceptions = await get_postcode_data(postcode, bikes, crime, nearby) exception_list += new_exceptions return postcode_data exception_list: List[Exception] = [] handle_getter = partial(handle_getter, exception_list) handle_datas = partial(handle_datas, exception_list) postcode_getters = {location: match_getter(location) for location in set(location_strings) | ({random_postcodes_count} if random_postcodes_count > 0 else set())} matched, unmatched = partition(lambda k_v: k_v[1] is not None, postcode_getters.items()) for location, getter in unmatched: echo(f"Invalid input for {location}") postcodes_collection = [await handle_getter(getter) for location, getter in matched] if len(exception_list) > 0: for f in exception_list: echo(str(f)) return 1 postcode_datas = [await handle_datas(postcode) for entry in postcodes_collection for postcode in entry] serializer = (PostcodeSerializerJSON if as_json else PostcodeSerializerHuman)(postcode_datas) echo(serializer.serialize())
[ "Runs", "the", "CLI", "app", ".", "Tries", "to", "execute", "as", "many", "steps", "as", "possible", "to", "give", "the", "user", "the", "best", "understanding", "of", "the", "errors", "(", "if", "there", "are", "any", ")", "." ]
arlyon/hyperion
python
https://github.com/arlyon/hyperion/blob/d8de0388ba98b85ce472e0f49ac18fecb14d3343/hyperion/cli/__init__.py#L32-L88
[ "async", "def", "cli", "(", "location_strings", ":", "Tuple", "[", "str", "]", ",", "random_postcodes_count", ":", "int", ",", "*", ",", "bikes", ":", "bool", "=", "False", ",", "crime", ":", "bool", "=", "False", ",", "nearby", ":", "bool", "=", "False", ",", "as_json", ":", "bool", "=", "False", ")", ":", "def", "match_getter", "(", "location", ")", "->", "Optional", "[", "PostcodeGetter", "]", ":", "for", "getter", "in", "getters", ":", "if", "getter", ".", "can_provide", "(", "location", ")", ":", "return", "getter", "(", "location", ")", "else", ":", "return", "None", "async", "def", "handle_getter", "(", "exception_list", ",", "getter", ")", ":", "try", ":", "return", "await", "getter", ".", "get_postcodes", "(", ")", "except", "(", "CachingError", ",", "ApiError", ")", ":", "exception_list", ".", "append", "(", "f\"Could not get data for {getter}\"", ")", "async", "def", "handle_datas", "(", "exception_list", ",", "postcode", ")", ":", "postcode_data", ",", "new_exceptions", "=", "await", "get_postcode_data", "(", "postcode", ",", "bikes", ",", "crime", ",", "nearby", ")", "exception_list", "+=", "new_exceptions", "return", "postcode_data", "exception_list", ":", "List", "[", "Exception", "]", "=", "[", "]", "handle_getter", "=", "partial", "(", "handle_getter", ",", "exception_list", ")", "handle_datas", "=", "partial", "(", "handle_datas", ",", "exception_list", ")", "postcode_getters", "=", "{", "location", ":", "match_getter", "(", "location", ")", "for", "location", "in", "set", "(", "location_strings", ")", "|", "(", "{", "random_postcodes_count", "}", "if", "random_postcodes_count", ">", "0", "else", "set", "(", ")", ")", "}", "matched", ",", "unmatched", "=", "partition", "(", "lambda", "k_v", ":", "k_v", "[", "1", "]", "is", "not", "None", ",", "postcode_getters", ".", "items", "(", ")", ")", "for", "location", ",", "getter", "in", "unmatched", ":", "echo", "(", "f\"Invalid input for {location}\"", ")", "postcodes_collection", "=", "[", "await", "handle_getter", "(", "getter", ")", "for", "location", ",", "getter", "in", "matched", "]", "if", "len", "(", "exception_list", ")", ">", "0", ":", "for", "f", "in", "exception_list", ":", "echo", "(", "str", "(", "f", ")", ")", "return", "1", "postcode_datas", "=", "[", "await", "handle_datas", "(", "postcode", ")", "for", "entry", "in", "postcodes_collection", "for", "postcode", "in", "entry", "]", "serializer", "=", "(", "PostcodeSerializerJSON", "if", "as_json", "else", "PostcodeSerializerHuman", ")", "(", "postcode_datas", ")", "echo", "(", "serializer", ".", "serialize", "(", ")", ")" ]
d8de0388ba98b85ce472e0f49ac18fecb14d3343
test
fetch_neighbourhood
Gets the neighbourhood from the fetch that is associated with the given postcode. :return: A neighbourhood object parsed from the fetch. :raise ApiError: When there was an error connecting to the API.
hyperion/fetch/police.py
async def fetch_neighbourhood(lat: float, long: float) -> Optional[dict]: """ Gets the neighbourhood from the fetch that is associated with the given postcode. :return: A neighbourhood object parsed from the fetch. :raise ApiError: When there was an error connecting to the API. """ lookup_url = f"https://data.police.uk/api/locate-neighbourhood?q={lat},{long}" async with ClientSession() as session: try: async with session.get(lookup_url) as request: if request.status == 404: return None neighbourhood = await request.json() except ClientConnectionError as con_err: logger.debug(f"Could not connect to {con_err.host}") raise ApiError(f"Could not connect to {con_err.host}") except JSONDecodeError as dec_err: logger.error(f"Could not decode data: {dec_err}") raise ApiError(f"Could not decode data: {dec_err}") neighbourhood_url = f"https://data.police.uk/api/{neighbourhood['force']}/{neighbourhood['neighbourhood']}" try: async with session.get(neighbourhood_url) as request: neighbourhood_data = await request.json() except ConnectionError as con_err: logger.debug(f"Could not connect to {con_err.args[0].pool.host}") raise ApiError(f"Could not connect to {con_err.args[0].pool.host}") except JSONDecodeError as dec_err: logger.error(f"Could not decode data: {dec_err}") raise ApiError(f"Could not decode data: {dec_err}") return neighbourhood_data
async def fetch_neighbourhood(lat: float, long: float) -> Optional[dict]: """ Gets the neighbourhood from the fetch that is associated with the given postcode. :return: A neighbourhood object parsed from the fetch. :raise ApiError: When there was an error connecting to the API. """ lookup_url = f"https://data.police.uk/api/locate-neighbourhood?q={lat},{long}" async with ClientSession() as session: try: async with session.get(lookup_url) as request: if request.status == 404: return None neighbourhood = await request.json() except ClientConnectionError as con_err: logger.debug(f"Could not connect to {con_err.host}") raise ApiError(f"Could not connect to {con_err.host}") except JSONDecodeError as dec_err: logger.error(f"Could not decode data: {dec_err}") raise ApiError(f"Could not decode data: {dec_err}") neighbourhood_url = f"https://data.police.uk/api/{neighbourhood['force']}/{neighbourhood['neighbourhood']}" try: async with session.get(neighbourhood_url) as request: neighbourhood_data = await request.json() except ConnectionError as con_err: logger.debug(f"Could not connect to {con_err.args[0].pool.host}") raise ApiError(f"Could not connect to {con_err.args[0].pool.host}") except JSONDecodeError as dec_err: logger.error(f"Could not decode data: {dec_err}") raise ApiError(f"Could not decode data: {dec_err}") return neighbourhood_data
[ "Gets", "the", "neighbourhood", "from", "the", "fetch", "that", "is", "associated", "with", "the", "given", "postcode", ".", ":", "return", ":", "A", "neighbourhood", "object", "parsed", "from", "the", "fetch", ".", ":", "raise", "ApiError", ":", "When", "there", "was", "an", "error", "connecting", "to", "the", "API", "." ]
arlyon/hyperion
python
https://github.com/arlyon/hyperion/blob/d8de0388ba98b85ce472e0f49ac18fecb14d3343/hyperion/fetch/police.py#L15-L49
[ "async", "def", "fetch_neighbourhood", "(", "lat", ":", "float", ",", "long", ":", "float", ")", "->", "Optional", "[", "dict", "]", ":", "lookup_url", "=", "f\"https://data.police.uk/api/locate-neighbourhood?q={lat},{long}\"", "async", "with", "ClientSession", "(", ")", "as", "session", ":", "try", ":", "async", "with", "session", ".", "get", "(", "lookup_url", ")", "as", "request", ":", "if", "request", ".", "status", "==", "404", ":", "return", "None", "neighbourhood", "=", "await", "request", ".", "json", "(", ")", "except", "ClientConnectionError", "as", "con_err", ":", "logger", ".", "debug", "(", "f\"Could not connect to {con_err.host}\"", ")", "raise", "ApiError", "(", "f\"Could not connect to {con_err.host}\"", ")", "except", "JSONDecodeError", "as", "dec_err", ":", "logger", ".", "error", "(", "f\"Could not decode data: {dec_err}\"", ")", "raise", "ApiError", "(", "f\"Could not decode data: {dec_err}\"", ")", "neighbourhood_url", "=", "f\"https://data.police.uk/api/{neighbourhood['force']}/{neighbourhood['neighbourhood']}\"", "try", ":", "async", "with", "session", ".", "get", "(", "neighbourhood_url", ")", "as", "request", ":", "neighbourhood_data", "=", "await", "request", ".", "json", "(", ")", "except", "ConnectionError", "as", "con_err", ":", "logger", ".", "debug", "(", "f\"Could not connect to {con_err.args[0].pool.host}\"", ")", "raise", "ApiError", "(", "f\"Could not connect to {con_err.args[0].pool.host}\"", ")", "except", "JSONDecodeError", "as", "dec_err", ":", "logger", ".", "error", "(", "f\"Could not decode data: {dec_err}\"", ")", "raise", "ApiError", "(", "f\"Could not decode data: {dec_err}\"", ")", "return", "neighbourhood_data" ]
d8de0388ba98b85ce472e0f49ac18fecb14d3343
test
fetch_crime
Gets crime for a given lat and long. :raise ApiError: When there was an error connecting to the API. todo cache
hyperion/fetch/police.py
async def fetch_crime(lat: float, long: float) -> List[Dict]: """ Gets crime for a given lat and long. :raise ApiError: When there was an error connecting to the API. todo cache """ crime_lookup = f"https://data.police.uk/api/crimes-street/all-crime?lat={lat}&lng={long}" async with ClientSession() as session: try: async with session.get(crime_lookup) as request: crime_request = await request.json() except ClientConnectionError as con_err: logger.debug(f"Could not connect to {con_err.args[0].pool.host}") raise ApiError(f"Could not connect to {con_err.args[0].pool.host}") except JSONDecodeError as dec_err: logger.error(f"Could not decode data: {dec_err}") raise ApiError(f"Could not decode data: {dec_err}") else: return crime_request
async def fetch_crime(lat: float, long: float) -> List[Dict]: """ Gets crime for a given lat and long. :raise ApiError: When there was an error connecting to the API. todo cache """ crime_lookup = f"https://data.police.uk/api/crimes-street/all-crime?lat={lat}&lng={long}" async with ClientSession() as session: try: async with session.get(crime_lookup) as request: crime_request = await request.json() except ClientConnectionError as con_err: logger.debug(f"Could not connect to {con_err.args[0].pool.host}") raise ApiError(f"Could not connect to {con_err.args[0].pool.host}") except JSONDecodeError as dec_err: logger.error(f"Could not decode data: {dec_err}") raise ApiError(f"Could not decode data: {dec_err}") else: return crime_request
[ "Gets", "crime", "for", "a", "given", "lat", "and", "long", ".", ":", "raise", "ApiError", ":", "When", "there", "was", "an", "error", "connecting", "to", "the", "API", "." ]
arlyon/hyperion
python
https://github.com/arlyon/hyperion/blob/d8de0388ba98b85ce472e0f49ac18fecb14d3343/hyperion/fetch/police.py#L53-L72
[ "async", "def", "fetch_crime", "(", "lat", ":", "float", ",", "long", ":", "float", ")", "->", "List", "[", "Dict", "]", ":", "crime_lookup", "=", "f\"https://data.police.uk/api/crimes-street/all-crime?lat={lat}&lng={long}\"", "async", "with", "ClientSession", "(", ")", "as", "session", ":", "try", ":", "async", "with", "session", ".", "get", "(", "crime_lookup", ")", "as", "request", ":", "crime_request", "=", "await", "request", ".", "json", "(", ")", "except", "ClientConnectionError", "as", "con_err", ":", "logger", ".", "debug", "(", "f\"Could not connect to {con_err.args[0].pool.host}\"", ")", "raise", "ApiError", "(", "f\"Could not connect to {con_err.args[0].pool.host}\"", ")", "except", "JSONDecodeError", "as", "dec_err", ":", "logger", ".", "error", "(", "f\"Could not decode data: {dec_err}\"", ")", "raise", "ApiError", "(", "f\"Could not decode data: {dec_err}\"", ")", "else", ":", "return", "crime_request" ]
d8de0388ba98b85ce472e0f49ac18fecb14d3343
test
run
Runs the program. Takes a list of postcodes or coordinates and returns various information about them. If using the cli, make sure to update the bikes database with the -u command. Locations can be either a specific postcode, or a pair of coordinates. Coordinates are passed in the form "55.948824,-3.196425". :param locations: The list of postcodes or coordinates to search. :param random: The number of random postcodes to include. :param bikes: Includes a list of stolen bikes in that area. :param crime: Includes a list of committed crimes in that area. :param nearby: Includes a list of wikipedia articles in that area. :param json: Returns the data in json format. :param update_bikes: Whether to force update bikes. :param api_server: If given, the program will instead run a rest api. :param cross_origin: :param host: :param port: Defines the port to run the rest api on. :param db_path: The path to the sqlite db to use. :param verbose: The verbosity.
hyperion/__main__.py
def run(locations, random, bikes, crime, nearby, json, update_bikes, api_server, cross_origin, host, port, db_path, verbose): """ Runs the program. Takes a list of postcodes or coordinates and returns various information about them. If using the cli, make sure to update the bikes database with the -u command. Locations can be either a specific postcode, or a pair of coordinates. Coordinates are passed in the form "55.948824,-3.196425". :param locations: The list of postcodes or coordinates to search. :param random: The number of random postcodes to include. :param bikes: Includes a list of stolen bikes in that area. :param crime: Includes a list of committed crimes in that area. :param nearby: Includes a list of wikipedia articles in that area. :param json: Returns the data in json format. :param update_bikes: Whether to force update bikes. :param api_server: If given, the program will instead run a rest api. :param cross_origin: :param host: :param port: Defines the port to run the rest api on. :param db_path: The path to the sqlite db to use. :param verbose: The verbosity. """ log_levels = [logging.WARNING, logging.INFO, logging.DEBUG] logging.basicConfig(level=log_levels[min(verbose, 2)]) initialize_database(db_path) loop = get_event_loop() if update_bikes: logger.info("Force updating bikes.") loop.run_until_complete(util.update_bikes()) if api_server: if cross_origin: enable_cross_origin(app) try: web.run_app(app, host=host, port=port) except CancelledError as e: if e.__context__ is not None: click.echo(Fore.RED + ( f"Could not bind to address {host}:{port}" if e.__context__.errno == 48 else e.__context__)) exit(1) else: click.echo("Goodbye!") elif len(locations) > 0 or random > 0: exit(loop.run_until_complete(cli(locations, random, bikes=bikes, crime=crime, nearby=nearby, as_json=json))) else: click.echo(Fore.RED + "Either include a post code, or the --api-server flag.")
def run(locations, random, bikes, crime, nearby, json, update_bikes, api_server, cross_origin, host, port, db_path, verbose): """ Runs the program. Takes a list of postcodes or coordinates and returns various information about them. If using the cli, make sure to update the bikes database with the -u command. Locations can be either a specific postcode, or a pair of coordinates. Coordinates are passed in the form "55.948824,-3.196425". :param locations: The list of postcodes or coordinates to search. :param random: The number of random postcodes to include. :param bikes: Includes a list of stolen bikes in that area. :param crime: Includes a list of committed crimes in that area. :param nearby: Includes a list of wikipedia articles in that area. :param json: Returns the data in json format. :param update_bikes: Whether to force update bikes. :param api_server: If given, the program will instead run a rest api. :param cross_origin: :param host: :param port: Defines the port to run the rest api on. :param db_path: The path to the sqlite db to use. :param verbose: The verbosity. """ log_levels = [logging.WARNING, logging.INFO, logging.DEBUG] logging.basicConfig(level=log_levels[min(verbose, 2)]) initialize_database(db_path) loop = get_event_loop() if update_bikes: logger.info("Force updating bikes.") loop.run_until_complete(util.update_bikes()) if api_server: if cross_origin: enable_cross_origin(app) try: web.run_app(app, host=host, port=port) except CancelledError as e: if e.__context__ is not None: click.echo(Fore.RED + ( f"Could not bind to address {host}:{port}" if e.__context__.errno == 48 else e.__context__)) exit(1) else: click.echo("Goodbye!") elif len(locations) > 0 or random > 0: exit(loop.run_until_complete(cli(locations, random, bikes=bikes, crime=crime, nearby=nearby, as_json=json))) else: click.echo(Fore.RED + "Either include a post code, or the --api-server flag.")
[ "Runs", "the", "program", ".", "Takes", "a", "list", "of", "postcodes", "or", "coordinates", "and", "returns", "various", "information", "about", "them", ".", "If", "using", "the", "cli", "make", "sure", "to", "update", "the", "bikes", "database", "with", "the", "-", "u", "command", "." ]
arlyon/hyperion
python
https://github.com/arlyon/hyperion/blob/d8de0388ba98b85ce472e0f49ac18fecb14d3343/hyperion/__main__.py#L37-L90
[ "def", "run", "(", "locations", ",", "random", ",", "bikes", ",", "crime", ",", "nearby", ",", "json", ",", "update_bikes", ",", "api_server", ",", "cross_origin", ",", "host", ",", "port", ",", "db_path", ",", "verbose", ")", ":", "log_levels", "=", "[", "logging", ".", "WARNING", ",", "logging", ".", "INFO", ",", "logging", ".", "DEBUG", "]", "logging", ".", "basicConfig", "(", "level", "=", "log_levels", "[", "min", "(", "verbose", ",", "2", ")", "]", ")", "initialize_database", "(", "db_path", ")", "loop", "=", "get_event_loop", "(", ")", "if", "update_bikes", ":", "logger", ".", "info", "(", "\"Force updating bikes.\"", ")", "loop", ".", "run_until_complete", "(", "util", ".", "update_bikes", "(", ")", ")", "if", "api_server", ":", "if", "cross_origin", ":", "enable_cross_origin", "(", "app", ")", "try", ":", "web", ".", "run_app", "(", "app", ",", "host", "=", "host", ",", "port", "=", "port", ")", "except", "CancelledError", "as", "e", ":", "if", "e", ".", "__context__", "is", "not", "None", ":", "click", ".", "echo", "(", "Fore", ".", "RED", "+", "(", "f\"Could not bind to address {host}:{port}\"", "if", "e", ".", "__context__", ".", "errno", "==", "48", "else", "e", ".", "__context__", ")", ")", "exit", "(", "1", ")", "else", ":", "click", ".", "echo", "(", "\"Goodbye!\"", ")", "elif", "len", "(", "locations", ")", ">", "0", "or", "random", ">", "0", ":", "exit", "(", "loop", ".", "run_until_complete", "(", "cli", "(", "locations", ",", "random", ",", "bikes", "=", "bikes", ",", "crime", "=", "crime", ",", "nearby", "=", "nearby", ",", "as_json", "=", "json", ")", ")", ")", "else", ":", "click", ".", "echo", "(", "Fore", ".", "RED", "+", "\"Either include a post code, or the --api-server flag.\"", ")" ]
d8de0388ba98b85ce472e0f49ac18fecb14d3343
test
bidi
Adds to the context BiDi related variables LANGUAGE_DIRECTION -- Direction of current language ('ltr' or 'rtl') LANGUAGE_START -- Start of language layout ('right' for rtl, 'left' for 'ltr') LANGUAGE_END -- End of language layout ('left' for rtl, 'right' for 'ltr') LANGUAGE_MARKER -- Language marker entity ('&rlm;' for rtl, '&lrm' for ltr)
bidiutils/context_processors.py
def bidi(request): """Adds to the context BiDi related variables LANGUAGE_DIRECTION -- Direction of current language ('ltr' or 'rtl') LANGUAGE_START -- Start of language layout ('right' for rtl, 'left' for 'ltr') LANGUAGE_END -- End of language layout ('left' for rtl, 'right' for 'ltr') LANGUAGE_MARKER -- Language marker entity ('&rlm;' for rtl, '&lrm' for ltr) """ from django.utils import translation from django.utils.safestring import mark_safe if translation.get_language_bidi(): extra_context = { 'LANGUAGE_DIRECTION':'rtl', 'LANGUAGE_START':'right', 'LANGUAGE_END':'left', 'LANGUAGE_MARKER': mark_safe('&rlm;'), } else: extra_context = { 'LANGUAGE_DIRECTION':'ltr', 'LANGUAGE_START':'left', 'LANGUAGE_END':'right', 'LANGUAGE_MARKER': mark_safe('&lrm;'), } return extra_context
def bidi(request): """Adds to the context BiDi related variables LANGUAGE_DIRECTION -- Direction of current language ('ltr' or 'rtl') LANGUAGE_START -- Start of language layout ('right' for rtl, 'left' for 'ltr') LANGUAGE_END -- End of language layout ('left' for rtl, 'right' for 'ltr') LANGUAGE_MARKER -- Language marker entity ('&rlm;' for rtl, '&lrm' for ltr) """ from django.utils import translation from django.utils.safestring import mark_safe if translation.get_language_bidi(): extra_context = { 'LANGUAGE_DIRECTION':'rtl', 'LANGUAGE_START':'right', 'LANGUAGE_END':'left', 'LANGUAGE_MARKER': mark_safe('&rlm;'), } else: extra_context = { 'LANGUAGE_DIRECTION':'ltr', 'LANGUAGE_START':'left', 'LANGUAGE_END':'right', 'LANGUAGE_MARKER': mark_safe('&lrm;'), } return extra_context
[ "Adds", "to", "the", "context", "BiDi", "related", "variables" ]
MeirKriheli/django-bidi-utils
python
https://github.com/MeirKriheli/django-bidi-utils/blob/48a8c481fe728fbccf486582999e79454195036e/bidiutils/context_processors.py#L3-L33
[ "def", "bidi", "(", "request", ")", ":", "from", "django", ".", "utils", "import", "translation", "from", "django", ".", "utils", ".", "safestring", "import", "mark_safe", "if", "translation", ".", "get_language_bidi", "(", ")", ":", "extra_context", "=", "{", "'LANGUAGE_DIRECTION'", ":", "'rtl'", ",", "'LANGUAGE_START'", ":", "'right'", ",", "'LANGUAGE_END'", ":", "'left'", ",", "'LANGUAGE_MARKER'", ":", "mark_safe", "(", "'&rlm;'", ")", ",", "}", "else", ":", "extra_context", "=", "{", "'LANGUAGE_DIRECTION'", ":", "'ltr'", ",", "'LANGUAGE_START'", ":", "'left'", ",", "'LANGUAGE_END'", ":", "'right'", ",", "'LANGUAGE_MARKER'", ":", "mark_safe", "(", "'&lrm;'", ")", ",", "}", "return", "extra_context" ]
48a8c481fe728fbccf486582999e79454195036e
test
_is_null
Determine if an attribute of an *instance* with a specific *name* is null.
xtuml/meta.py
def _is_null(instance, name): ''' Determine if an attribute of an *instance* with a specific *name* is null. ''' if name in instance.__dict__: value = instance.__dict__[name] else: value = getattr(instance, name) if value: return False elif value is None: return True name = name.upper() metaclass = get_metaclass(instance) for attr_name, attr_ty in metaclass.attributes: if attr_name.upper() != name: continue attr_ty = attr_ty.upper() if attr_ty == 'UNIQUE_ID': # UUID(int=0) is reserved for null return value == 0 elif attr_ty == 'STRING': # empty string is reserved for null return len(value) == 0 else: #null-values for integer, boolean and real are not supported return False
def _is_null(instance, name): ''' Determine if an attribute of an *instance* with a specific *name* is null. ''' if name in instance.__dict__: value = instance.__dict__[name] else: value = getattr(instance, name) if value: return False elif value is None: return True name = name.upper() metaclass = get_metaclass(instance) for attr_name, attr_ty in metaclass.attributes: if attr_name.upper() != name: continue attr_ty = attr_ty.upper() if attr_ty == 'UNIQUE_ID': # UUID(int=0) is reserved for null return value == 0 elif attr_ty == 'STRING': # empty string is reserved for null return len(value) == 0 else: #null-values for integer, boolean and real are not supported return False
[ "Determine", "if", "an", "attribute", "of", "an", "*", "instance", "*", "with", "a", "specific", "*", "name", "*", "is", "null", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L100-L133
[ "def", "_is_null", "(", "instance", ",", "name", ")", ":", "if", "name", "in", "instance", ".", "__dict__", ":", "value", "=", "instance", ".", "__dict__", "[", "name", "]", "else", ":", "value", "=", "getattr", "(", "instance", ",", "name", ")", "if", "value", ":", "return", "False", "elif", "value", "is", "None", ":", "return", "True", "name", "=", "name", ".", "upper", "(", ")", "metaclass", "=", "get_metaclass", "(", "instance", ")", "for", "attr_name", ",", "attr_ty", "in", "metaclass", ".", "attributes", ":", "if", "attr_name", ".", "upper", "(", ")", "!=", "name", ":", "continue", "attr_ty", "=", "attr_ty", ".", "upper", "(", ")", "if", "attr_ty", "==", "'UNIQUE_ID'", ":", "# UUID(int=0) is reserved for null", "return", "value", "==", "0", "elif", "attr_ty", "==", "'STRING'", ":", "# empty string is reserved for null", "return", "len", "(", "value", ")", "==", "0", "else", ":", "#null-values for integer, boolean and real are not supported", "return", "False" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
apply_query_operators
Apply a series of query operators to a sequence of instances, e.g. where_eq(), order_by() or filter functions.
xtuml/meta.py
def apply_query_operators(iterable, ops): ''' Apply a series of query operators to a sequence of instances, e.g. where_eq(), order_by() or filter functions. ''' for op in ops: if isinstance(op, WhereEqual): iterable = op(iterable) elif isinstance(op, OrderBy): iterable = op(iterable) elif isinstance(op, dict): iterable = WhereEqual(op)(iterable) else: iterable = filter(op, iterable) return iterable
def apply_query_operators(iterable, ops): ''' Apply a series of query operators to a sequence of instances, e.g. where_eq(), order_by() or filter functions. ''' for op in ops: if isinstance(op, WhereEqual): iterable = op(iterable) elif isinstance(op, OrderBy): iterable = op(iterable) elif isinstance(op, dict): iterable = WhereEqual(op)(iterable) else: iterable = filter(op, iterable) return iterable
[ "Apply", "a", "series", "of", "query", "operators", "to", "a", "sequence", "of", "instances", "e", ".", "g", ".", "where_eq", "()", "order_by", "()", "or", "filter", "functions", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L136-L154
[ "def", "apply_query_operators", "(", "iterable", ",", "ops", ")", ":", "for", "op", "in", "ops", ":", "if", "isinstance", "(", "op", ",", "WhereEqual", ")", ":", "iterable", "=", "op", "(", "iterable", ")", "elif", "isinstance", "(", "op", ",", "OrderBy", ")", ":", "iterable", "=", "op", "(", "iterable", ")", "elif", "isinstance", "(", "op", ",", "dict", ")", ":", "iterable", "=", "WhereEqual", "(", "op", ")", "(", "iterable", ")", "else", ":", "iterable", "=", "filter", "(", "op", ",", "iterable", ")", "return", "iterable" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
navigate_subtype
Perform a navigation from *supertype* to its subtype across *rel_id*. The navigated association must be modeled as a subtype-supertype association. The return value will an instance or None.
xtuml/meta.py
def navigate_subtype(supertype, rel_id): ''' Perform a navigation from *supertype* to its subtype across *rel_id*. The navigated association must be modeled as a subtype-supertype association. The return value will an instance or None. ''' if not supertype: return if isinstance(rel_id, int): rel_id = 'R%d' % rel_id metaclass = get_metaclass(supertype) for kind, rel_id_candidate, _ in metaclass.links: if rel_id != rel_id_candidate: continue subtype = navigate_one(supertype).nav(kind, rel_id)() if subtype: return subtype
def navigate_subtype(supertype, rel_id): ''' Perform a navigation from *supertype* to its subtype across *rel_id*. The navigated association must be modeled as a subtype-supertype association. The return value will an instance or None. ''' if not supertype: return if isinstance(rel_id, int): rel_id = 'R%d' % rel_id metaclass = get_metaclass(supertype) for kind, rel_id_candidate, _ in metaclass.links: if rel_id != rel_id_candidate: continue subtype = navigate_one(supertype).nav(kind, rel_id)() if subtype: return subtype
[ "Perform", "a", "navigation", "from", "*", "supertype", "*", "to", "its", "subtype", "across", "*", "rel_id", "*", ".", "The", "navigated", "association", "must", "be", "modeled", "as", "a", "subtype", "-", "supertype", "association", ".", "The", "return", "value", "will", "an", "instance", "or", "None", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L857-L877
[ "def", "navigate_subtype", "(", "supertype", ",", "rel_id", ")", ":", "if", "not", "supertype", ":", "return", "if", "isinstance", "(", "rel_id", ",", "int", ")", ":", "rel_id", "=", "'R%d'", "%", "rel_id", "metaclass", "=", "get_metaclass", "(", "supertype", ")", "for", "kind", ",", "rel_id_candidate", ",", "_", "in", "metaclass", ".", "links", ":", "if", "rel_id", "!=", "rel_id_candidate", ":", "continue", "subtype", "=", "navigate_one", "(", "supertype", ")", ".", "nav", "(", "kind", ",", "rel_id", ")", "(", ")", "if", "subtype", ":", "return", "subtype" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
sort_reflexive
Sort a *set of instances* in the order they appear across a conditional and reflexive association. The first instance in the resulting ordered set is **not** associated to an instance across the given *phrase*.
xtuml/meta.py
def sort_reflexive(set_of_instances, rel_id, phrase): ''' Sort a *set of instances* in the order they appear across a conditional and reflexive association. The first instance in the resulting ordered set is **not** associated to an instance across the given *phrase*. ''' if not isinstance(set_of_instances, QuerySet): raise MetaException('The collection to sort must be a QuerySet') if not set_of_instances.first: return QuerySet() if isinstance(rel_id, int): rel_id = 'R%d' % rel_id # Figure out the phrase in the other direction metaclass = get_metaclass(set_of_instances.first) for link in metaclass.links.values(): if link.to_metaclass != metaclass: continue if link.rel_id != rel_id: continue if link.phrase == phrase: continue other_phrase = link.phrase break else: raise UnknownLinkException(metaclass.kind, metaclass.kind, rel_id, phrase) first_filt = lambda sel: not navigate_one(sel).nav(metaclass.kind, rel_id, phrase)() first_instances = list(filter(first_filt, set_of_instances)) if not first_instances: #the instance sequence is recursive, start anywhere first_instances = [set_of_instances.first] def sequence_generator(): for first in first_instances: inst = first while inst: if inst in set_of_instances: yield inst inst = navigate_one(inst).nav(metaclass.kind, rel_id, other_phrase)() if inst is first: break return QuerySet(sequence_generator())
def sort_reflexive(set_of_instances, rel_id, phrase): ''' Sort a *set of instances* in the order they appear across a conditional and reflexive association. The first instance in the resulting ordered set is **not** associated to an instance across the given *phrase*. ''' if not isinstance(set_of_instances, QuerySet): raise MetaException('The collection to sort must be a QuerySet') if not set_of_instances.first: return QuerySet() if isinstance(rel_id, int): rel_id = 'R%d' % rel_id # Figure out the phrase in the other direction metaclass = get_metaclass(set_of_instances.first) for link in metaclass.links.values(): if link.to_metaclass != metaclass: continue if link.rel_id != rel_id: continue if link.phrase == phrase: continue other_phrase = link.phrase break else: raise UnknownLinkException(metaclass.kind, metaclass.kind, rel_id, phrase) first_filt = lambda sel: not navigate_one(sel).nav(metaclass.kind, rel_id, phrase)() first_instances = list(filter(first_filt, set_of_instances)) if not first_instances: #the instance sequence is recursive, start anywhere first_instances = [set_of_instances.first] def sequence_generator(): for first in first_instances: inst = first while inst: if inst in set_of_instances: yield inst inst = navigate_one(inst).nav(metaclass.kind, rel_id, other_phrase)() if inst is first: break return QuerySet(sequence_generator())
[ "Sort", "a", "*", "set", "of", "instances", "*", "in", "the", "order", "they", "appear", "across", "a", "conditional", "and", "reflexive", "association", ".", "The", "first", "instance", "in", "the", "resulting", "ordered", "set", "is", "**", "not", "**", "associated", "to", "an", "instance", "across", "the", "given", "*", "phrase", "*", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L909-L957
[ "def", "sort_reflexive", "(", "set_of_instances", ",", "rel_id", ",", "phrase", ")", ":", "if", "not", "isinstance", "(", "set_of_instances", ",", "QuerySet", ")", ":", "raise", "MetaException", "(", "'The collection to sort must be a QuerySet'", ")", "if", "not", "set_of_instances", ".", "first", ":", "return", "QuerySet", "(", ")", "if", "isinstance", "(", "rel_id", ",", "int", ")", ":", "rel_id", "=", "'R%d'", "%", "rel_id", "# Figure out the phrase in the other direction", "metaclass", "=", "get_metaclass", "(", "set_of_instances", ".", "first", ")", "for", "link", "in", "metaclass", ".", "links", ".", "values", "(", ")", ":", "if", "link", ".", "to_metaclass", "!=", "metaclass", ":", "continue", "if", "link", ".", "rel_id", "!=", "rel_id", ":", "continue", "if", "link", ".", "phrase", "==", "phrase", ":", "continue", "other_phrase", "=", "link", ".", "phrase", "break", "else", ":", "raise", "UnknownLinkException", "(", "metaclass", ".", "kind", ",", "metaclass", ".", "kind", ",", "rel_id", ",", "phrase", ")", "first_filt", "=", "lambda", "sel", ":", "not", "navigate_one", "(", "sel", ")", ".", "nav", "(", "metaclass", ".", "kind", ",", "rel_id", ",", "phrase", ")", "(", ")", "first_instances", "=", "list", "(", "filter", "(", "first_filt", ",", "set_of_instances", ")", ")", "if", "not", "first_instances", ":", "#the instance sequence is recursive, start anywhere", "first_instances", "=", "[", "set_of_instances", ".", "first", "]", "def", "sequence_generator", "(", ")", ":", "for", "first", "in", "first_instances", ":", "inst", "=", "first", "while", "inst", ":", "if", "inst", "in", "set_of_instances", ":", "yield", "inst", "inst", "=", "navigate_one", "(", "inst", ")", ".", "nav", "(", "metaclass", ".", "kind", ",", "rel_id", ",", "other_phrase", ")", "(", ")", "if", "inst", "is", "first", ":", "break", "return", "QuerySet", "(", "sequence_generator", "(", ")", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
_find_link
Find links that correspond to the given arguments.
xtuml/meta.py
def _find_link(inst1, inst2, rel_id, phrase): ''' Find links that correspond to the given arguments. ''' metaclass1 = get_metaclass(inst1) metaclass2 = get_metaclass(inst2) if isinstance(rel_id, int): rel_id = 'R%d' % rel_id for ass in metaclass1.metamodel.associations: if ass.rel_id != rel_id: continue if (ass.source_link.from_metaclass.kind == metaclass1.kind and ass.source_link.to_metaclass.kind == metaclass2.kind and ass.source_link.phrase == phrase): return inst1, inst2, ass if (ass.target_link.from_metaclass.kind == metaclass1.kind and ass.target_link.to_metaclass.kind == metaclass2.kind and ass.target_link.phrase == phrase): return inst2, inst1, ass raise UnknownLinkException(metaclass1.kind, metaclass2.kind, rel_id, phrase)
def _find_link(inst1, inst2, rel_id, phrase): ''' Find links that correspond to the given arguments. ''' metaclass1 = get_metaclass(inst1) metaclass2 = get_metaclass(inst2) if isinstance(rel_id, int): rel_id = 'R%d' % rel_id for ass in metaclass1.metamodel.associations: if ass.rel_id != rel_id: continue if (ass.source_link.from_metaclass.kind == metaclass1.kind and ass.source_link.to_metaclass.kind == metaclass2.kind and ass.source_link.phrase == phrase): return inst1, inst2, ass if (ass.target_link.from_metaclass.kind == metaclass1.kind and ass.target_link.to_metaclass.kind == metaclass2.kind and ass.target_link.phrase == phrase): return inst2, inst1, ass raise UnknownLinkException(metaclass1.kind, metaclass2.kind, rel_id, phrase)
[ "Find", "links", "that", "correspond", "to", "the", "given", "arguments", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L960-L984
[ "def", "_find_link", "(", "inst1", ",", "inst2", ",", "rel_id", ",", "phrase", ")", ":", "metaclass1", "=", "get_metaclass", "(", "inst1", ")", "metaclass2", "=", "get_metaclass", "(", "inst2", ")", "if", "isinstance", "(", "rel_id", ",", "int", ")", ":", "rel_id", "=", "'R%d'", "%", "rel_id", "for", "ass", "in", "metaclass1", ".", "metamodel", ".", "associations", ":", "if", "ass", ".", "rel_id", "!=", "rel_id", ":", "continue", "if", "(", "ass", ".", "source_link", ".", "from_metaclass", ".", "kind", "==", "metaclass1", ".", "kind", "and", "ass", ".", "source_link", ".", "to_metaclass", ".", "kind", "==", "metaclass2", ".", "kind", "and", "ass", ".", "source_link", ".", "phrase", "==", "phrase", ")", ":", "return", "inst1", ",", "inst2", ",", "ass", "if", "(", "ass", ".", "target_link", ".", "from_metaclass", ".", "kind", "==", "metaclass1", ".", "kind", "and", "ass", ".", "target_link", ".", "to_metaclass", ".", "kind", "==", "metaclass2", ".", "kind", "and", "ass", ".", "target_link", ".", "phrase", "==", "phrase", ")", ":", "return", "inst2", ",", "inst1", ",", "ass", "raise", "UnknownLinkException", "(", "metaclass1", ".", "kind", ",", "metaclass2", ".", "kind", ",", "rel_id", ",", "phrase", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
relate
Relate *from_instance* to *to_instance* across *rel_id*. For reflexive association, a *phrase* indicating the direction must also be provided. The two instances are related to each other by copying the identifying attributes from the instance on the TO side of a association to the instance n the FROM side. Updated values which affect existing associations are propagated. A set of all affected instances will be returned.
xtuml/meta.py
def relate(from_instance, to_instance, rel_id, phrase=''): ''' Relate *from_instance* to *to_instance* across *rel_id*. For reflexive association, a *phrase* indicating the direction must also be provided. The two instances are related to each other by copying the identifying attributes from the instance on the TO side of a association to the instance n the FROM side. Updated values which affect existing associations are propagated. A set of all affected instances will be returned. ''' if None in [from_instance, to_instance]: return False inst1, inst2, ass = _find_link(from_instance, to_instance, rel_id, phrase) if not ass.source_link.connect(inst1, inst2): raise RelateException(from_instance, to_instance, rel_id, phrase) if not ass.target_link.connect(inst2, inst1): raise RelateException(from_instance, to_instance, rel_id, phrase) return True
def relate(from_instance, to_instance, rel_id, phrase=''): ''' Relate *from_instance* to *to_instance* across *rel_id*. For reflexive association, a *phrase* indicating the direction must also be provided. The two instances are related to each other by copying the identifying attributes from the instance on the TO side of a association to the instance n the FROM side. Updated values which affect existing associations are propagated. A set of all affected instances will be returned. ''' if None in [from_instance, to_instance]: return False inst1, inst2, ass = _find_link(from_instance, to_instance, rel_id, phrase) if not ass.source_link.connect(inst1, inst2): raise RelateException(from_instance, to_instance, rel_id, phrase) if not ass.target_link.connect(inst2, inst1): raise RelateException(from_instance, to_instance, rel_id, phrase) return True
[ "Relate", "*", "from_instance", "*", "to", "*", "to_instance", "*", "across", "*", "rel_id", "*", ".", "For", "reflexive", "association", "a", "*", "phrase", "*", "indicating", "the", "direction", "must", "also", "be", "provided", ".", "The", "two", "instances", "are", "related", "to", "each", "other", "by", "copying", "the", "identifying", "attributes", "from", "the", "instance", "on", "the", "TO", "side", "of", "a", "association", "to", "the", "instance", "n", "the", "FROM", "side", ".", "Updated", "values", "which", "affect", "existing", "associations", "are", "propagated", ".", "A", "set", "of", "all", "affected", "instances", "will", "be", "returned", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L987-L1007
[ "def", "relate", "(", "from_instance", ",", "to_instance", ",", "rel_id", ",", "phrase", "=", "''", ")", ":", "if", "None", "in", "[", "from_instance", ",", "to_instance", "]", ":", "return", "False", "inst1", ",", "inst2", ",", "ass", "=", "_find_link", "(", "from_instance", ",", "to_instance", ",", "rel_id", ",", "phrase", ")", "if", "not", "ass", ".", "source_link", ".", "connect", "(", "inst1", ",", "inst2", ")", ":", "raise", "RelateException", "(", "from_instance", ",", "to_instance", ",", "rel_id", ",", "phrase", ")", "if", "not", "ass", ".", "target_link", ".", "connect", "(", "inst2", ",", "inst1", ")", ":", "raise", "RelateException", "(", "from_instance", ",", "to_instance", ",", "rel_id", ",", "phrase", ")", "return", "True" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
unrelate
Unrelate *from_instance* from *to_instance* across *rel_id*. For reflexive associations, a *phrase* indicating the direction must also be provided. The two instances are unrelated from each other by reseting the identifying attributes on the FROM side of the association. Updated values which affect existing associations are propagated. A set of all affected instances will be returned.
xtuml/meta.py
def unrelate(from_instance, to_instance, rel_id, phrase=''): ''' Unrelate *from_instance* from *to_instance* across *rel_id*. For reflexive associations, a *phrase* indicating the direction must also be provided. The two instances are unrelated from each other by reseting the identifying attributes on the FROM side of the association. Updated values which affect existing associations are propagated. A set of all affected instances will be returned. ''' if None in [from_instance, to_instance]: return False inst1, inst2, ass = _find_link(from_instance, to_instance, rel_id, phrase) if not ass.source_link.disconnect(inst1, inst2): raise UnrelateException(from_instance, to_instance, rel_id, phrase) if not ass.target_link.disconnect(inst2, inst1): raise UnrelateException(from_instance, to_instance, rel_id, phrase) return True
def unrelate(from_instance, to_instance, rel_id, phrase=''): ''' Unrelate *from_instance* from *to_instance* across *rel_id*. For reflexive associations, a *phrase* indicating the direction must also be provided. The two instances are unrelated from each other by reseting the identifying attributes on the FROM side of the association. Updated values which affect existing associations are propagated. A set of all affected instances will be returned. ''' if None in [from_instance, to_instance]: return False inst1, inst2, ass = _find_link(from_instance, to_instance, rel_id, phrase) if not ass.source_link.disconnect(inst1, inst2): raise UnrelateException(from_instance, to_instance, rel_id, phrase) if not ass.target_link.disconnect(inst2, inst1): raise UnrelateException(from_instance, to_instance, rel_id, phrase) return True
[ "Unrelate", "*", "from_instance", "*", "from", "*", "to_instance", "*", "across", "*", "rel_id", "*", ".", "For", "reflexive", "associations", "a", "*", "phrase", "*", "indicating", "the", "direction", "must", "also", "be", "provided", ".", "The", "two", "instances", "are", "unrelated", "from", "each", "other", "by", "reseting", "the", "identifying", "attributes", "on", "the", "FROM", "side", "of", "the", "association", ".", "Updated", "values", "which", "affect", "existing", "associations", "are", "propagated", ".", "A", "set", "of", "all", "affected", "instances", "will", "be", "returned", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L1010-L1030
[ "def", "unrelate", "(", "from_instance", ",", "to_instance", ",", "rel_id", ",", "phrase", "=", "''", ")", ":", "if", "None", "in", "[", "from_instance", ",", "to_instance", "]", ":", "return", "False", "inst1", ",", "inst2", ",", "ass", "=", "_find_link", "(", "from_instance", ",", "to_instance", ",", "rel_id", ",", "phrase", ")", "if", "not", "ass", ".", "source_link", ".", "disconnect", "(", "inst1", ",", "inst2", ")", ":", "raise", "UnrelateException", "(", "from_instance", ",", "to_instance", ",", "rel_id", ",", "phrase", ")", "if", "not", "ass", ".", "target_link", ".", "disconnect", "(", "inst2", ",", "inst1", ")", ":", "raise", "UnrelateException", "(", "from_instance", ",", "to_instance", ",", "rel_id", ",", "phrase", ")", "return", "True" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
get_metaclass
Get the metaclass for a *class_or_instance*.
xtuml/meta.py
def get_metaclass(class_or_instance): ''' Get the metaclass for a *class_or_instance*. ''' if isinstance(class_or_instance, Class): return class_or_instance.__metaclass__ elif issubclass(class_or_instance, Class): return class_or_instance.__metaclass__ raise MetaException("the provided argument is not an xtuml class or instance")
def get_metaclass(class_or_instance): ''' Get the metaclass for a *class_or_instance*. ''' if isinstance(class_or_instance, Class): return class_or_instance.__metaclass__ elif issubclass(class_or_instance, Class): return class_or_instance.__metaclass__ raise MetaException("the provided argument is not an xtuml class or instance")
[ "Get", "the", "metaclass", "for", "a", "*", "class_or_instance", "*", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L1033-L1043
[ "def", "get_metaclass", "(", "class_or_instance", ")", ":", "if", "isinstance", "(", "class_or_instance", ",", "Class", ")", ":", "return", "class_or_instance", ".", "__metaclass__", "elif", "issubclass", "(", "class_or_instance", ",", "Class", ")", ":", "return", "class_or_instance", ".", "__metaclass__", "raise", "MetaException", "(", "\"the provided argument is not an xtuml class or instance\"", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
delete
Delete an *instance* from its metaclass instance pool and optionally *disconnect* it from any links it might be connected to.
xtuml/meta.py
def delete(instance, disconnect=True): ''' Delete an *instance* from its metaclass instance pool and optionally *disconnect* it from any links it might be connected to. ''' if not isinstance(instance, Class): raise DeleteException("the provided argument is not an xtuml instance") return get_metaclass(instance).delete(instance, disconnect)
def delete(instance, disconnect=True): ''' Delete an *instance* from its metaclass instance pool and optionally *disconnect* it from any links it might be connected to. ''' if not isinstance(instance, Class): raise DeleteException("the provided argument is not an xtuml instance") return get_metaclass(instance).delete(instance, disconnect)
[ "Delete", "an", "*", "instance", "*", "from", "its", "metaclass", "instance", "pool", "and", "optionally", "*", "disconnect", "*", "it", "from", "any", "links", "it", "might", "be", "connected", "to", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L1053-L1061
[ "def", "delete", "(", "instance", ",", "disconnect", "=", "True", ")", ":", "if", "not", "isinstance", "(", "instance", ",", "Class", ")", ":", "raise", "DeleteException", "(", "\"the provided argument is not an xtuml instance\"", ")", "return", "get_metaclass", "(", "instance", ")", ".", "delete", "(", "instance", ",", "disconnect", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
Association.formalize
Formalize the association and expose referential attributes on instances.
xtuml/meta.py
def formalize(self): ''' Formalize the association and expose referential attributes on instances. ''' source_class = self.source_link.to_metaclass target_class = self.target_link.to_metaclass source_class.referential_attributes |= set(self.source_keys) target_class.identifying_attributes |= set(self.target_keys) def fget(inst, ref_name, alt_prop): other_inst = self.target_link.navigate_one(inst) if other_inst is None and alt_prop: return alt_prop.fget(inst) return getattr(other_inst, ref_name, None) def fset(inst, value, name, ref_name, alt_prop): kind = get_metaclass(inst).kind raise MetaException('%s.%s is a referential attribute '\ 'and cannot be assigned directly'% (kind, name)) #other_inst = self.target_link.navigate_one(inst) #if other_inst is None and alt_prop: # return alt_prop.fset(inst, value) # #elif other_inst: # return setattr(other_inst, ref_name, value) for ref_key, primary_key in zip(self.source_keys, self.target_keys): prop = getattr(source_class.clazz, ref_key, None) prop = property(partial(fget, ref_name=primary_key, alt_prop=prop), partial(fset, name=ref_key, ref_name=primary_key, alt_prop=prop)) setattr(source_class.clazz, ref_key, prop)
def formalize(self): ''' Formalize the association and expose referential attributes on instances. ''' source_class = self.source_link.to_metaclass target_class = self.target_link.to_metaclass source_class.referential_attributes |= set(self.source_keys) target_class.identifying_attributes |= set(self.target_keys) def fget(inst, ref_name, alt_prop): other_inst = self.target_link.navigate_one(inst) if other_inst is None and alt_prop: return alt_prop.fget(inst) return getattr(other_inst, ref_name, None) def fset(inst, value, name, ref_name, alt_prop): kind = get_metaclass(inst).kind raise MetaException('%s.%s is a referential attribute '\ 'and cannot be assigned directly'% (kind, name)) #other_inst = self.target_link.navigate_one(inst) #if other_inst is None and alt_prop: # return alt_prop.fset(inst, value) # #elif other_inst: # return setattr(other_inst, ref_name, value) for ref_key, primary_key in zip(self.source_keys, self.target_keys): prop = getattr(source_class.clazz, ref_key, None) prop = property(partial(fget, ref_name=primary_key, alt_prop=prop), partial(fset, name=ref_key, ref_name=primary_key, alt_prop=prop)) setattr(source_class.clazz, ref_key, prop)
[ "Formalize", "the", "association", "and", "expose", "referential", "attributes", "on", "instances", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L204-L238
[ "def", "formalize", "(", "self", ")", ":", "source_class", "=", "self", ".", "source_link", ".", "to_metaclass", "target_class", "=", "self", ".", "target_link", ".", "to_metaclass", "source_class", ".", "referential_attributes", "|=", "set", "(", "self", ".", "source_keys", ")", "target_class", ".", "identifying_attributes", "|=", "set", "(", "self", ".", "target_keys", ")", "def", "fget", "(", "inst", ",", "ref_name", ",", "alt_prop", ")", ":", "other_inst", "=", "self", ".", "target_link", ".", "navigate_one", "(", "inst", ")", "if", "other_inst", "is", "None", "and", "alt_prop", ":", "return", "alt_prop", ".", "fget", "(", "inst", ")", "return", "getattr", "(", "other_inst", ",", "ref_name", ",", "None", ")", "def", "fset", "(", "inst", ",", "value", ",", "name", ",", "ref_name", ",", "alt_prop", ")", ":", "kind", "=", "get_metaclass", "(", "inst", ")", ".", "kind", "raise", "MetaException", "(", "'%s.%s is a referential attribute '", "'and cannot be assigned directly'", "%", "(", "kind", ",", "name", ")", ")", "#other_inst = self.target_link.navigate_one(inst)", "#if other_inst is None and alt_prop:", "# return alt_prop.fset(inst, value)", "#", "#elif other_inst:", "# return setattr(other_inst, ref_name, value)", "for", "ref_key", ",", "primary_key", "in", "zip", "(", "self", ".", "source_keys", ",", "self", ".", "target_keys", ")", ":", "prop", "=", "getattr", "(", "source_class", ".", "clazz", ",", "ref_key", ",", "None", ")", "prop", "=", "property", "(", "partial", "(", "fget", ",", "ref_name", "=", "primary_key", ",", "alt_prop", "=", "prop", ")", ",", "partial", "(", "fset", ",", "name", "=", "ref_key", ",", "ref_name", "=", "primary_key", ",", "alt_prop", "=", "prop", ")", ")", "setattr", "(", "source_class", ".", "clazz", ",", "ref_key", ",", "prop", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
Link.cardinality
Obtain the cardinality string. Example: '1C' for a conditional link with a single instance [0..1] 'MC' for a link with any number of instances [0..*] 'M' for a more than one instance [1..*] 'M' for a link with exactly one instance [1]
xtuml/meta.py
def cardinality(self): ''' Obtain the cardinality string. Example: '1C' for a conditional link with a single instance [0..1] 'MC' for a link with any number of instances [0..*] 'M' for a more than one instance [1..*] 'M' for a link with exactly one instance [1] ''' if self.many: s = 'M' else: s = '1' if self.conditional: s += 'C' return s
def cardinality(self): ''' Obtain the cardinality string. Example: '1C' for a conditional link with a single instance [0..1] 'MC' for a link with any number of instances [0..*] 'M' for a more than one instance [1..*] 'M' for a link with exactly one instance [1] ''' if self.many: s = 'M' else: s = '1' if self.conditional: s += 'C' return s
[ "Obtain", "the", "cardinality", "string", ".", "Example", ":", "1C", "for", "a", "conditional", "link", "with", "a", "single", "instance", "[", "0", "..", "1", "]", "MC", "for", "a", "link", "with", "any", "number", "of", "instances", "[", "0", "..", "*", "]", "M", "for", "a", "more", "than", "one", "instance", "[", "1", "..", "*", "]", "M", "for", "a", "link", "with", "exactly", "one", "instance", "[", "1", "]" ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L275-L292
[ "def", "cardinality", "(", "self", ")", ":", "if", "self", ".", "many", ":", "s", "=", "'M'", "else", ":", "s", "=", "'1'", "if", "self", ".", "conditional", ":", "s", "+=", "'C'", "return", "s" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
Link.connect
Connect an *instance* to *another_instance*. Optionally, disable any cardinality *check* that would prevent the two instances from being connected.
xtuml/meta.py
def connect(self, instance, another_instance, check=True): ''' Connect an *instance* to *another_instance*. Optionally, disable any cardinality *check* that would prevent the two instances from being connected. ''' if instance not in self: self[instance] = xtuml.OrderedSet() if another_instance in self[instance]: return True if self[instance] and not self.many and check: return False self[instance].add(another_instance) return True
def connect(self, instance, another_instance, check=True): ''' Connect an *instance* to *another_instance*. Optionally, disable any cardinality *check* that would prevent the two instances from being connected. ''' if instance not in self: self[instance] = xtuml.OrderedSet() if another_instance in self[instance]: return True if self[instance] and not self.many and check: return False self[instance].add(another_instance) return True
[ "Connect", "an", "*", "instance", "*", "to", "*", "another_instance", "*", ".", "Optionally", "disable", "any", "cardinality", "*", "check", "*", "that", "would", "prevent", "the", "two", "instances", "from", "being", "connected", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L301-L318
[ "def", "connect", "(", "self", ",", "instance", ",", "another_instance", ",", "check", "=", "True", ")", ":", "if", "instance", "not", "in", "self", ":", "self", "[", "instance", "]", "=", "xtuml", ".", "OrderedSet", "(", ")", "if", "another_instance", "in", "self", "[", "instance", "]", ":", "return", "True", "if", "self", "[", "instance", "]", "and", "not", "self", ".", "many", "and", "check", ":", "return", "False", "self", "[", "instance", "]", ".", "add", "(", "another_instance", ")", "return", "True" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
Link.disconnect
Disconnect an *instance* from *another_instance*.
xtuml/meta.py
def disconnect(self, instance, another_instance): ''' Disconnect an *instance* from *another_instance*. ''' if instance not in self: return False if another_instance not in self[instance]: return False self[instance].remove(another_instance) return True
def disconnect(self, instance, another_instance): ''' Disconnect an *instance* from *another_instance*. ''' if instance not in self: return False if another_instance not in self[instance]: return False self[instance].remove(another_instance) return True
[ "Disconnect", "an", "*", "instance", "*", "from", "*", "another_instance", "*", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L320-L331
[ "def", "disconnect", "(", "self", ",", "instance", ",", "another_instance", ")", ":", "if", "instance", "not", "in", "self", ":", "return", "False", "if", "another_instance", "not", "in", "self", "[", "instance", "]", ":", "return", "False", "self", "[", "instance", "]", ".", "remove", "(", "another_instance", ")", "return", "True" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
Link.compute_lookup_key
Compute the lookup key for an instance, i.e. a foreign key that can be used to identify an instance at the end of the link.
xtuml/meta.py
def compute_lookup_key(self, from_instance): ''' Compute the lookup key for an instance, i.e. a foreign key that can be used to identify an instance at the end of the link. ''' kwargs = dict() for attr, other_attr in self.key_map.items(): if _is_null(from_instance, attr): return None if attr in from_instance.__dict__: kwargs[other_attr] = from_instance.__dict__[attr] else: kwargs[other_attr] = getattr(from_instance, attr) return frozenset(tuple(kwargs.items()))
def compute_lookup_key(self, from_instance): ''' Compute the lookup key for an instance, i.e. a foreign key that can be used to identify an instance at the end of the link. ''' kwargs = dict() for attr, other_attr in self.key_map.items(): if _is_null(from_instance, attr): return None if attr in from_instance.__dict__: kwargs[other_attr] = from_instance.__dict__[attr] else: kwargs[other_attr] = getattr(from_instance, attr) return frozenset(tuple(kwargs.items()))
[ "Compute", "the", "lookup", "key", "for", "an", "instance", "i", ".", "e", ".", "a", "foreign", "key", "that", "can", "be", "used", "to", "identify", "an", "instance", "at", "the", "end", "of", "the", "link", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L348-L363
[ "def", "compute_lookup_key", "(", "self", ",", "from_instance", ")", ":", "kwargs", "=", "dict", "(", ")", "for", "attr", ",", "other_attr", "in", "self", ".", "key_map", ".", "items", "(", ")", ":", "if", "_is_null", "(", "from_instance", ",", "attr", ")", ":", "return", "None", "if", "attr", "in", "from_instance", ".", "__dict__", ":", "kwargs", "[", "other_attr", "]", "=", "from_instance", ".", "__dict__", "[", "attr", "]", "else", ":", "kwargs", "[", "other_attr", "]", "=", "getattr", "(", "from_instance", ",", "attr", ")", "return", "frozenset", "(", "tuple", "(", "kwargs", ".", "items", "(", ")", ")", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
Link.compute_index_key
Compute the index key that can be used to identify an instance on the link.
xtuml/meta.py
def compute_index_key(self, to_instance): ''' Compute the index key that can be used to identify an instance on the link. ''' kwargs = dict() for attr in self.key_map.values(): if _is_null(to_instance, attr): return None if attr in to_instance.__dict__: kwargs[attr] = to_instance.__dict__[attr] else: kwargs[attr] = getattr(to_instance, attr) return frozenset(tuple(kwargs.items()))
def compute_index_key(self, to_instance): ''' Compute the index key that can be used to identify an instance on the link. ''' kwargs = dict() for attr in self.key_map.values(): if _is_null(to_instance, attr): return None if attr in to_instance.__dict__: kwargs[attr] = to_instance.__dict__[attr] else: kwargs[attr] = getattr(to_instance, attr) return frozenset(tuple(kwargs.items()))
[ "Compute", "the", "index", "key", "that", "can", "be", "used", "to", "identify", "an", "instance", "on", "the", "link", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L365-L380
[ "def", "compute_index_key", "(", "self", ",", "to_instance", ")", ":", "kwargs", "=", "dict", "(", ")", "for", "attr", "in", "self", ".", "key_map", ".", "values", "(", ")", ":", "if", "_is_null", "(", "to_instance", ",", "attr", ")", ":", "return", "None", "if", "attr", "in", "to_instance", ".", "__dict__", ":", "kwargs", "[", "attr", "]", "=", "to_instance", ".", "__dict__", "[", "attr", "]", "else", ":", "kwargs", "[", "attr", "]", "=", "getattr", "(", "to_instance", ",", "attr", ")", "return", "frozenset", "(", "tuple", "(", "kwargs", ".", "items", "(", ")", ")", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
MetaClass.attribute_type
Obtain the type of an attribute.
xtuml/meta.py
def attribute_type(self, attribute_name): ''' Obtain the type of an attribute. ''' attribute_name = attribute_name.upper() for name, ty in self.attributes: if name.upper() == attribute_name: return ty
def attribute_type(self, attribute_name): ''' Obtain the type of an attribute. ''' attribute_name = attribute_name.upper() for name, ty in self.attributes: if name.upper() == attribute_name: return ty
[ "Obtain", "the", "type", "of", "an", "attribute", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L509-L516
[ "def", "attribute_type", "(", "self", ",", "attribute_name", ")", ":", "attribute_name", "=", "attribute_name", ".", "upper", "(", ")", "for", "name", ",", "ty", "in", "self", ".", "attributes", ":", "if", "name", ".", "upper", "(", ")", "==", "attribute_name", ":", "return", "ty" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
MetaClass.add_link
Add a new link from *self* to *metaclass*.
xtuml/meta.py
def add_link(self, metaclass, rel_id, phrase, conditional, many): ''' Add a new link from *self* to *metaclass*. ''' link = Link(self, rel_id, metaclass, phrase, conditional, many) key = (metaclass.kind.upper(), rel_id, phrase) self.links[key] = link return link
def add_link(self, metaclass, rel_id, phrase, conditional, many): ''' Add a new link from *self* to *metaclass*. ''' link = Link(self, rel_id, metaclass, phrase, conditional, many) key = (metaclass.kind.upper(), rel_id, phrase) self.links[key] = link return link
[ "Add", "a", "new", "link", "from", "*", "self", "*", "to", "*", "metaclass", "*", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L518-L526
[ "def", "add_link", "(", "self", ",", "metaclass", ",", "rel_id", ",", "phrase", ",", "conditional", ",", "many", ")", ":", "link", "=", "Link", "(", "self", ",", "rel_id", ",", "metaclass", ",", "phrase", ",", "conditional", ",", "many", ")", "key", "=", "(", "metaclass", ".", "kind", ".", "upper", "(", ")", ",", "rel_id", ",", "phrase", ")", "self", ".", "links", "[", "key", "]", "=", "link", "return", "link" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
MetaClass.append_attribute
Append an attribute with a given *name* and *type name* at the end of the list of attributes.
xtuml/meta.py
def append_attribute(self, name, type_name): ''' Append an attribute with a given *name* and *type name* at the end of the list of attributes. ''' attr = (name, type_name) self.attributes.append(attr)
def append_attribute(self, name, type_name): ''' Append an attribute with a given *name* and *type name* at the end of the list of attributes. ''' attr = (name, type_name) self.attributes.append(attr)
[ "Append", "an", "attribute", "with", "a", "given", "*", "name", "*", "and", "*", "type", "name", "*", "at", "the", "end", "of", "the", "list", "of", "attributes", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L528-L534
[ "def", "append_attribute", "(", "self", ",", "name", ",", "type_name", ")", ":", "attr", "=", "(", "name", ",", "type_name", ")", "self", ".", "attributes", ".", "append", "(", "attr", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
MetaClass.insert_attribute
Insert an attribute with a given *name* and *type name* at some *index* in the list of attributes.
xtuml/meta.py
def insert_attribute(self, index, name, type_name): ''' Insert an attribute with a given *name* and *type name* at some *index* in the list of attributes. ''' attr = (name, type_name) self.attributes.insert(index, attr)
def insert_attribute(self, index, name, type_name): ''' Insert an attribute with a given *name* and *type name* at some *index* in the list of attributes. ''' attr = (name, type_name) self.attributes.insert(index, attr)
[ "Insert", "an", "attribute", "with", "a", "given", "*", "name", "*", "and", "*", "type", "name", "*", "at", "some", "*", "index", "*", "in", "the", "list", "of", "attributes", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L536-L542
[ "def", "insert_attribute", "(", "self", ",", "index", ",", "name", ",", "type_name", ")", ":", "attr", "=", "(", "name", ",", "type_name", ")", "self", ".", "attributes", ".", "insert", "(", "index", ",", "attr", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
MetaClass.delete_attribute
Delete an attribute with a given *name* from the list of attributes.
xtuml/meta.py
def delete_attribute(self, name): ''' Delete an attribute with a given *name* from the list of attributes. ''' for idx, attr in enumerate(self.attributes): attr_name, _ = attr if attr_name == name: del self.attributes[idx] return
def delete_attribute(self, name): ''' Delete an attribute with a given *name* from the list of attributes. ''' for idx, attr in enumerate(self.attributes): attr_name, _ = attr if attr_name == name: del self.attributes[idx] return
[ "Delete", "an", "attribute", "with", "a", "given", "*", "name", "*", "from", "the", "list", "of", "attributes", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L544-L552
[ "def", "delete_attribute", "(", "self", ",", "name", ")", ":", "for", "idx", ",", "attr", "in", "enumerate", "(", "self", ".", "attributes", ")", ":", "attr_name", ",", "_", "=", "attr", "if", "attr_name", "==", "name", ":", "del", "self", ".", "attributes", "[", "idx", "]", "return" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
MetaClass.default_value
Obtain the default value for some *type name*.
xtuml/meta.py
def default_value(self, type_name): ''' Obtain the default value for some *type name*. ''' uname = type_name.upper() if uname == 'BOOLEAN': return False elif uname == 'INTEGER': return 0 elif uname == 'REAL': return 0.0 elif uname == 'STRING': return '' elif uname == 'UNIQUE_ID': if self.metamodel: return next(self.metamodel.id_generator) else: return None else: raise MetaException("Unknown type named '%s'" % type_name)
def default_value(self, type_name): ''' Obtain the default value for some *type name*. ''' uname = type_name.upper() if uname == 'BOOLEAN': return False elif uname == 'INTEGER': return 0 elif uname == 'REAL': return 0.0 elif uname == 'STRING': return '' elif uname == 'UNIQUE_ID': if self.metamodel: return next(self.metamodel.id_generator) else: return None else: raise MetaException("Unknown type named '%s'" % type_name)
[ "Obtain", "the", "default", "value", "for", "some", "*", "type", "name", "*", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L554-L577
[ "def", "default_value", "(", "self", ",", "type_name", ")", ":", "uname", "=", "type_name", ".", "upper", "(", ")", "if", "uname", "==", "'BOOLEAN'", ":", "return", "False", "elif", "uname", "==", "'INTEGER'", ":", "return", "0", "elif", "uname", "==", "'REAL'", ":", "return", "0.0", "elif", "uname", "==", "'STRING'", ":", "return", "''", "elif", "uname", "==", "'UNIQUE_ID'", ":", "if", "self", ".", "metamodel", ":", "return", "next", "(", "self", ".", "metamodel", ".", "id_generator", ")", "else", ":", "return", "None", "else", ":", "raise", "MetaException", "(", "\"Unknown type named '%s'\"", "%", "type_name", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
MetaClass.new
Create and return a new instance.
xtuml/meta.py
def new(self, *args, **kwargs): ''' Create and return a new instance. ''' inst = self.clazz() self.storage.append(inst) # set all attributes with an initial default value referential_attributes = dict() for name, ty in self.attributes: if name not in self.referential_attributes: value = self.default_value(ty) setattr(inst, name, value) # set all positional arguments for attr, value in zip(self.attributes, args): name, ty = attr if name not in self.referential_attributes: setattr(inst, name, value) else: referential_attributes[name] = value # set all named arguments for name, value in kwargs.items(): if name not in self.referential_attributes: setattr(inst, name, value) else: referential_attributes[name] = value if not referential_attributes: return inst # batch relate referential attributes for link in self.links.values(): if set(link.key_map.values()) - set(referential_attributes.keys()): continue kwargs = dict() for key, value in link.key_map.items(): kwargs[key] = referential_attributes[value] if not kwargs: continue for other_inst in link.to_metaclass.query(kwargs): relate(other_inst, inst, link.rel_id, link.phrase) for name, value in referential_attributes.items(): if getattr(inst, name) != value: logger.warning('unable to assign %s to %s', name, inst) return inst
def new(self, *args, **kwargs): ''' Create and return a new instance. ''' inst = self.clazz() self.storage.append(inst) # set all attributes with an initial default value referential_attributes = dict() for name, ty in self.attributes: if name not in self.referential_attributes: value = self.default_value(ty) setattr(inst, name, value) # set all positional arguments for attr, value in zip(self.attributes, args): name, ty = attr if name not in self.referential_attributes: setattr(inst, name, value) else: referential_attributes[name] = value # set all named arguments for name, value in kwargs.items(): if name not in self.referential_attributes: setattr(inst, name, value) else: referential_attributes[name] = value if not referential_attributes: return inst # batch relate referential attributes for link in self.links.values(): if set(link.key_map.values()) - set(referential_attributes.keys()): continue kwargs = dict() for key, value in link.key_map.items(): kwargs[key] = referential_attributes[value] if not kwargs: continue for other_inst in link.to_metaclass.query(kwargs): relate(other_inst, inst, link.rel_id, link.phrase) for name, value in referential_attributes.items(): if getattr(inst, name) != value: logger.warning('unable to assign %s to %s', name, inst) return inst
[ "Create", "and", "return", "a", "new", "instance", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L579-L630
[ "def", "new", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "inst", "=", "self", ".", "clazz", "(", ")", "self", ".", "storage", ".", "append", "(", "inst", ")", "# set all attributes with an initial default value", "referential_attributes", "=", "dict", "(", ")", "for", "name", ",", "ty", "in", "self", ".", "attributes", ":", "if", "name", "not", "in", "self", ".", "referential_attributes", ":", "value", "=", "self", ".", "default_value", "(", "ty", ")", "setattr", "(", "inst", ",", "name", ",", "value", ")", "# set all positional arguments", "for", "attr", ",", "value", "in", "zip", "(", "self", ".", "attributes", ",", "args", ")", ":", "name", ",", "ty", "=", "attr", "if", "name", "not", "in", "self", ".", "referential_attributes", ":", "setattr", "(", "inst", ",", "name", ",", "value", ")", "else", ":", "referential_attributes", "[", "name", "]", "=", "value", "# set all named arguments", "for", "name", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "if", "name", "not", "in", "self", ".", "referential_attributes", ":", "setattr", "(", "inst", ",", "name", ",", "value", ")", "else", ":", "referential_attributes", "[", "name", "]", "=", "value", "if", "not", "referential_attributes", ":", "return", "inst", "# batch relate referential attributes ", "for", "link", "in", "self", ".", "links", ".", "values", "(", ")", ":", "if", "set", "(", "link", ".", "key_map", ".", "values", "(", ")", ")", "-", "set", "(", "referential_attributes", ".", "keys", "(", ")", ")", ":", "continue", "kwargs", "=", "dict", "(", ")", "for", "key", ",", "value", "in", "link", ".", "key_map", ".", "items", "(", ")", ":", "kwargs", "[", "key", "]", "=", "referential_attributes", "[", "value", "]", "if", "not", "kwargs", ":", "continue", "for", "other_inst", "in", "link", ".", "to_metaclass", ".", "query", "(", "kwargs", ")", ":", "relate", "(", "other_inst", ",", "inst", ",", "link", ".", "rel_id", ",", "link", ".", "phrase", ")", "for", "name", ",", "value", "in", "referential_attributes", ".", "items", "(", ")", ":", "if", "getattr", "(", "inst", ",", "name", ")", "!=", "value", ":", "logger", ".", "warning", "(", "'unable to assign %s to %s'", ",", "name", ",", "inst", ")", "return", "inst" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
MetaClass.clone
Create a shallow clone of an *instance*. **Note:** the clone and the original instance **does not** have to be part of the same metaclass.
xtuml/meta.py
def clone(self, instance): ''' Create a shallow clone of an *instance*. **Note:** the clone and the original instance **does not** have to be part of the same metaclass. ''' args = list() for name, _ in get_metaclass(instance).attributes: value = getattr(instance, name) args.append(value) return self.new(*args)
def clone(self, instance): ''' Create a shallow clone of an *instance*. **Note:** the clone and the original instance **does not** have to be part of the same metaclass. ''' args = list() for name, _ in get_metaclass(instance).attributes: value = getattr(instance, name) args.append(value) return self.new(*args)
[ "Create", "a", "shallow", "clone", "of", "an", "*", "instance", "*", ".", "**", "Note", ":", "**", "the", "clone", "and", "the", "original", "instance", "**", "does", "not", "**", "have", "to", "be", "part", "of", "the", "same", "metaclass", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L632-L644
[ "def", "clone", "(", "self", ",", "instance", ")", ":", "args", "=", "list", "(", ")", "for", "name", ",", "_", "in", "get_metaclass", "(", "instance", ")", ".", "attributes", ":", "value", "=", "getattr", "(", "instance", ",", "name", ")", "args", ".", "append", "(", "value", ")", "return", "self", ".", "new", "(", "*", "args", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
MetaClass.delete
Delete an *instance* from the instance pool and optionally *disconnect* it from any links it might be connected to. If the *instance* is not part of the metaclass, a *MetaException* is thrown.
xtuml/meta.py
def delete(self, instance, disconnect=True): ''' Delete an *instance* from the instance pool and optionally *disconnect* it from any links it might be connected to. If the *instance* is not part of the metaclass, a *MetaException* is thrown. ''' if instance in self.storage: self.storage.remove(instance) else: raise DeleteException("Instance not found in the instance pool") if not disconnect: return for link in self.links.values(): if instance not in link: continue for other in link[instance]: unrelate(instance, other, link.rel_id, link.phrase)
def delete(self, instance, disconnect=True): ''' Delete an *instance* from the instance pool and optionally *disconnect* it from any links it might be connected to. If the *instance* is not part of the metaclass, a *MetaException* is thrown. ''' if instance in self.storage: self.storage.remove(instance) else: raise DeleteException("Instance not found in the instance pool") if not disconnect: return for link in self.links.values(): if instance not in link: continue for other in link[instance]: unrelate(instance, other, link.rel_id, link.phrase)
[ "Delete", "an", "*", "instance", "*", "from", "the", "instance", "pool", "and", "optionally", "*", "disconnect", "*", "it", "from", "any", "links", "it", "might", "be", "connected", "to", ".", "If", "the", "*", "instance", "*", "is", "not", "part", "of", "the", "metaclass", "a", "*", "MetaException", "*", "is", "thrown", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L646-L665
[ "def", "delete", "(", "self", ",", "instance", ",", "disconnect", "=", "True", ")", ":", "if", "instance", "in", "self", ".", "storage", ":", "self", ".", "storage", ".", "remove", "(", "instance", ")", "else", ":", "raise", "DeleteException", "(", "\"Instance not found in the instance pool\"", ")", "if", "not", "disconnect", ":", "return", "for", "link", "in", "self", ".", "links", ".", "values", "(", ")", ":", "if", "instance", "not", "in", "link", ":", "continue", "for", "other", "in", "link", "[", "instance", "]", ":", "unrelate", "(", "instance", ",", "other", ",", "link", ".", "rel_id", ",", "link", ".", "phrase", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
MetaClass.select_one
Select a single instance from the instance pool. Query operators such as where_eq(), order_by() or filter functions may be passed as optional arguments.
xtuml/meta.py
def select_one(self, *args): ''' Select a single instance from the instance pool. Query operators such as where_eq(), order_by() or filter functions may be passed as optional arguments. ''' s = apply_query_operators(self.storage, args) return next(iter(s), None)
def select_one(self, *args): ''' Select a single instance from the instance pool. Query operators such as where_eq(), order_by() or filter functions may be passed as optional arguments. ''' s = apply_query_operators(self.storage, args) return next(iter(s), None)
[ "Select", "a", "single", "instance", "from", "the", "instance", "pool", ".", "Query", "operators", "such", "as", "where_eq", "()", "order_by", "()", "or", "filter", "functions", "may", "be", "passed", "as", "optional", "arguments", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L667-L674
[ "def", "select_one", "(", "self", ",", "*", "args", ")", ":", "s", "=", "apply_query_operators", "(", "self", ".", "storage", ",", "args", ")", "return", "next", "(", "iter", "(", "s", ")", ",", "None", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
MetaClass.select_many
Select several instances from the instance pool. Query operators such as where_eq(), order_by() or filter functions may be passed as optional arguments.
xtuml/meta.py
def select_many(self, *args): ''' Select several instances from the instance pool. Query operators such as where_eq(), order_by() or filter functions may be passed as optional arguments. ''' s = apply_query_operators(self.storage, args) if isinstance(s, QuerySet): return s else: return QuerySet(s)
def select_many(self, *args): ''' Select several instances from the instance pool. Query operators such as where_eq(), order_by() or filter functions may be passed as optional arguments. ''' s = apply_query_operators(self.storage, args) if isinstance(s, QuerySet): return s else: return QuerySet(s)
[ "Select", "several", "instances", "from", "the", "instance", "pool", ".", "Query", "operators", "such", "as", "where_eq", "()", "order_by", "()", "or", "filter", "functions", "may", "be", "passed", "as", "optional", "arguments", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L676-L686
[ "def", "select_many", "(", "self", ",", "*", "args", ")", ":", "s", "=", "apply_query_operators", "(", "self", ".", "storage", ",", "args", ")", "if", "isinstance", "(", "s", ",", "QuerySet", ")", ":", "return", "s", "else", ":", "return", "QuerySet", "(", "s", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
MetaClass.navigate
Navigate across a link with some *rel_id* and *phrase* that yields instances of some *kind*.
xtuml/meta.py
def navigate(self, inst, kind, rel_id, phrase=''): ''' Navigate across a link with some *rel_id* and *phrase* that yields instances of some *kind*. ''' key = (kind.upper(), rel_id, phrase) if key in self.links: link = self.links[key] return link.navigate(inst) link1, link2 = self._find_assoc_links(kind, rel_id, phrase) inst_set = xtuml.OrderedSet() for inst in link1.navigate(inst): inst_set |= link2.navigate(inst) return inst_set
def navigate(self, inst, kind, rel_id, phrase=''): ''' Navigate across a link with some *rel_id* and *phrase* that yields instances of some *kind*. ''' key = (kind.upper(), rel_id, phrase) if key in self.links: link = self.links[key] return link.navigate(inst) link1, link2 = self._find_assoc_links(kind, rel_id, phrase) inst_set = xtuml.OrderedSet() for inst in link1.navigate(inst): inst_set |= link2.navigate(inst) return inst_set
[ "Navigate", "across", "a", "link", "with", "some", "*", "rel_id", "*", "and", "*", "phrase", "*", "that", "yields", "instances", "of", "some", "*", "kind", "*", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L700-L715
[ "def", "navigate", "(", "self", ",", "inst", ",", "kind", ",", "rel_id", ",", "phrase", "=", "''", ")", ":", "key", "=", "(", "kind", ".", "upper", "(", ")", ",", "rel_id", ",", "phrase", ")", "if", "key", "in", "self", ".", "links", ":", "link", "=", "self", ".", "links", "[", "key", "]", "return", "link", ".", "navigate", "(", "inst", ")", "link1", ",", "link2", "=", "self", ".", "_find_assoc_links", "(", "kind", ",", "rel_id", ",", "phrase", ")", "inst_set", "=", "xtuml", ".", "OrderedSet", "(", ")", "for", "inst", "in", "link1", ".", "navigate", "(", "inst", ")", ":", "inst_set", "|=", "link2", ".", "navigate", "(", "inst", ")", "return", "inst_set" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
MetaModel.instances
Obtain a sequence of all instances in the metamodel.
xtuml/meta.py
def instances(self): ''' Obtain a sequence of all instances in the metamodel. ''' for metaclass in self.metaclasses.values(): for inst in metaclass.storage: yield inst
def instances(self): ''' Obtain a sequence of all instances in the metamodel. ''' for metaclass in self.metaclasses.values(): for inst in metaclass.storage: yield inst
[ "Obtain", "a", "sequence", "of", "all", "instances", "in", "the", "metamodel", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L1148-L1154
[ "def", "instances", "(", "self", ")", ":", "for", "metaclass", "in", "self", ".", "metaclasses", ".", "values", "(", ")", ":", "for", "inst", "in", "metaclass", ".", "storage", ":", "yield", "inst" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
MetaModel.define_class
Define a new class in the metamodel, and return its metaclass.
xtuml/meta.py
def define_class(self, kind, attributes, doc=''): ''' Define a new class in the metamodel, and return its metaclass. ''' ukind = kind.upper() if ukind in self.metaclasses: raise MetaModelException('A class with the name %s is already defined' % kind) metaclass = MetaClass(kind, self) for name, ty in attributes: metaclass.append_attribute(name, ty) self.metaclasses[ukind] = metaclass return metaclass
def define_class(self, kind, attributes, doc=''): ''' Define a new class in the metamodel, and return its metaclass. ''' ukind = kind.upper() if ukind in self.metaclasses: raise MetaModelException('A class with the name %s is already defined' % kind) metaclass = MetaClass(kind, self) for name, ty in attributes: metaclass.append_attribute(name, ty) self.metaclasses[ukind] = metaclass return metaclass
[ "Define", "a", "new", "class", "in", "the", "metamodel", "and", "return", "its", "metaclass", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L1156-L1170
[ "def", "define_class", "(", "self", ",", "kind", ",", "attributes", ",", "doc", "=", "''", ")", ":", "ukind", "=", "kind", ".", "upper", "(", ")", "if", "ukind", "in", "self", ".", "metaclasses", ":", "raise", "MetaModelException", "(", "'A class with the name %s is already defined'", "%", "kind", ")", "metaclass", "=", "MetaClass", "(", "kind", ",", "self", ")", "for", "name", ",", "ty", "in", "attributes", ":", "metaclass", ".", "append_attribute", "(", "name", ",", "ty", ")", "self", ".", "metaclasses", "[", "ukind", "]", "=", "metaclass", "return", "metaclass" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
MetaModel.find_metaclass
Find a metaclass of some *kind* in the metamodel.
xtuml/meta.py
def find_metaclass(self, kind): ''' Find a metaclass of some *kind* in the metamodel. ''' ukind = kind.upper() if ukind in self.metaclasses: return self.metaclasses[ukind] else: raise UnknownClassException(kind)
def find_metaclass(self, kind): ''' Find a metaclass of some *kind* in the metamodel. ''' ukind = kind.upper() if ukind in self.metaclasses: return self.metaclasses[ukind] else: raise UnknownClassException(kind)
[ "Find", "a", "metaclass", "of", "some", "*", "kind", "*", "in", "the", "metamodel", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L1178-L1186
[ "def", "find_metaclass", "(", "self", ",", "kind", ")", ":", "ukind", "=", "kind", ".", "upper", "(", ")", "if", "ukind", "in", "self", ".", "metaclasses", ":", "return", "self", ".", "metaclasses", "[", "ukind", "]", "else", ":", "raise", "UnknownClassException", "(", "kind", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
MetaModel.new
Create and return a new instance in the metamodel of some *kind*. Optionally, initial attribute values may be assigned to the new instance by passing them as positional or keyword arguments. Positional arguments are assigned in the order in which they appear in the metaclass.
xtuml/meta.py
def new(self, kind, *args, **kwargs): ''' Create and return a new instance in the metamodel of some *kind*. Optionally, initial attribute values may be assigned to the new instance by passing them as positional or keyword arguments. Positional arguments are assigned in the order in which they appear in the metaclass. ''' metaclass = self.find_metaclass(kind) return metaclass.new(*args, **kwargs)
def new(self, kind, *args, **kwargs): ''' Create and return a new instance in the metamodel of some *kind*. Optionally, initial attribute values may be assigned to the new instance by passing them as positional or keyword arguments. Positional arguments are assigned in the order in which they appear in the metaclass. ''' metaclass = self.find_metaclass(kind) return metaclass.new(*args, **kwargs)
[ "Create", "and", "return", "a", "new", "instance", "in", "the", "metamodel", "of", "some", "*", "kind", "*", ".", "Optionally", "initial", "attribute", "values", "may", "be", "assigned", "to", "the", "new", "instance", "by", "passing", "them", "as", "positional", "or", "keyword", "arguments", ".", "Positional", "arguments", "are", "assigned", "in", "the", "order", "in", "which", "they", "appear", "in", "the", "metaclass", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L1188-L1197
[ "def", "new", "(", "self", ",", "kind", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "metaclass", "=", "self", ".", "find_metaclass", "(", "kind", ")", "return", "metaclass", ".", "new", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
MetaModel.clone
Create a shallow clone of an *instance*. **Note:** the clone and the original instance **does not** have to be part of the same metaclass.
xtuml/meta.py
def clone(self, instance): ''' Create a shallow clone of an *instance*. **Note:** the clone and the original instance **does not** have to be part of the same metaclass. ''' metaclass = get_metaclass(instance) metaclass = self.find_metaclass(metaclass.kind) return metaclass.clone(instance)
def clone(self, instance): ''' Create a shallow clone of an *instance*. **Note:** the clone and the original instance **does not** have to be part of the same metaclass. ''' metaclass = get_metaclass(instance) metaclass = self.find_metaclass(metaclass.kind) return metaclass.clone(instance)
[ "Create", "a", "shallow", "clone", "of", "an", "*", "instance", "*", ".", "**", "Note", ":", "**", "the", "clone", "and", "the", "original", "instance", "**", "does", "not", "**", "have", "to", "be", "part", "of", "the", "same", "metaclass", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L1199-L1208
[ "def", "clone", "(", "self", ",", "instance", ")", ":", "metaclass", "=", "get_metaclass", "(", "instance", ")", "metaclass", "=", "self", ".", "find_metaclass", "(", "metaclass", ".", "kind", ")", "return", "metaclass", ".", "clone", "(", "instance", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
MetaModel.define_association
Define and return an association from one kind of class (the source kind) to some other kind of class (the target kind).
xtuml/meta.py
def define_association(self, rel_id, source_kind, source_keys, source_many, source_conditional, source_phrase, target_kind, target_keys, target_many, target_conditional, target_phrase): ''' Define and return an association from one kind of class (the source kind) to some other kind of class (the target kind). ''' if isinstance(rel_id, int): rel_id = 'R%d' % rel_id source_metaclass = self.find_metaclass(source_kind) target_metaclass = self.find_metaclass(target_kind) source_link = target_metaclass.add_link(source_metaclass, rel_id, many=source_many, phrase=target_phrase, conditional=source_conditional) target_link = source_metaclass.add_link(target_metaclass, rel_id, many=target_many, phrase=source_phrase, conditional=target_conditional) ass = Association(rel_id, source_keys, source_link, target_keys, target_link) source_link.key_map = dict(zip(source_keys, target_keys)) target_link.key_map = dict(zip(target_keys, source_keys)) self.associations.append(ass) return ass
def define_association(self, rel_id, source_kind, source_keys, source_many, source_conditional, source_phrase, target_kind, target_keys, target_many, target_conditional, target_phrase): ''' Define and return an association from one kind of class (the source kind) to some other kind of class (the target kind). ''' if isinstance(rel_id, int): rel_id = 'R%d' % rel_id source_metaclass = self.find_metaclass(source_kind) target_metaclass = self.find_metaclass(target_kind) source_link = target_metaclass.add_link(source_metaclass, rel_id, many=source_many, phrase=target_phrase, conditional=source_conditional) target_link = source_metaclass.add_link(target_metaclass, rel_id, many=target_many, phrase=source_phrase, conditional=target_conditional) ass = Association(rel_id, source_keys, source_link, target_keys, target_link) source_link.key_map = dict(zip(source_keys, target_keys)) target_link.key_map = dict(zip(target_keys, source_keys)) self.associations.append(ass) return ass
[ "Define", "and", "return", "an", "association", "from", "one", "kind", "of", "class", "(", "the", "source", "kind", ")", "to", "some", "other", "kind", "of", "class", "(", "the", "target", "kind", ")", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L1210-L1243
[ "def", "define_association", "(", "self", ",", "rel_id", ",", "source_kind", ",", "source_keys", ",", "source_many", ",", "source_conditional", ",", "source_phrase", ",", "target_kind", ",", "target_keys", ",", "target_many", ",", "target_conditional", ",", "target_phrase", ")", ":", "if", "isinstance", "(", "rel_id", ",", "int", ")", ":", "rel_id", "=", "'R%d'", "%", "rel_id", "source_metaclass", "=", "self", ".", "find_metaclass", "(", "source_kind", ")", "target_metaclass", "=", "self", ".", "find_metaclass", "(", "target_kind", ")", "source_link", "=", "target_metaclass", ".", "add_link", "(", "source_metaclass", ",", "rel_id", ",", "many", "=", "source_many", ",", "phrase", "=", "target_phrase", ",", "conditional", "=", "source_conditional", ")", "target_link", "=", "source_metaclass", ".", "add_link", "(", "target_metaclass", ",", "rel_id", ",", "many", "=", "target_many", ",", "phrase", "=", "source_phrase", ",", "conditional", "=", "target_conditional", ")", "ass", "=", "Association", "(", "rel_id", ",", "source_keys", ",", "source_link", ",", "target_keys", ",", "target_link", ")", "source_link", ".", "key_map", "=", "dict", "(", "zip", "(", "source_keys", ",", "target_keys", ")", ")", "target_link", ".", "key_map", "=", "dict", "(", "zip", "(", "target_keys", ",", "source_keys", ")", ")", "self", ".", "associations", ".", "append", "(", "ass", ")", "return", "ass" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a
test
MetaModel.define_unique_identifier
Define a unique identifier for some *kind* of class based on its *named attributes*.
xtuml/meta.py
def define_unique_identifier(self, kind, name, *named_attributes): ''' Define a unique identifier for some *kind* of class based on its *named attributes*. ''' if not named_attributes: return if isinstance(name, int): name = 'I%d' % name metaclass = self.find_metaclass(kind) metaclass.indices[name] = tuple(named_attributes) metaclass.identifying_attributes |= set(named_attributes)
def define_unique_identifier(self, kind, name, *named_attributes): ''' Define a unique identifier for some *kind* of class based on its *named attributes*. ''' if not named_attributes: return if isinstance(name, int): name = 'I%d' % name metaclass = self.find_metaclass(kind) metaclass.indices[name] = tuple(named_attributes) metaclass.identifying_attributes |= set(named_attributes)
[ "Define", "a", "unique", "identifier", "for", "some", "*", "kind", "*", "of", "class", "based", "on", "its", "*", "named", "attributes", "*", "." ]
xtuml/pyxtuml
python
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L1245-L1258
[ "def", "define_unique_identifier", "(", "self", ",", "kind", ",", "name", ",", "*", "named_attributes", ")", ":", "if", "not", "named_attributes", ":", "return", "if", "isinstance", "(", "name", ",", "int", ")", ":", "name", "=", "'I%d'", "%", "name", "metaclass", "=", "self", ".", "find_metaclass", "(", "kind", ")", "metaclass", ".", "indices", "[", "name", "]", "=", "tuple", "(", "named_attributes", ")", "metaclass", ".", "identifying_attributes", "|=", "set", "(", "named_attributes", ")" ]
7dd9343b9a0191d1db1887ab9288d0a026608d9a