How to use new_instance method in localstack

Best Python code snippet using localstack_python

test_agent.py

Source:test_agent.py Github

copy

Full Screen

...63 assert len(instances) == 3646566def test_create_instance(test_agent):67 instance = test_agent.new_instance("java.lang.String", ["sss"])68 assert instance69 assert instance.class_name == "java.lang.String"70 assert instance.to_string() == 'sss'7172 instance = test_agent.new_instance("int", [3])73 assert instance74 assert instance.class_name == "java.lang.Integer"75 assert instance.to_string() == '3'7677 instance = test_agent.new_instance("char", ["c"])78 assert instance79 assert instance.class_name == "java.lang.Character"80 assert instance.to_string() == 'c'8182 instance = test_agent.new_instance("float", [3.2])83 assert instance84 assert instance.class_name == "java.lang.Float"85 assert instance.to_string() == '3.2'8687 instance = test_agent.new_instance("double", [3.2])88 assert instance89 assert instance.class_name == "java.lang.Double"90 assert instance.to_string() == '3.2'9192 instance = test_agent.new_instance("boolean", [False])93 assert instance94 assert instance.class_name == "java.lang.Boolean"95 assert instance.to_string() == 'false'9697 instance = test_agent.new_instance("java.lang.Integer", [3])98 assert instance99 assert instance.class_name == "java.lang.Integer"100 assert instance.to_string() == '3'101102 instance = test_agent.new_instance(TEST_APP_TEST_CLASS_NAME)103 assert instance104 assert instance.class_name == TEST_APP_TEST_CLASS_NAME105 assert instance.to_string() == 'ToString1'106107 instance = test_agent.new_instance(TEST_APP_SAMPLE_CLASS)108 assert instance109 assert instance.class_name == TEST_APP_SAMPLE_CLASS110 assert instance.to_string() == 'empty'111112 instance = test_agent.new_instance(TEST_APP_SAMPLE_CLASS, [1, 1.1, 'c', "sss", True, 33, 5555, 22.33],113 ['int', 'double', 'char', 'java.lang.String', 'boolean', 'byte', 'long',114 'float'])115 assert instance116 assert instance.class_name == TEST_APP_SAMPLE_CLASS117 assert instance.to_string() == 's1'118119 instance = test_agent.new_instance(TEST_APP_SAMPLE_CLASS, [1, 1.1, 'c', "sss", True, 33, 5555, 22.33])120 assert instance121 assert instance.class_name == TEST_APP_SAMPLE_CLASS122 assert instance.to_string() == 's1'123124 instance = test_agent.new_instance(TEST_APP_SAMPLE_CLASS,125 [test_agent.new_instance("int", [3]),126 test_agent.new_instance("double", [3.3]),127 test_agent.new_instance("char", ['3']),128 test_agent.new_instance("java.lang.String", ['somestr']),129 test_agent.new_instance("boolean", [True]),130 test_agent.new_instance("byte", [3]),131 test_agent.new_instance("long", [33333]),132 test_agent.new_instance("float", [3.56])])133 assert instance134 assert instance.class_name == TEST_APP_SAMPLE_CLASS135 assert instance.to_string() == 's2'136137 instance = test_agent.new_instance(TEST_APP_SAMPLE_CLASS, [3])138 assert test_agent.__get_field_value__(TEST_APP_SAMPLE_CLASS, "s", instance.id) == "i1"139140 instance = test_agent.new_instance(TEST_APP_SAMPLE_CLASS, [test_agent.new_instance("int", [3])])141 assert test_agent.__get_field_value__(TEST_APP_SAMPLE_CLASS, "s", instance.id) == "i2"142143 instance = test_agent.new_instance(TEST_APP_SAMPLE_CLASS, [test_agent.new_instance("java.lang.Integer", [3])])144 assert test_agent.__get_field_value__(TEST_APP_SAMPLE_CLASS, "s", instance.id) == "i2"145146 assert instance147 assert instance.class_name == TEST_APP_SAMPLE_CLASS148149150def test_get_field_value(test_agent, test_instance):151 def geti(field_name):152 return test_agent.__get_field_value__(TEST_APP_TEST_CLASS_NAME, field_name, test_instance.id)153154 def get(field_name):155 return test_agent.get_static_field_value(TEST_APP_TEST_CLASS_NAME, field_name)156157 # static fields, primitive instances158 assert get("si") == 100159 assert get("sI").to_string() == "101"160 assert get("sI").class_name == "java.lang.Integer"161162 # static fields, class instances163 v = get("sSample")164 assert v.class_name == TEST_APP_SAMPLE_CLASS165 assert v.id166167 # static field, null value168 assert get("sSampleNull") is None169170 # instance field, primitive instances171 assert geti("b") == 1172 assert geti("B").to_string() == "2"173 assert geti("i") == 3174 assert geti("I").to_string() == "4"175 assert geti("s") == 5176 assert geti("S").to_string() == "6"177 assert geti("d") == 7.7178 assert geti("D").to_string() == "8.8"179 assert "{:.1f}".format(geti("f")) == '7.7'180 assert geti("F").to_string() == "8.8"181 assert geti("c") == "c"182 assert geti("C").to_string() == "C"183 assert geti("bool") is True184 assert geti("Bool").to_string() == 'false'185 assert geti("Str") == "sample-string..."186187 # instance field, class instances188 assert geti("someNullValue") is None189 v = geti("sampleClassInstance")190 assert v.class_name == TEST_APP_SAMPLE_CLASS191 assert v.id192193 # check that the type that return is the dynamic type194 v = geti("itsb")195 assert v.class_name == TEST_APP_TEST_CLASS_NAME + "$B"196197 v = geti("as")198 assert isinstance(v, Array)199 assert v.class_name == 'java.lang.String[]'200201 v = geti("ai")202 assert isinstance(v, Array)203 assert v.class_name == 'int[][]'204205 v = geti("aI")206 assert isinstance(v, Array)207 assert v.class_name == 'java.lang.Integer[][][]'208209210def test_set_field_value(test_agent, test_instance):211 def geti(field_name):212 return test_agent.__get_field_value__(TEST_APP_TEST_CLASS_NAME, field_name, test_instance.id)213214 def get(field_name):215 return test_agent.get_static_field_value(TEST_APP_TEST_CLASS_NAME, field_name)216217 def seti(field_name, new_value):218 return test_agent.__set_field_value__(TEST_APP_TEST_CLASS_NAME, field_name, new_value, test_instance.id)219220 def set(field_name, new_value):221 return test_agent.set_static_field_value(TEST_APP_TEST_CLASS_NAME, field_name, new_value)222223 # static fields, primitive instances224 set("si", 200)225 assert get("si") == 200226227 set("sI", test_agent.new_instance("java.lang.Integer", [3]))228 assert get("sI").to_string() == "3"229 assert get("sI").class_name == "java.lang.Integer"230231 # static fields, class instances232 set("sSample", None)233 v = get("sSample")234 assert v is None235236 sample = test_agent.new_instance(TEST_APP_SAMPLE_CLASS,237 [test_agent.new_instance("int", [3]),238 test_agent.new_instance("double", [3.3]),239 test_agent.new_instance("char", ['3']),240 test_agent.new_instance("java.lang.String", ['somestr']),241 test_agent.new_instance("boolean", [True]),242 test_agent.new_instance("byte", [3]),243 test_agent.new_instance("long", [33333]),244 test_agent.new_instance("float", [3.56])])245 set("sSample", sample)246 v = get("sSample")247 assert v248 assert v.class_name == TEST_APP_SAMPLE_CLASS249 assert v.to_string() == 's2'250251 # static field, null value252 assert get("sSampleNull") is None253254 # instance field, primitive instances255 seti("b", 55)256 assert geti("b") == 55257258 seti("B", test_agent.new_instance("java.lang.Byte", [3]))259 assert geti("B").to_string() == "3"260261 seti("i", 87)262 assert geti("i") == 87263264 seti("I", test_agent.new_instance("java.lang.Integer", [3]))265 assert geti("I").to_string() == "3"266267 seti("s", 45)268 assert geti("s") == 45269270 seti("S", test_agent.new_instance("java.lang.Short", [32]))271 assert geti("S").to_string() == "32"272273 seti("d", 9.91)274 assert geti("d") == 9.91275276 seti("D", test_agent.new_instance("java.lang.Double", [32.32]))277 assert geti("D").to_string() == "32.32"278279 seti("f", 3.3)280 assert "{:.1f}".format(geti("f")) == '3.3'281282 seti("F", test_agent.new_instance("java.lang.Float", [12.32]))283 assert geti("F").to_string() == "12.32"284285 seti("c", 'w')286 assert geti("c") == "w"287288 seti("C", test_agent.new_instance("java.lang.Character", ['T']))289 assert geti("C").to_string() == "T"290291 seti("bool", False)292 assert geti("bool") is False293294 seti("Bool", test_agent.new_instance("java.lang.Boolean", [True]))295 assert geti("Bool").to_string() == 'true'296297 seti("Str", test_agent.new_instance("java.lang.String", ['hello']))298 assert geti("Str") == "hello"299300 # instance field, class instances301 instance = test_agent.new_instance(TEST_APP_SAMPLE_CLASS, [1, 1.1, 'c', "sss", True, 33, 5555, 22.33],302 ['int', 'double', 'char', 'java.lang.String', 'boolean', 'byte', 'long',303 'float'])304 seti("someNullValue", instance)305 v = geti("sampleClassInstance")306 assert v.to_string() == 's1'307308 # check that the type that return is the dynamic type309 a_instance = test_agent.new_instance(TEST_APP_TEST_CLASS_NAME + "$A")310 seti("itsb", a_instance)311 assert geti("itsb").class_name == TEST_APP_TEST_CLASS_NAME + "$A"312 b_instance = test_agent.new_instance(TEST_APP_TEST_CLASS_NAME + "$B")313 seti("itsb", b_instance)314 assert geti("itsb").class_name == TEST_APP_TEST_CLASS_NAME + "$B"315316 seti("as", ['a', 'b', 'c'])317 v = geti("as")318 assert isinstance(v, Array)319 assert v.class_name == 'java.lang.String[]'320 assert str(v) == '[a, b, c]'321322 seti("ai", test_agent.new_array('int[][]', [[1], [2, 9], [3]]))323 v = geti("ai")324 assert isinstance(v, Array)325 assert v.class_name == 'int[][]'326 assert str(v) == '[[1], [2, 9], [3]]'327328 seti("aI", test_agent.new_array('java.lang.Integer[][][]', [[[1]], [[2], [9]], [[3]]]))329 v = geti("aI")330 assert isinstance(v, Array)331 assert v.class_name == 'java.lang.Integer[][][]'332 assert str(v) == '[[[1]], [[2], [9]], [[3]]]'333334335def test_to_string(test_agent):336 instance = test_agent.new_instance(TEST_APP_SAMPLE_CLASS, [3])337 assert test_agent.__to_string__(instance.id) == "i1"338339 instance = test_agent.new_instance(TEST_APP_SAMPLE_CLASS, [test_agent.new_instance("int", [3])])340 assert test_agent.__to_string__(instance.id) == "i2"341342343def test_call_static_method(test_agent):344 # call static methods345 assert test_agent.call_static_method(TEST_APP_TEST_CLASS_NAME, "overload", [""], ["java.lang.String"]) == 1346 double_instance = test_agent.new_instance("java.lang.Double", [3.2])347 assert test_agent.call_static_method(TEST_APP_TEST_CLASS_NAME, "overload",348 [1, double_instance],349 ["int", "java.lang.Double"]) is None350 assert test_agent.call_static_method(TEST_APP_TEST_CLASS_NAME, "voidFunc") is None351 assert test_agent.call_static_method(TEST_APP_TEST_CLASS_NAME, "f", [1, 3], ['int', 'double']) == 3352 assert test_agent.call_static_method(TEST_APP_TEST_CLASS_NAME, "f", [2, 3.2], ['int', 'double']) == 6.4353 assert test_agent.call_static_method(TEST_APP_TEST_CLASS_NAME, "f", [2, 2.2], ['int', 'double']) == 4.4354355 arr = test_agent.call_static_method(TEST_APP_TEST_CLASS_NAME, "sgetArr", ["hello"], ["java.lang.String"])356 assert isinstance(arr, Array)357 assert arr.class_name is None358 print(str(arr))359 assert re.match(r"\[.*Ainstance.*Binstance.*\]", str(arr))360361 arr = test_agent.call_static_method(TEST_APP_TEST_CLASS_NAME, "sgetArr2", ['c'], ["char"])362 assert isinstance(arr, Array)363 assert arr.class_name is None364 assert re.match(r"\[.*Binstance.*Binstance.*Binstance.*Binstance.*\]", str(arr))365366 arr = test_agent.call_static_method(TEST_APP_TEST_CLASS_NAME, "sgetArr3", [99], ["short"])367 assert isinstance(arr, Array)368 assert arr.class_name is None369 assert "[[[1, 2]], [[3, 4]]]" == str(arr)370371372# TODO: call a method that gets an array as param373374375def test_create_array_1d(test_agent):376 arr = test_agent.new_array("int[]", [1, 2])377 assert arr.class_name == "int[]"378 assert '[1, 2]' == str(arr)379 arr[1] = 3380 arr[0] = 7381 assert '[7, 3]' == str(arr)382383 arr = test_agent.new_array("java.lang.Integer[]", [test_agent.new_instance('java.lang.Integer', [1]),384 test_agent.new_instance('java.lang.Integer', [2]),385 test_agent.new_instance('java.lang.Integer', [3])])386 assert arr.class_name == "java.lang.Integer[]"387 assert '[1, 2, 3]' == str(arr)388 arr[1] = test_agent.new_instance('java.lang.Integer', [3])389 assert '[1, 3, 3]' == str(arr)390391 arr = test_agent.new_array('double[]', [1.1, 2, 3])392 assert arr.class_name == "double[]"393 assert '[1.1, 2, 3]' == str(arr)394 arr[2] = 7.2395 assert '[1.1, 2, 7.2]' == str(arr)396397 i1 = test_agent.new_instance(TEST_APP_SAMPLE_CLASS)398 i2 = test_agent.new_instance(TEST_APP_SAMPLE_CLASS, [2])399 i3 = test_agent.new_instance(TEST_APP_SAMPLE_CLASS, ['3'])400401 arr = test_agent.new_array(TEST_APP_SAMPLE_CLASS + "[]", [i1, i2, i3])402 assert arr.class_name == TEST_APP_SAMPLE_CLASS + "[]"403 assert "[empty, i1, 3]" == str(arr)404405406def test_call_instance_method(test_agent, test_instance):407 # call instance methods408 assert test_agent.__call_instance_method__(test_instance.id, "overload", [], []) is None409 assert test_agent.__call_instance_method__(test_instance.id, "gg", [None, None, 1],410 ["java.lang.String", "java.lang.Object", "byte"]411 ) == -1412 assert test_agent.__call_instance_method__(test_instance.id, "gg",413 ["hi", test_agent.new_instance("java.lang.Object"), 1],414 ["java.lang.String", "java.lang.Object", "byte"]) == -1415416 sc1 = test_agent.new_instance(TEST_APP_SAMPLE_CLASS)417 sc2 = test_agent.new_instance(TEST_APP_SAMPLE_CLASS)418 assert test_agent.__call_instance_method__(test_instance.id, "sampleString", [sc1, sc2, "2", 3],419 [TEST_APP_SAMPLE_CLASS, TEST_APP_SAMPLE_CLASS, "java.lang.String",420 "int"]) == "emptyempty23"421422 assert test_agent.__call_instance_method__(test_instance.id, "uu", [3], ["int"]) == 11423 assert test_agent.__call_instance_method__(test_instance.id, "uu",424 [test_agent.new_instance('java.lang.Integer', [3])],425 ["java.lang.Integer"]) == 22426 assert test_agent.__call_instance_method__(test_instance.id, "uu", [test_agent.new_instance("int", [3])],427 ["java.lang.Integer"]) == 22428429 # func return an array430 arr = test_agent.__call_instance_method__(test_instance.id, "getArr", ["mys"], ["java.lang.String"])431 assert isinstance(arr, Array)432 assert arr.length() == 3433 assert len(arr) == 3434 assert "[1, 2, 3]" == str(arr)435 for i in range(3):436 assert i + 1 == arr[i]437438 arr = test_agent.__call_instance_method__(test_instance.id, "getArr2", ['3'], ["char"])439 assert isinstance(arr, Array)440 assert "[[1], [2, 3], [3]]" == str(arr)441442 arr = test_agent.__call_instance_method__(test_instance.id, "getArr3", [4], ["short"])443 assert isinstance(arr, Array)444 assert "[[[1, 2]], [[3, 4]]]" == str(arr)445446 # func get an array as param447 assert test_agent.__call_instance_method__(test_instance.id, "a1", [[3, 2, 1]], ["int[]"]) == 3448449 arr = test_agent.new_array("int[][]", [[18, 2, 3], [12, 1, 1], [2, 2, 2]])450 assert test_agent.__call_instance_method__(test_instance.id, "a2", [arr], ["int[][]"]) == 12451 assert test_agent.__call_instance_method__(test_instance.id, "a2", [[[18, 2, 3], [12, 1, 1], [2, 2, 2]]],452 ["int[][]"]) == 12453 assert test_agent.__call_instance_method__(test_instance.id, "a3", [[[[1, 1], [2, 2]], [[3, 3], [4, 4]]]],454 ["int[][][]"]) == 4455 assert test_agent.__call_instance_method__(test_instance.id, "arrayFunc", [[1, 2, 3], 1.5],456 ["int[]", "double"]) == 9457 assert test_agent.__call_instance_method__(test_instance.id, "arrayFunc",458 [[test_agent.new_instance('java.lang.Integer', [1]),459 test_agent.new_instance('java.lang.Integer', [2]),460 test_agent.new_instance('java.lang.Integer', [3])],461 test_agent.new_instance('java.lang.Double', [1.5])],462 ["java.lang.Integer[]", "java.lang.Double"]) == 2463464 assert test_agent.__call_instance_method__(test_instance.id, "darrayFunc", [[["a", "b"], ["c"], ["d", "e", "f"]]],465 ["java.lang.String[][]"]) == 'abcdef'466467468def test_create_array_2d(test_agent):469 row1 = test_agent.new_array("int[]", [1, 2])470 row2 = test_agent.new_array("int[]", [3, 4])471 arr = test_agent.new_array("int[][]", [row1, row2, [5, 6]])472 assert arr.class_name == "int[][]"473 assert '[[1, 2], [3, 4], [5, 6]]' == str(arr)474 row2[1] = 8475 assert '[[1, 2], [3, 8], [5, 6]]' == str(arr)476 arr[0][1] = 8477 assert '[[1, 8], [3, 8], [5, 6]]' == str(arr)478479 arr = test_agent.new_array('int[][]', [[1, 2], [3, 4]])480 assert isinstance(arr, Array)481 assert arr.class_name == "int[][]"482 assert "[[1, 2], [3, 4]]" == str(arr)483484 arr = test_agent.new_array("float[][]", [[], []])485 arr[0] = [3, 2]486 assert '[[3, 2], []]' == str(arr)487 arr[1] = [9, 2, 3]488 assert '[[3, 2], [9, 2, 3]]' == str(arr)489 arr[0] = [-1, 0, 888]490 assert '[[-1, 0, 888], [9, 2, 3]]' == str(arr)491492493def test_create_array_complex(test_agent):494 size = 3495 arr = test_agent.new_array("double[][][]", [[[0], [0], [0]], [[0], [0], [0]], [[0], [0], [0]]])496 assert arr.class_name == "double[][][]"497 for i in range(size):498 for j in range(size):499 arr[i][j][0] = 1500501 s = 0502 for i in range(size):503 for j in range(size):504 s += arr[i][j][0]505506 assert s == 9507508 size = 2509 arr = test_agent.new_array('java.lang.String[][][]', [[[]], [[]]])510 assert arr.class_name == "java.lang.String[][][]"511 assert '[[[]], [[]]]' == str(arr)512 for i in range(len(arr)):513 arr[i] = [['a', 'a']] * size514515 assert len(arr) == 2516 assert len(arr[0]) == 2517 assert len(arr[0][0]) == 2518519 s = ''520 for i in range(len(arr)):521 for j in range(len(arr[i])):522 for k in range(len(arr[i][j])):523 s += arr[i][j][k]524525 assert s == 'a' * size * size * size526527528def test_create_instance_different_ctors(test_agent):529 instance = test_agent.new_instance(TEST_APP_SAMPLE_CLASS)530 assert test_agent.__get_field_value__(TEST_APP_SAMPLE_CLASS, "s", instance.id) == "empty"531532 instance = test_agent.new_instance(TEST_APP_SAMPLE_CLASS, [3])533 assert test_agent.__get_field_value__(TEST_APP_SAMPLE_CLASS, "s", instance.id) == "i1"534535 instance = test_agent.new_instance(TEST_APP_SAMPLE_CLASS, [3])536 assert test_agent.__get_field_value__(TEST_APP_SAMPLE_CLASS, "s", instance.id) == "i1"537538 instance = test_agent.new_instance(TEST_APP_SAMPLE_CLASS, [test_agent.new_instance('java.lang.Integer', [3])])539 assert test_agent.__get_field_value__(TEST_APP_SAMPLE_CLASS, "s", instance.id) == "i2"540541 instance = test_agent.new_instance(TEST_APP_SAMPLE_CLASS, [test_agent.new_instance('java.lang.Integer', [3])])542 assert test_agent.__get_field_value__(TEST_APP_SAMPLE_CLASS, "s", instance.id) == "i2"543544 instance = test_agent.new_instance(TEST_APP_SAMPLE_CLASS, ["3"], ['java.lang.String'])545 assert test_agent.__get_field_value__(TEST_APP_SAMPLE_CLASS, "s", instance.id) == "3"546547 instance = test_agent.new_instance(TEST_APP_SAMPLE_CLASS,548 [1, 1, '1', test_agent.new_instance('java.lang.String', ["3"]), False, 1, 1,549 9.1],550 ['int', 'double', 'char', 'java.lang.String', 'boolean', 'byte', 'long',551 'float'])552 assert test_agent.__get_field_value__(TEST_APP_SAMPLE_CLASS, "s", instance.id) == "s1"553554 instance = test_agent.new_instance(TEST_APP_SAMPLE_CLASS, [1, 1, '1', '1', False, 1, 1, 1],555 ['java.lang.Integer', 'java.lang.Double', 'java.lang.Character',556 'java.lang.String', 'java.lang.Boolean', 'java.lang.Byte', 'java.lang.Long',557 'java.lang.Float'])558 assert test_agent.__get_field_value__(TEST_APP_SAMPLE_CLASS, "s", instance.id) == "s2"559560 arr = test_agent.new_array('int[]', [2, 3])561 instance = test_agent.new_instance(TEST_APP_SAMPLE_CLASS, [arr], ['int[]'])562 assert test_agent.__get_field_value__(TEST_APP_SAMPLE_CLASS, "sum", instance.id) == 5563564 instance = test_agent.new_instance(TEST_APP_SAMPLE_CLASS, [[1, 2]], ['int[]'])565 assert test_agent.__get_field_value__(TEST_APP_SAMPLE_CLASS, "sum", instance.id) == 3566567 arr = test_agent.new_array('int[][]', [[1, 2], [3, 3]])568 instance = test_agent.new_instance(TEST_APP_SAMPLE_CLASS, [arr], ['int[][]'])569 assert test_agent.__get_field_value__(TEST_APP_SAMPLE_CLASS, "sum", instance.id) == 9570571 instance = test_agent.new_instance(TEST_APP_SAMPLE_CLASS, [[[1, 2], [3, 2]]], ['int[][]'])572 assert test_agent.__get_field_value__(TEST_APP_SAMPLE_CLASS, "sum", instance.id) == 8573574 row1 = test_agent.new_array("int[]", [1, 2])575 row2 = test_agent.new_array("int[]", [3, 4])576 arr = test_agent.new_array("int[][]", [row1, row2, [5, 6]])577578 instance = test_agent.new_instance(TEST_APP_SAMPLE_CLASS, [arr], ['int[][]'])579 assert test_agent.__get_field_value__(TEST_APP_SAMPLE_CLASS, "sum", instance.id) == 21580581582def test_create_instance_exception(test_agent):583 for s in ["int[]", "java.lang.Integer[][]"]:584 with pytest.raises(ValueError, match=r".*array.*"): ...

Full Screen

Full Screen

adult_actions.py

Source:adult_actions.py Github

copy

Full Screen

1import numpy as np2from ..action import Action3from sequential.adult.adult_constraints import (4 AgeOnlyIncreaseAndInBounds,5 EducationOnlyIncreaseAndInBounds,6 WorkclassInBounds,7 WorkHrsInBounds,8 OccupationInBounds,9 CapitalInBounds,10)11from sequential.adult.adult_costs import (12 IncreaseAgeCosts,13 IncreaseEducationCosts,14 ChangeWorkHrsCosts,15 ChangeCategoricalCosts,16 IncreaseCapitalGainCosts,17)18class IncreaseAge(Action):19 def __init__(20 self,21 action_id: int,22 initial_instance,23 feature_idx: int,24 problem,25 dependency_graph=None,26 *args,27 **kwargs,28 ):29 super().__init__(30 action_id=action_id,31 feature_idx=feature_idx,32 initial_instance=initial_instance.copy(),33 problem=problem,34 action_name="Wait X Years",35 is_categorical=False,36 description="Increases the feature age by the respective value.",37 feature_name="Age",38 dependency_graph=dependency_graph,39 *args,40 **kwargs,41 )42 self.costs = IncreaseAgeCosts(problem.feature, dependency_graph)43 def _get_costs(self, old_state, new_state):44 return self.costs.get_costs(old_state, new_state)45 def _tweak(self, new_value, old_instance) -> np.ndarray:46 new_instance = old_instance.copy()47 new_instance[self.feature_idx] = new_value48 return new_instance49 def _penalty(self, old_instance, new_instance, change_values) -> float:50 tweak_value = change_values[self.feature_idx]51 penalty = max(1.0, abs(tweak_value))52 constraint = AgeOnlyIncreaseAndInBounds(53 initial_value=self.initial_value,54 max_value=68, # we assume below is retirement55 feature_idx=self.feature_idx,56 )57 if not constraint.validate(old_instance, new_instance):58 return penalty59 return 0.060class ChangeEducation(Action):61 def __init__(62 self,63 action_id: int,64 initial_instance,65 feature_idx: int,66 problem,67 dependency_graph=None,68 *args,69 **kwargs,70 ):71 super().__init__(72 action_id=action_id,73 feature_idx=feature_idx,74 initial_instance=initial_instance.copy(),75 problem=problem,76 action_name="Change Education",77 is_categorical=True,78 description="Changes the education level with respect to the intial one. I.e. education can only increase.",79 feature_name="Education",80 dependency_graph=dependency_graph,81 *args,82 **kwargs,83 )84 self.general_costs = [85 0.0, # nothing to School86 3.0, # School to HS87 3.0, # HS to college88 1.0, # college to prof-school89 2.0, # prof-school to assoc90 3.5, # assoc to bachelors91 2.5, # bachelors to masters92 5.0, # masters to doctorate93 ]94 self.education_level_order = [0, 1, 2, 3, 4, 5, 6, 7]95 self.education_costs = IncreaseEducationCosts(problem.feature, dependency_graph)96 self.age_costs = IncreaseAgeCosts(problem.feature, dependency_graph)97 def _get_costs(self, old_state, new_state):98 return self.education_costs.get_costs(99 old_state, new_state100 ) + self.age_costs.get_costs(old_state, new_state)101 def _tweak(self, new_value, old_instance) -> np.ndarray:102 new_instance = old_instance.copy()103 # update education level104 new_instance[self.feature_idx] = new_value105 if new_instance[self.feature_idx] == old_instance[self.feature_idx]:106 return old_instance107 # applying an action must always have an effect!108 # * This is already checked in the .tweak meta method109 assert new_instance[self.feature_idx] != old_instance[self.feature_idx]110 # update age111 current_level = self.education_level_order.index(old_instance[self.feature_idx])112 age_increase = (113 sum(self.general_costs[current_level + 1 : int(new_value) + 1])114 ) + 1.0115 work_hrs = np.interp(116 old_instance[self.problem.feature["hours_per_week"]], [0, 30], [0.5, 1]117 )118 new_instance[self.problem.feature["age"]] += age_increase * work_hrs119 # applying an action must always have an effect!120 assert (121 new_instance[self.problem.feature["age"]]122 != old_instance[self.problem.feature["age"]]123 )124 # # ! Testing125 # # when increasing degree, you lose your job126 # new_instance[self.problem.feature["workclass"]] = 0.0127 # # assert (128 # # new_instance[self.problem.feature["workclass"]]129 # # != old_instance[self.problem.feature["workclass"]]130 # # )131 # new_instance[self.problem.feature["occupation"]] = 0.0132 # # assert (133 # # new_instance[self.problem.feature["occupation"]]134 # # != old_instance[self.problem.feature["occupation"]]135 # # )136 # new_instance[self.problem.feature["hours_per_week"]] = 0.0137 return new_instance138 def _penalty(self, old_instance, new_instance, change_values) -> float:139 former_level = self.education_level_order.index(old_instance[self.feature_idx])140 penalty = 1.0141 constraint = EducationOnlyIncreaseAndInBounds(142 initial_value=self.initial_value,143 allowed_values=self.education_level_order[former_level:],144 feature_idx=self.feature_idx,145 ).AND(146 AgeOnlyIncreaseAndInBounds(147 initial_value=old_instance[self.problem.feature["age"]],148 max_value=68, # we assume below is retirement,149 feature_idx=self.problem.feature["age"],150 )151 )152 if not constraint.validate(old_instance, new_instance):153 return penalty154 return 0.0155class IncreaseCapital(Action):156 def __init__(157 self,158 action_id: int,159 initial_instance,160 feature_idx: int,161 problem,162 dependency_graph=None,163 *args,164 **kwargs,165 ):166 super().__init__(167 action_id=action_id,168 feature_idx=feature_idx,169 initial_instance=initial_instance.copy(),170 problem=problem,171 action_name="Increase Capital",172 is_categorical=False,173 description="Increases the capital gain.",174 feature_name="Capital-gain",175 dependency_graph=dependency_graph,176 *args,177 **kwargs,178 )179 self.capital_gain_costs = IncreaseCapitalGainCosts(180 problem.feature, dependency_graph181 )182 self.age_costs = IncreaseAgeCosts(problem.feature, dependency_graph)183 def _get_costs(self, old_state, new_state):184 return self.capital_gain_costs.get_costs(185 old_state, new_state186 ) # + self.age_costs.get_costs(old_state, new_state)187 def _tweak(self, new_value, old_instance) -> np.ndarray:188 new_instance = old_instance.copy()189 new_instance[self.feature_idx] = new_value190 if new_instance[self.feature_idx] == old_instance[self.feature_idx]:191 return old_instance192 # applying an action must always have an effect193 # * This is already checked in the .tweak meta method194 assert new_instance[self.feature_idx] != old_instance[self.feature_idx]195 # capital_change = abs(new_value - old_instance[self.feature_idx])196 # # 2 years for each 1000$ more197 # age_increase = capital_change / 500198 # new_instance[self.problem.feature["age"]] += age_increase199 # # applying an action must always have an effect!200 # assert (201 # new_instance[self.problem.feature["age"]]202 # != old_instance[self.problem.feature["age"]]203 # )204 return new_instance205 def _penalty(self, old_instance, new_instance, change_values) -> float:206 tweak_value = change_values[self.feature_idx]207 penalty = max(1.0, abs(tweak_value))208 constraint = CapitalInBounds(209 lower_bound=0, upper_bound=99999, feature_idx=self.feature_idx210 )211 # ).AND(212 # AgeOnlyIncreaseAndInBounds(213 # initial_value=old_instance[self.problem.feature["age"]],214 # max_value=68, # we assume below is retirement,215 # feature_idx=self.problem.feature["age"],216 # )217 # )218 if not constraint.validate(old_instance, new_instance):219 return penalty220 return 0.0221class ChangeMaritalStatus(Action):222 def __init__(223 self,224 action_id: int,225 initial_instance,226 feature_idx: int,227 problem,228 dependency_graph=None,229 *args,230 **kwargs,231 ):232 super().__init__(233 action_id=action_id,234 feature_idx=feature_idx,235 initial_instance=initial_instance.copy(),236 problem=problem,237 action_name="Change Marital Status",238 is_categorical=True,239 description="Changes the marital status with respect to impossible actions, e.g. divorce without prior marriage.",240 feature_name="Marital-status",241 dependency_graph=dependency_graph,242 *args,243 **kwargs,244 )245 self.costs = ChangeCategoricalCosts(246 self.feature_idx, problem.feature, dependency_graph247 )248 def _get_costs(self, old_state, new_state):249 return self.costs.get_costs(old_state, new_state)250 def _tweak(self, new_value, old_instance) -> np.ndarray:251 new_instance = old_instance.copy()252 new_instance[self.feature_idx] = new_value253 return new_instance254 def _penalty(self, old_instance, new_instance, change_values) -> float:255 new_value = new_instance[self.feature_idx]256 former_value = old_instance[self.feature_idx]257 assume_same = False258 shared_weight = 5.0259 infeasible = 20.0260 # TODO write this as a constraint object261 if former_value == 0: # is divorced262 if new_value == 1: # change to married263 return shared_weight if assume_same else 5.0264 elif new_value == 3: # change to single265 return shared_weight if assume_same else 1.0266 else:267 return infeasible268 elif former_value == 1: # is married269 if new_value == 0: # change to divorced270 return shared_weight if assume_same else 5.0271 elif new_value == 2: # change to separated272 return shared_weight if assume_same else 3.0273 elif new_value == 3: # change to single274 return shared_weight if assume_same else 5.0275 elif new_value == 4: # change to widowed276 return shared_weight if assume_same else 10.0277 else:278 return infeasible279 elif former_value == 2: # is separated280 if new_value == 0: # change to divorced281 return shared_weight if assume_same else 3.0282 elif new_value == 1: # change to married283 return shared_weight if assume_same else 3.0284 elif new_value == 3: # change to single285 return shared_weight if assume_same else 3.0286 elif new_value == 4: # change to widowed287 return shared_weight if assume_same else 10.0288 else:289 return infeasible290 elif former_value == 3: # is Single291 if new_value == 1: # change to married292 return shared_weight if assume_same else 5.0293 else:294 return infeasible295 elif former_value == 4: # is Widowed296 if new_value == 1: # change to married297 return shared_weight if assume_same else 8.0298 elif new_value == 3: # change to single299 return shared_weight if assume_same else 1.0300 else:301 return infeasible302 else:303 return infeasible304class ChangeWorkHours(Action):305 def __init__(306 self,307 action_id: int,308 initial_instance,309 feature_idx: int,310 problem,311 dependency_graph=None,312 *args,313 **kwargs,314 ):315 super().__init__(316 action_id=action_id,317 feature_idx=feature_idx,318 initial_instance=initial_instance.copy(),319 problem=problem,320 action_name="Change Work Hours",321 is_categorical=False,322 description="Change the working hours.",323 feature_name="Working-hours",324 dependency_graph=dependency_graph,325 *args,326 **kwargs,327 )328 self.costs = ChangeWorkHrsCosts(problem.feature, dependency_graph)329 def _get_costs(self, old_state, new_state):330 return self.costs.get_costs(old_state, new_state)331 def _tweak(self, new_value, old_instance) -> np.ndarray:332 new_instance = old_instance.copy()333 new_instance[self.feature_idx] = new_value334 return new_instance335 def _penalty(self, old_instance, new_instance, change_values) -> float:336 tweak_value = change_values[self.feature_idx]337 penalty = max(1.0, abs(tweak_value))338 constraint = WorkHrsInBounds(339 lower_bound=0, upper_bound=80, feature_idx=self.feature_idx340 )341 if not constraint.validate(old_instance, new_instance):342 return penalty343 return 0.0344class ChangeOccupation(Action):345 def __init__(346 self,347 action_id: int,348 initial_instance,349 feature_idx: int,350 problem,351 dependency_graph=None,352 *args,353 **kwargs,354 ):355 super().__init__(356 action_id=action_id,357 feature_idx=feature_idx,358 initial_instance=initial_instance.copy(),359 problem=problem,360 action_name="Change Occupation",361 is_categorical=True,362 description="Changes the occupation.",363 feature_name="Occupation",364 dependency_graph=dependency_graph,365 *args,366 **kwargs,367 )368 self.costs = ChangeCategoricalCosts(369 self.feature_idx, problem.feature, dependency_graph370 )371 def _get_costs(self, old_state, new_state):372 return self.costs.get_costs(old_state, new_state)373 def _tweak(self, new_value, old_instance) -> np.ndarray:374 new_instance = old_instance.copy()375 new_instance[self.feature_idx] = new_value376 return new_instance377 def _penalty(self, old_instance, new_instance, change_values) -> float:378 return 0.0379class ChangeWorkclass(Action):380 def __init__(381 self,382 action_id: int,383 initial_instance,384 feature_idx: int,385 problem,386 dependency_graph=None,387 *args,388 **kwargs,389 ):390 super().__init__(391 action_id=action_id,392 feature_idx=feature_idx,393 initial_instance=initial_instance.copy(),394 problem=problem,395 action_name="Change Workclass",396 is_categorical=True,397 description="Changes the workclass.",398 feature_name="Workclass",399 dependency_graph=dependency_graph,400 *args,401 **kwargs,402 )403 self.costs = ChangeCategoricalCosts(404 self.feature_idx, problem.feature, dependency_graph405 )406 def _get_costs(self, old_state, new_state):407 return self.costs.get_costs(old_state, new_state)408 def _tweak(self, new_value, old_instance) -> np.ndarray:409 new_instance = old_instance.copy()410 new_instance[self.feature_idx] = new_value411 return new_instance412 def _penalty(self, old_instance, new_instance, change_values) -> float:413 return 0.0414class QuitJob(Action):415 def __init__(416 self,417 action_id: int,418 initial_instance,419 feature_idx: int,420 problem,421 dependency_graph=None,422 *args,423 **kwargs,424 ):425 super().__init__(426 action_id=action_id,427 feature_idx=feature_idx,428 initial_instance=initial_instance.copy(),429 problem=problem,430 action_name="Quit Job",431 is_categorical=True,432 description="",433 feature_name="Occupation",434 dependency_graph=dependency_graph,435 *args,436 **kwargs,437 )438 self.costsOccupation = ChangeCategoricalCosts(439 problem.feature["occupation"], problem.feature, dependency_graph440 )441 self.costsWorkclass = ChangeCategoricalCosts(442 problem.feature["workclass"], problem.feature, dependency_graph443 )444 self.costsHrsPerWeek = ChangeWorkHrsCosts(problem.feature, dependency_graph)445 def _get_costs(self, old_state, new_state):446 return (447 self.costsOccupation.get_costs(old_state, new_state)448 + self.costsWorkclass.get_costs(old_state, new_state)449 + self.costsHrsPerWeek.get_costs(old_state, new_state)450 )451 def _tweak(self, new_value, old_instance) -> np.ndarray:452 new_instance = old_instance.copy()453 new_instance[self.problem.feature["workclass"]] = 0.0454 new_instance[self.problem.feature["occupation"]] = 0.0455 new_instance[self.problem.feature["hours_per_week"]] = 0.0456 return new_instance457 def _penalty(self, old_instance, new_instance, change_values) -> float:458 constraint = WorkHrsInBounds(459 lower_bound=0,460 upper_bound=80,461 feature_idx=self.problem.feature["hours_per_week"],462 )463 if not constraint.validate(old_instance, new_instance):464 return 1.0465 return 0.0466actions = {467 0: IncreaseAge,468 1: ChangeEducation,469 2: IncreaseCapital,470 3: ChangeMaritalStatus,471 4: ChangeWorkHours,472 5: ChangeOccupation,473 6: ChangeWorkclass,474 7: QuitJob,...

Full Screen

Full Screen

serializers.py

Source:serializers.py Github

copy

Full Screen

1from django.db import transaction2from main.models import Account, Transaction3from rest_framework import serializers4class AccountSerializer(serializers.ModelSerializer):5 class Meta:6 model = Account7 fields = ['id', 'type', 'name', 'current_month_amount', 'actual_amount', 'planned_amount', 'get_fill_percent', 'get_absolute_url']8class TransactionSerializer(serializers.ModelSerializer):9 class Meta:10 model = Transaction11 fields = ['id', 'source', 'destination', 'amount', 'tags', 'comment', 'date']12 @transaction.atomic13 def create(self, validated_data):14 instance = super().create(validated_data)15 if instance.source.type == Account.DEPOSIT:16 instance.source.actual_amount -= instance.amount17 instance.source.save()18 if instance.destination.type == Account.DEPOSIT:19 instance.destination.actual_amount += instance.amount20 instance.destination.save()21 22 return instance23 @transaction.atomic24 def update(self, instance, validated_data):25 prev_amount = instance.amount26 prev_source = instance.source27 prev_destination = instance.destination28 new_instance = super().update(instance, validated_data)29 if new_instance.source == prev_source:30 if new_instance.source.type == Account.DEPOSIT:31 new_instance.source.actual_amount -= new_instance.amount - prev_amount32 new_instance.source.save()33 else:34 prev_source.actual_amount += prev_amount35 prev_source.save()36 new_instance.source.actual_amount -= new_instance.amount37 new_instance.source.save()38 if new_instance.destination == prev_destination:39 if new_instance.destination.type == Account.DEPOSIT:40 new_instance.destination.actual_amount += new_instance.amount - prev_amount41 new_instance.destination.save()42 else:43 prev_destination.actual_amount -= prev_amount44 prev_destination.save()45 new_instance.destination.actual_amount += new_instance.amount46 new_instance.destination.save()47 48 return new_instance49class TransactionListSerializer(serializers.ModelSerializer):50 source = AccountSerializer(read_only=True)51 destination = AccountSerializer(read_only=True)52 class Meta:53 model = Transaction...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run localstack automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful