def test_add(self): """ Test add function from class Calculator """ calcu = Calculator() result = calcu.add(3, 4) self.assertEqual(result, 7)
def check(x, ks): if not ks: return "empty sequence" if len(ks) > 100000: return "sequence too long." ka = ks.split(',') try: c = Calculator() for k in ka: c.click(k) if c.equal(x): return "passed" else: return "your result " + str( c.v) + " is not equal to " + str(x) + " (max_error = 1e-5)." except CalculatorUnknownKey: return "there're unknown key(s)." except ValueError: return "value error" except ZeroDivisionError: return "float division by zero" except Exception as e: print(e) return "system error"
def process_request(self, message: str) -> str: """Processes HTTP request and returns response.""" parser = HTTPParser() response = HTTPResponse() calc = Calculator() request = parser.parse_request(message) # Invalid request (no expression sent) if (not request["params"] or "expression" not in request["params"]): print("Request is invalid. Missing parameters.") return response.build_response(status=406, data="-1") expression = request["params"]["expression"][0] print("{}Expression received:{} {}".format(bcolors.OKBLUE, bcolors.ENDC, expression)) # Evaluate the expression try: result = calc.evaluate(expression) print("{}Expression valid{}, result = {}".format( bcolors.OKGREEN, bcolors.ENDC, result)) return response.build_response(status=200, data=result) # Send error message if not valid except Exception as exc: print("{}An exception occurred:{} {} ({})".format( bcolors.FAIL, bcolors.ENDC, str(exc), type(exc).__name__)) return response.build_response(status=406, data="-1") return ""
class CalculatorTest(unittest.TestCase): def setUp(self): self.calc = Calculator() def test_last_answer_init(self): value = self.calc.last_answer self.assertEqual(value, 0.0, FAILURE) def test_add(self): value = self.calc.add(NUMBER_1, NUMBER_2) self.assertEqual(value, 6.0, FAILURE) self.assertEqual(value, self.calc.last_answer, FAILURE) def test_subtract(self): value = self.calc.subtract(NUMBER_1, NUMBER_2) self.assertEqual(value, 1.0, FAILURE) self.assertEqual(value, self.calc.last_answer, FAILURE) def test_subtract_negative(self): value = self.calc.subtract(NUMBER_2, NUMBER_1) self.assertEqual(value, -1.0, FAILURE) self.assertEqual(value, self.calc.last_answer, FAILURE) def test_multiply(self): value = self.calc.multiply(NUMBER_1, NUMBER_2) self.assertEqual(value, 6.0, FAILURE) self.assertEqual(value, self.calc.last_answer, FAILURE) def test_divide(self): value = self.calc.divide(NUMBER_1, NUMBER_2) self.assertEqual(value, 1.5, FAILURE) self.assertEqual(value, self.calc.last_answer, FAILURE) def test_divide_by_zero(self): self.assertRaises(ZeroDivisionError, self.calc.divide, NUMBER_1, 0)
def test_add(self, input_a, input_b, expected_result): print("test_add()") print("input_a", input_a) print("input_b", input_b) print("expected_result", expected_result) calc = Calculator() self.assertEqual(calc.add(input_a, input_b), expected_result)
def repl(): calc = Calculator() while True: line = input('> ') try: print(calc.parse(line)) except SyntaxError as e: print(f'Syntax Error: {e.msg}')
def main(): """ main function realization of calculation of simples operations """ #pass print(__name__) calc = Calculator() print(calc.add())
def _input_amount(self): amount = rlinput("\n" "金額を入力してください。四則演算の計算式でも構いません。\n" "> ") if Checkers.isvalid_amount(amount): calculator = Calculator() self.amount = str(calculator.calc(amount)) self._confirm() else: print("入力が不正です。") self._input_amount()
def _modify_amount(self, record_id): amount = rlinput("\n" "金額を入力してください。四則演算の計算式でも構いません。\n" "> ", self.amount) if Checkers.isvalid_amount(amount): calculator = Calculator() self.amount = str(calculator.calc(amount)) self._confirm_modification(record_id) else: print("入力が不正です。") self._modify_amount(record_id)
def caclulate(): calc = Calculator() data = request.json try: equation = data['to_calculate'] result = calc.calculate(equation) except KeyError: return make_response({"error": "Missing required parameter 'to_caclulate'"}, 400) except: return make_response({"error": "Could not process equation"}, 400) return make_response({'result': result}, 200)
class CalcTestCase(unittest.TestCase): def setUp(self): self.C = Calculator() def test_multiplication_with_ints(self): self.assertEqual(self.C.multiply(5, 5), 25) def test_add_with_ints(self): self.assertEqual(self.C.add(1, 5), 6) self.assertEqual(self.C.add(2, 2), 4) def test_div(self): self.assertEqual(self.C.div(10, 2), 5)
class Calc1TestCase(unittest.TestCase): def setUp(self): self.calc = Calculator(1) def tearDown(self): self.calc = None def testAdd1(self): assert self.calc.add(1) == 2, "addition is wrong" def testAdd2(self): assert self.calc.add(2) == 3, "addition is wrong" def testSub(self): assert self.calc.sub(1) == 0, "substraction is wrong"
class Calc0TestCase(unittest.TestCase): def setUp(self): self.calc = Calculator(0) def tearDown(self): self.calc = None def testAdd1(self): assert self.calc.add(1) == 1, "addition is wrong" def testAdd2(self): assert self.calc.add(2) == 2, "addition is wrong" def testSub(self): assert self.calc.sub(1) == -1, "substraction is wrong"
def calc(self, i): self.setWindowTitle("Calculator") if i == "=": formel = self.textLine.text().replace("=", "") clc = Calculator() try: r = clc.worker(formel) except ZeroDivisionError as ident: r = "" self.setWindowTitle("Zero Divison Error") self.textLine.setText(str(r))
def __init__(self, log, id, mode, memOC, coreUC, fanSpeed, steps, powerLimit, nbrOfShares, nbrOfDatapoints, marginInMH, powerCost, dollarPerMHash): # basics self.id = id self.log = log self.existing = False self.calc = Calculator(marginInMH, powerCost, dollarPerMHash) self.nvTool = NVTool(self.log, self.id) # overall Tuning Variables self.maxMemClockFound = False self.minCoreClockFound = False self.minPowerLimitFound = False # HW settings self.fanSpeed = fanSpeed self.memOC = memOC self.coreUC = coreUC self.powerLimit = powerLimit # tuning variables self.mode = mode self.steps = steps self.nbrOfShares = nbrOfShares self.margin = marginInMH self.nbrOfDatapoints = nbrOfDatapoints ## DATA TO CALCULATE ON ## # speed data via mining software self.currentMinerData = [] self.lastMinerData = [] self.overheatingThreshold = 5 self.thermalLimitReached = 0 # hw data of GPU via nvidia-smi self.currentHWData = [] self.lastHWData = [] ## HELPER VARIABLES ## self.dataSummary = [] self.maxSpeed = 0.0 self.defaultPowerLimit = 0.0 self.tuningTries = 0 ## TUNING PROCESS VARIABLES self.requiresRestart = False self.tuningDone = False self.found = self.Initialize()
class CalculatorLibrary(object): def __init__(self): self.calc = Calculator() def calculate(self, input_a, input_b, operation): if operation == "+": return self.calc.add(input_a, input_b) elif operation == "-": return self.calc.sub(input_a, input_b) elif operation == "*": return self.calc.mul(input_a, input_b) elif operation == "/": return self.calc.div(input_a, input_b) else: raise ValueError("wrong operation")
def test_sum_list(self, li=[ 1, 2, 3, 4, -5, 6, 7, 8, -9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]): self.assertEqual(182, Calculator.sum_list(self, li))
def test_plus(self): cases = [ { 'first': 100, 'second': 200, 'expected': 300, }, { 'first': 0, 'second': 0, 'expected': 0, }, { 'first': -100, 'second': 200, 'expected': 100, }, { 'first': -5, 'second': -9, 'expected': -14, }, ] for case in cases: first = case['first'] second = case['second'] self.assertEqual(case['expected'], Calculator.plus(first, second))
def test_odd_list(self, li=[ 1, 2, 3, 4, -5, 6, 7, 8, -9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]): self.assertEqual([1, 3, -5, 7, -9, 11, 13, 15, 17, 19], Calculator.odd_list(self, li))
def test_even_list(self, li=[ 1, 2, 3, 4, -5, 6, 7, 8, -9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]): self.assertEqual([2, 4, 6, 8, 10, 12, 14, 16, 18, 20], Calculator.even_list(self, li))
class CalculatorTest(unittest.TestCase): Calculator = Calculator() def test_add(self): self.assertEqual(4, self.Calculator.add(2, 2)) self.assertEqual(-2, self.Calculator.add(3, -5)) self.assertEqual(5.2, self.Calculator.add(3, 2.2)) def test_multiple(self): self.assertEqual(30, self.Calculator.multiple(5, 6)) self.assertEqual(-30, self.Calculator.multiple(-5, 6)) self.assertEqual(66.6, self.Calculator.multiple(3, 22.2)) def test_subtract(self): self.assertEqual(2, self.Calculator.subtract(4, 2)) self.assertEqual(-2, self.Calculator.subtract(2, 4)) self.assertEqual(6.7, self.Calculator.subtract(10, 3.3)) def test_divide(self): self.assertEqual(3, self.Calculator.divide(9, 3)) self.assertEqual(-3, self.Calculator.divide(-9, 3)) self.assertEqual(3.5, self.Calculator.divide(10.5, 3)) with self.assertRaises(ZeroDivisionError): self.Calculator.divide(2, 0) def test_x_and_y_are_not_numbers(self): self.assertRaises(ValueError, self.Calculator.add, 'two', 'three') self.assertRaises(ValueError, self.Calculator.add, 'two', 3) self.assertRaises(ValueError, self.Calculator.add, 2, 'three')
def test_neg(self, li=[ 1, 2, 3, 4, -5, 6, 7, 8, -9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]): #self.assertEqual([1, 2, 3, 4, -5, 6, 7, 8, -9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], Calculator.neg(self, li)) self.assertEqual([-5, -9], Calculator.neg(self, li))
class TestExample(unittest.TestCase): def setUp(self): self.calc = Calculator() def should_return_correct_result(self): result = self.calc.add(1, 2) self.assertEqual(3, result)
def main(): print("Hello! Welcome~") print("Please enter the kind of function you would like to use.") print("Currently supported functions are: \n" + list_to_string(FUNCTIONS_SUPPORTED)) sel = input("Select an option: ") # Apply logic based on selection if (sel == "add"): print("Specify two numbers, a and b") a = input("a: ") b = input("b: ") # Cast numbers to float via function, then add res = Calculator.add(float(a), float(b)) print("Result: " + str(res)) elif (sel == "sub"): print("Specify two numbers, a and b") a = input("a: ") b = input("b: ") res = Calculator.sub(float(a), float(b)) print("Result " + str(res)) elif (sel == "mul"): print("Specify two numbers, a and b") a = input("a: ") b = input("b: ") res = Calculator.mul(float(a), float(b)) print("Result " + str(res)) elif (sel == "div"): print("Specify two numbers, a and b") a = input("a: ") b = input("b: ") res = Calculator.div(float(a), float(b)) print("Result " + str(res)) elif (sel == "power"): print("Specify two numbers, a and b") a = input("a: ") b = input("b: ") res = Calculator.power(float(a), float(b)) print("Result " + str(res)) else: print("Function \"" + sel + "\" not implemented.")
def test_calc_stats(): values = [6, 9, 15, -2, 92, 11] calc = Calculator(values) assert calc.min == -2 assert calc.max == 92 assert calc.len == 6 assert calc.avg == 21.833333333333332
def test_pos(self, li=[ 1, 2, 3, 4, -5, 6, 7, 8, -9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]): self.assertEqual( [1, 2, 3, 4, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], Calculator.pos(self, li))
def test_div(): calc = Calculator() assert calc.divide(5, 5) == 1 assert calc.divide(5, -5) == -1 assert calc.divide(5, 3) == 1 assert calc.divide(5, -3) == -2 assert calc.divide(5, '$') == 'invalid input' assert calc.divide(5, 0) == "Could not calcuate with given input"
def test_square_list(self, li=[ 1, 2, 3, 4, -5, 6, 7, 8, -9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]): self.assertEqual([ 2, 4, 6, 8, -10, 12, 14, 16, -18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40 ], Calculator.square_list(self, li))
def test_multiply_list(self, li=[ 1, 2, 3, 4, -5, 6, 7, 8, -9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]): self.assertEqual([ 5, 10, 15, 20, -25, 30, 35, 40, -45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100 ], Calculator.multiply_list(self, li, 5))
def test_calcs(version): print 'Prueba de calculos:' calcs = Calculator() calcs.load_xml(version) calcs.load_xsl('calculos.xsl') calcs.calc(xml) for x in calcs.get_calculations(): print x print 'Listo'
def test_power(self, li=[ 1, 2, 3, 4, -5, 6, 7, 8, -9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]): self.assertEqual([ 1, 32, 243, 1024, -3125, 7776, 16807, 32768, -59049, 100000, 161051, 248832, 371293, 537824, 759375, 1048576, 1419857, 1889568, 2476099, 3200000 ], Calculator.power(self, li, 5))
class TestCalculator(unittest.TestCase): def setUp(self): self.calc = Calculator() @patch("calc.Calculator.sum",return_value=9) def test_sum(self,sum): self.assertEqual(sum(2,3), 9) def test_sum1(self): answer = self.calc.sum(2, 4) self.assertEqual(answer, 6) def tearDown(self): pass
class CalcTestCase(unittest.TestCase): def setUp(self): self.calculator = Calculator() def test_adds_two_numbers(self): self.calculator.add(1,1) self.assertEqual(self.calculator.total, 2) @unittest.skip("Needs more work") def test_adds_single_number(self): calculator = Calculator() calculator.add(1) self.assertEqual(calculator.total, 1) @unittest.expectedFailure def test_divide_two_numbers(self): calculator = Calculator() calculator.divide(1,0)
class TestCalculator(unittest.TestCase): @classmethod def setUpClass(self): print("Set up class") self.calc = Calculator() # Create an instance of the calculator that can be used in all tests @classmethod def tearDownClass(self): print("Tear down class") def test_add(self): self.assertEqual(self.calc.add(2, 7), 9) # Write test methods for subtract, multiply, and divide def test_subtract(self): self.assertEqual(self.calc.subtract(7, 2), 5) def test_multiply(self): self.assertEqual(self.calc.multiply(2, 4), 8) def test_divide(self): self.assertEqual(self.calc.divide(8, 2), 4)
def set_declaracion(self, declaracion): self.declaracion = declaracion self.calcs = Calculator() if not self.calcs.load_xml(self.declaracion): ezGlade.DialogBox("ERROR: No se pudo cargar el XML de cálculos para " + self.declaracion.get_version(), "error") self.calcs = None return self.validations = Validator() if not self.validations.load_xml(self.declaracion): ezGlade.DialogBox("ERROR: No se pudo cargar el XML de validaciones para " + self.declaracion.get_version(), "error") self.validations = None return self.calcs.load_xsl() self.validations.load_xsl()
class CalculatorTest(unittest.TestCase): # init class calculator = Calculator() # test adder def test_add(self): self.assertEqual(4, self.calculator.add(2, 2)) self.assertEqual(3.2, self.calculator.add(1, 2.2)) # test subtracter def test_minus(self): self.assertEqual(2, self.calculator.minus(3, 1)) self.assertEqual(-2, self.calculator.minus(1, 3)) # test mult def test_multiple(self): self.assertEqual(12, self.calculator.multiple(3, 4)) self.assertEqual(13.5, self.calculator.multiple(3, 4.5)) # test div def test_divide(self): self.assertEqual(3, self.calculator.divide(9, 3))
class wndDeclaracion(ezGlade.BaseWindow): widget_container = dict() xml = None declaracion = None ref_data = None calcs = None validations = None def on_numericfield_changed(self, entry): text = entry.get_text() text = unicode(text).strip() entry.set_text(''.join([i for i in text if i in '0123456789.'])) def set_declaracion(self, declaracion): self.declaracion = declaracion self.calcs = Calculator() if not self.calcs.load_xml(self.declaracion): ezGlade.DialogBox("ERROR: No se pudo cargar el XML de cálculos para " + self.declaracion.get_version(), "error") self.calcs = None return self.validations = Validator() if not self.validations.load_xml(self.declaracion): ezGlade.DialogBox("ERROR: No se pudo cargar el XML de validaciones para " + self.declaracion.get_version(), "error") self.validations = None return self.calcs.load_xsl() self.validations.load_xsl() def load_widget_contribuyente(self, number, text, width, height, left, top, tooltip): entry = gtk.Entry(max=0) entry.set_size_request(width, height) entry.set_tooltip_text(tooltip) entry.set_editable(False) entry.modify_base(gtk.STATE_NORMAL, gtk.gdk.color_parse("#cccccc")) # color deshabilitado ;) entry.set_text(text) entry.set_property('xalign', 1) self.fixed1.put(entry, left, top) self.widget_container[number] = entry entry.show() def load_combo_custom_data(self, number, value, width, height, left, top, tooltip, lista_datos): combo = gtk.combo_box_new_text() combo.set_size_request(width, height) combo.set_tooltip_text(tooltip) list_store = gtk.ListStore(str, str) combo.set_model(list_store) for code, name in lista_datos: if value == code : list_store.append([name, code]) combo.set_active(0) self.fixed1.put(combo, left, top) self.widget_container[number] = combo combo.show() def load_combo_contribuyente(self, number, value, width, height, left, top, tooltip, ref_table): combo = gtk.combo_box_new_text() combo.set_size_request(width, height) combo.set_tooltip_text(tooltip) if ref_table != "-1": list_store = gtk.ListStore(str, str) combo.set_model(list_store) lista_datos = self.ref_data.get_data_list(ref_table) for code, name in lista_datos: if value == code : list_store.append([name, code]) combo.set_active(0) self.fixed1.put(combo, left, top) self.widget_container[number] = combo combo.show() def load_widgets_from_xml(self): contribuyente = self.declaracion.get_contribuyente() if contribuyente is None: ezGlade.DialogBox("No existen datos del contribuyente", "error") return tree = etree.parse(os.path.join('XML','CMPFRM.xml')) version = self.declaracion.get_codigo_version() if version is None: ezGlade.DialogBox("Código de formulario no definido", "error") return form = tree.find("version[@codigo='"+version+"']") if form is None: ezGlade.DialogBox("Error al cargar el formulario", "error") return self.widget_container = dict() y_scale = 10 x_scale = 12 start_top = 1200 font_factor = 1000 for c in form: numero = str(int(c.attrib.get("numero"))) # se eliminan ceros de la izq top = (int(c.attrib.get("top")) - start_top ) / y_scale left = int(c.attrib.get("left")) / x_scale width = int(c.attrib.get("width")) / x_scale height = int(c.attrib.get("height")) / y_scale label = c.attrib.get("etiqueta") editable = c.attrib.get("editable") tablaReferencial = c.attrib.get("tablaReferencial") mensajeAyuda = c.attrib.get("mensajeAyuda") tipoControl = c.attrib.get("tipoControl") colorLetra = c.attrib.get("colorLetra") fontSize = str(int(c.attrib.get("fontSize")) * font_factor) # campos escritos desde la configuracion if numero in [ '101', '102', '198', '201', '202', '31', '104' ]: if numero == '202': # razon social self.load_widget_contribuyente(numero, contribuyente.get_nombre(), width, height, left, top, mensajeAyuda) elif numero == '201': # RUC self.load_widget_contribuyente(numero, contribuyente.get_ruc(), width, height, left, top, mensajeAyuda) elif numero == '101': # mes self.load_combo_contribuyente(numero, self.declaracion.get_mes(), width, height, left, top, mensajeAyuda, tablaReferencial) elif numero == '102': # año self.load_combo_contribuyente(numero, self.declaracion.get_anio(), width, height, left, top, mensajeAyuda, tablaReferencial) elif numero == '198': # cedula rep. legal self.load_widget_contribuyente(numero, contribuyente.get_documento(), width, height, left, top, mensajeAyuda) elif numero == '31': # original o sustitutiva self.load_combo_custom_data(numero, self.declaracion.get_original(), width, height, left, top, mensajeAyuda, self.ref_data.get_ori_sus()) elif numero == '104': # formulario sustituye self.load_widget_contribuyente(numero, self.declaracion.get_sustituye(), width, height, left, top, mensajeAyuda) continue if tipoControl == "L": # etiqueta lbl = gtk.Label(label) color = RGBToHTMLColor(int(colorLetra)) lbl.set_markup('<span color="'+color+'" size="'+fontSize+'">'+label+'</span>'); self.fixed1.put(lbl, left, top) lbl.show() elif tipoControl in ["T", 'M']: # caja de texto entry = gtk.Entry(max=0) entry.set_size_request(width, height) entry.set_tooltip_text(mensajeAyuda) if editable != "SI": entry.set_editable(False) entry.modify_base(gtk.STATE_NORMAL, gtk.gdk.color_parse("#cccccc")) # color deshabilitado ;) if tipoControl == "T": entry.set_text("") else: entry.set_text("0") entry.set_property('xalign', 1) self.fixed1.put(entry, left, top) entry.connect("changed", self.on_numericfield_changed) # validacion solo numeros y punto (.) entry.connect("focus-out-event", self._onEntryTextFocusOut) self.widget_container[numero] = entry entry.show() elif tipoControl == "C":# combo combo = gtk.combo_box_new_text() combo.set_size_request(width, height) combo.set_tooltip_text(mensajeAyuda) if numero == '921': combo.connect("changed", self._cmdBancos_changed) # binds change event if tablaReferencial != "-1": list_store = gtk.ListStore(str, str) combo.set_model(list_store) # llenar combo segun datos referenciales if numero in ['238', '219', '222', '243'] : lista_datos = self.ref_data.get_data_list_2(tablaReferencial) else: lista_datos = self.ref_data.get_data_list(tablaReferencial) if not len(lista_datos): ezGlade.DialogBox("Error al cargar tabla referencial " + str(tablaReferencial) + ' del campo ' + str(numero), "error") for code, name in lista_datos: list_store.append([name, code]) combo.set_active(0) self.fixed1.put(combo, left, top) self.widget_container[numero] = combo combo.show() # poner el titulo de la ventana title = self.wndDeclaracion.get_title() self.wndDeclaracion.set_title(title + self.declaracion.get_alias_formulario()) def _cmdBancos_changed(self, widget, *args): """ Metodo disparado al cambiar la seleccion de la forma de pago """ if not "922" in self.widget_container: return aiter = widget.get_active_iter() model = widget.get_model() if aiter is None: return widget2 = self.widget_container["922"] widget2.set_sensitive(True) biter = widget2.get_active_iter() bmodel = widget2.get_model() # 3 = Declaración Sin Valor a Pagar # 2 = Otras Formas de Pago # 1 = Convenio De Debito if model.get_value(aiter, 1) not in ['2', '3']: widget2.set_active(0) return # usar item codigo 89 = Declaraciones en cero if model.get_value(aiter, 1) == '3' : index = 0 biter = bmodel.get_iter_first() while biter : if bmodel.get_value(biter, 1) == "89": widget2.set_sensitive(False) break biter = bmodel.iter_next(biter) index += 1 widget2.set_active(index) return # usar item codigo 16 = RED BANCARIA elif model.get_value(aiter, 1) == '2' : index = 0 biter = bmodel.get_iter_first() while biter : if bmodel.get_value(biter, 1) == "16": widget2.set_sensitive(False) break biter = bmodel.iter_next(biter) index += 1 widget2.set_active(index) return def post_init(self): self.ref_data = RefData() self.wndDeclaracion.maximize() def push_statusbar_info(self, text): context_id = self.statusbar.get_context_id("Statusbar context") self.statusbar.push(context_id, text) def generate_xml_from_container(self): self.xml = None root = etree.Element("formulario") root.set('version', '0.2' ) cabecera = etree.SubElement(root, "cabecera") codigo_version_formulario = etree.SubElement(cabecera, "codigo_version_formulario") codigo_version_formulario.text = self.declaracion.get_codigo_version() ruc = etree.SubElement(cabecera, "ruc") ruc.text = self.declaracion.get_contribuyente().get_ruc() codigo_moneda = etree.SubElement(cabecera, "codigo_moneda") codigo_moneda.text = '1' detalle = etree.SubElement(root, "detalle") for num, obj in self.widget_container.iteritems(): if obj.__class__ is gtk.Entry: campo = etree.SubElement(detalle, "campo") campo.set('numero', num ) text = obj.get_text() campo.text = unicode(text).strip() elif obj.__class__ is gtk.ComboBox: campo = etree.SubElement(detalle, "campo") campo.set('numero', num ) aiter = obj.get_active_iter() model = obj.get_model() if aiter is not None: campo.text = str(model.get_value(aiter, 1)) else: print 'Iterador nulo para', num campo.text = '0' self.xml = root def do_validations(self): if self.validations is None: ezGlade.DialogBox("ERROR: El motor de validaciones no fué creado.", "error") return self.do_calculations() self.validations.validate(self.xml) validations = self.validations.get_validations() return validations def update_container_from_xml(self): for num, obj in self.widget_container.iteritems(): campo = self.xml.find('detalle/campo[@numero="'+str(num)+'"]') if campo is None or campo.text is None: continue if obj.__class__ is gtk.Entry: # actualizar textbox obj.set_text(campo.text) elif obj.__class__ is gtk.ComboBox: # actualizar combos index = 0 bmodel = obj.get_model() biter = bmodel.get_iter_first() while biter : if bmodel.get_value(biter, 1) == campo.text: break biter = bmodel.iter_next(biter) index += 1 obj.set_active(index) def do_calculations(self): if self.calcs is None: ezGlade.DialogBox("ERROR: El motor de cálculos no fué creado.", "error") return self.generate_xml_from_container() self.calcs.calc(self.xml) # actualizar el XML segun los calculos del XSLT self.update_container_from_xml() # actualizar el formulario segun los cambios al XML def _onEntryTextFocusOut(self, *args): self.do_calculations() def on_btnCancelar_clicked(self, widget, *args): # verificar si se han guardado los cambios!!! error_dlg = gtk.MessageDialog(type=gtk.MESSAGE_ERROR, message_format="Los datos no guardados se perderán. Salir?", buttons=gtk.BUTTONS_OK_CANCEL) if error_dlg.run() == gtk.RESPONSE_OK: self.win.destroy() error_dlg.destroy() def _generar_nombre_archivo(self): alias = self.declaracion.get_alias_formulario() filename = alias if self.declaracion.get_original(): filename += 'ORI_' else: filename += 'SUS_' if self.declaracion.get_periodicidad() == "SEMESTRAL": mes = self.ref_data.get_semestre_por_codigo(self.declaracion.get_mes()) elif self.declaracion.get_periodicidad() == "MENSUAL": mes = self.ref_data.get_mes_por_codigo(self.declaracion.get_mes()) mes = mes[:3] else: mes = '' filename += mes + str(self.declaracion.get_anio()) return filename def on_btnGuardar_clicked(self, widget, *args): validations = self.do_validations() text = "El formulario presenta los siguientes errores: \n\n" for item in validations: text += item['severidad'] + ': ' + item['error'] + "\n" text += "\nDesea continuar de todas formas? \n" if len(validations): error_dlg = gtk.MessageDialog(type=gtk.MESSAGE_ERROR, message_format=text, buttons=gtk.BUTTONS_OK_CANCEL) if error_dlg.run() != gtk.RESPONSE_OK: error_dlg.destroy() return error_dlg.destroy() if self.declaracion.get_archivo() is not None: curr_file = self.declaracion.get_archivo() f = open(curr_file, 'w+') f.write(etree.tostring(self.xml, encoding='utf8', pretty_print=True)) f.close() return dialog = gtk.FileChooserDialog("Guardar ...", None, gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK)) dialog.set_default_response(gtk.RESPONSE_OK) dialog.set_current_name(self._generar_nombre_archivo()) dialog.set_current_folder(os.path.join('XML_Declaraciones')) filter = gtk.FileFilter() filter.set_name("Archivos XML") filter.add_mime_type("application/xml") filter.add_pattern("*.xml") dialog.add_filter(filter) response = dialog.run() if response == gtk.RESPONSE_OK: outfile = dialog.get_filename() # archivo destino outfile = outfile + '.xml' f = open(outfile, 'w+') f.write(etree.tostring(self.xml, encoding='utf8', pretty_print=True)) f.close() self.declaracion.set_archivo(outfile) dialog.destroy()
def setUp(self): self.calc = Calculator(0)
def test_calcs(version): print 'Prueba de calculos:' calcs = Calculator() calcs.load_xml(version) calcs.load_xsl() calcs.calc(xml)
def runTest(self): calc = Calculator(0) assert calc.add(1) == 1, "addition is wrong"
def runTest(self): calc = Calculator(0) assert calc.sub(1) == -1, "substraction is wrong"
class CalcTests(unittest.TestCase): def setUp(self): """Create calculator class""" self.calc = Calculator() def tearDown(self): """Destroy calculator class""" del self.calc def testGetCommands(self): """Ensures command list is returned correctly""" expected = ("constants: display mathematical constants\n" "exit: close calculator\n" "help: show help\n" "history: input history\n" "prev: previous input\n" "var: save variable\n" "variables: display saved variables") commands = self.calc.get_commands() self.assertEqual(commands, expected) def testAddtoHistoryKey(self): """Ensures history is correctly added to""" line = "1+2" ans = "3" self.calc.add_to_history(line, ans) self.assertIn(line, self.calc._history) def testAddToHistoryValue(self): """Ensures answer is correctly added to history""" line= "1+2" ans = "3" self.calc.add_to_history(line, ans) self.assertEqual(ans, self.calc._history[line]) def testGetHistoryNoHistory(self): """Ensures history is clear when no calculations have been input""" expected = "" history = self.calc.get_history() self.assertEqual(history, expected) def testGetHistoryWithHistory(self): """Ensures history returns correct values when calculations have been input""" expected = ("1+2 = None\n" "2 * 2 = None") self.calc.add_to_history("1+2", "None") self.calc.add_to_history("2 * 2", "None") history = self.calc.get_history() self.assertEqual(history, expected) def testGetPrevious(self): """Ensures get_previous returns last calculation""" self.calc.add_to_history('1+2', '3') self.calc.add_to_history('2 * 2', '4') self.calc.add_to_history('10/5', '2') prev = self.calc.get_previous() self.assertEqual('10/5', prev) def testGetPreviousWithAnswer(self): """Ensures get_previous returns the answer to the last calculation when requested""" self.calc.add_to_history('1+2', '3') self.calc.add_to_history('2 * 2', '4') self.calc.add_to_history('10/5', '2') prev, ans = self.calc.get_previous(True) self.assertEqual('2', ans) def testSetAnswer(self): """Ensures previous answer constant gets set""" self.calc.set_answer('5') self.assertEqual(self.calc._constants['ans'], '5') def testSetVariable(self): """Ensures that variables can be set correctly""" expected = "five set to 5" actual = self.calc.set_variable('five', '5') self.assertEqual(actual, expected) def testSetVariableKeyInVariablesDict(self): """Ensures setting variable adds key to variables dict""" self.calc.set_variable('five', '5') self.assertIn('five', self.calc._variables) def testSetVariableValueInVariablesDict(self): """Ensures setting variable addes value to variables dict""" self.calc.set_variable('five', '5') self.assertEqual(self.calc._variables['five'], '5') def testSetVariableInvalidKey(self): """Ensures only a valid variable may be added (an identifier)""" expected = "Error: Variable must begin with a letter" actual = self.calc.set_variable('5', '5') self.assertEqual(actual, expected) def testSetVariableInvalidValue(self): """Ensures only a valid value may be added (a number, integer or decimal)""" expected = "Error: Value must be an integer or decimal" actual = self.calc.set_variable('five', 'X') self.assertEqual(actual, expected) def testSetVariableInvalidValueLong(self): """Ensures only a valid value may be added (integer or decimal) Tests for previous error of allowing very long strings """ expected = "Error: Value must be an integer or decimal" actual = self.calc.set_variable('t', '9324u2389423723742384') self.assertEqual(actual, expected) def testSetVariableNoCommandOverride(self): """Ensures set_variable does not override commands""" self.calc.set_variable('help', '5') self.assertNotEqual(self.calc._commands['help'], '5') def testSetVariableNoConstantOverride(self): """Ensures set_variable does not override constants""" self.calc.set_variable('pi', '3.14') self.assertNotEqual(self.calc._constants['pi'], '3.14') def testGetVariablesNoVariables(self): """Ensures no variables are returned by get_variables if none have been added""" expected = "" variables = self.calc.get_variables() self.assertEqual(expected, variables) def testGetVariablesWithVariables(self): """Ensures all variables are returned by get_variables after variables have been added""" expected = ("five = 5\n" "ten = 10") self.calc.set_variable('ten', '10') self.calc.set_variable('five', '5') variables = self.calc.get_variables() self.assertEqual(variables, expected) def testGetConstants(self): """Ensures all constants are returned by get_constants""" expected = ("ans = None\n" "e = {0}\n" "pi = {1}".format(math.e, math.pi)) constants = self.calc.get_constants() self.assertEqual(constants, expected) def testCheckForVariablesDoesNotExist(self): """If input contains a variable or constant, it replaces it with its value Ensures that, if the variable doesn't exist, it fails """ eval = "hello" expected = None actual = self.calc.check_for_variables(eval) self.assertEqual(actual, expected) def testCheckForVariablesValidVariable(self): """If input contains a variable, it should be replaced with its value Ensures that, if the variable exists, it is replaced """ var = "x" self.calc.set_variable(var, '5') result = self.calc.check_for_variables(var) self.assertEqual(result, '5') def testCheckForVariableValidConstant(self): """Ensures that constants are replaced with their appropriate value""" eval = 'pi' result = self.calc.check_for_variables(eval) self.assertEqual(result, str(math.pi)) def testCheckForVariableValidAnswer(self): """Ensures the previous answer constant is added""" self.calc.set_answer('5') result = self.calc.check_for_variables('ans') self.assertEqual(result, '5') def testCheckEqualParensEqual(self): """Ensures method returns true when input has equal number of left and right parentheses""" eval = '((2))' result = self.calc.check_equal_parens(eval) self.assertTrue(result) def testCheckEqualParensNotEqual(self): """Ensures method returns false when input has inequal number of left and right parentheses""" eval = '(((2))' result = self.calc.check_equal_parens(eval) self.assertFalse(result) def testCalculateReturnsCorrectAdd(self): """Ensures calculation is correct for addition""" eval = "2+2" expected = 4.0 answer = self.calc.calculate(eval) self.assertEqual(answer, expected) def testCalculateReturnsCorrectSub(self): """Ensures calculation is correct for subtraction""" eval = '2-2' expected = 0.0 answer = self.calc.calculate(eval) self.assertEqual(answer, expected) def testCalculateReturnsCorrectMult(self): """Ensures calculation is correct for multiplication""" eval = '2*2' expected = 4.0 answer = self.calc.calculate(eval) self.assertEqual(answer, expected) def testCalculateReturnsCorrectDiv(self): """Ensures calculation is correct for division""" eval = '2/2' expected = 1.0 answer = self.calc.calculate(eval) self.assertEqual(answer, expected) def testCalculateReturnsCorrectModulo(self): """Ensures calculation is correct for modulus""" eval = '10%2' expected = 0.0 answer = self.calc.calculate(eval) self.assertEqual(answer, expected) def testCalculateReturnsCorrectPower(self): """Ensures calculation is correct for eponentiation""" eval = '2^2' expected = 4.0 answer = self.calc.calculate(eval) self.assertEqual(answer, expected) def testCalculateReturnsCorrectComplex(self): """Ensures calculation is correct for a more complex calculation""" eval = '((10^2/2)*5)-300' expected = -50.0 answer = self.calc.calculate(eval) self.assertEqual(answer, expected) def testCalculateReturnsCorrectConstant(self): """Ensures calculation is correct with constant""" eval = '2*pi' eval = self.calc.verify(eval) expected = 2*math.pi answer = self.calc.calculate(eval) self.assertEqual(answer, expected) def testCalculateReturnsCorrectVariable(self): """Ensures calculation is correct with variable""" self.calc.set_variable('five', '5') eval = 'five^2' eval = self.calc.verify(eval) expected = 25.0 answer = self.calc.calculate(eval) self.assertEqual(answer, expected) def testCalculateReturnsCorrectVeryComplex(self): """Ensures calculation is correct with very complex calculation""" self.calc.set_variable('onehalf', '1/2') eval = '(1000-((20*onehalf)^2)/8) + onehalf*20-4*8' eval = self.calc.verify(eval) expected = 965.5 answer = self.calc.calculate(eval) self.assertEqual(answer, expected)
def setUp(self): """Create calculator class""" self.calc = Calculator()
def test_adding_one_and_one_is_two(self): calc = Calculator() result = calc.add(1,1) self.assertEqual(2, result)
x = r[gid] * x - r[gid] * x * x; } // Calculate periods more double x_p = x; for (int a=0; a < periods; a++) { x_p = r[gid] * x_p - r[gid] * x_p * x_p; printf("%d: %f %f , ", a, x_p, x); } //double diff = x_p - x; if (x_p == x) { result[gid] = r[gid]; } else { result[gid] = 0; } } """ app = Calculator(True) r_values = np.arange(3.4, 3.5, 0.1, dtype="float64") result = app.calculate(KERNEL, [app.createArrayBuffer(r_values), np.float64(0.6), np.int64(1000), np.int64(2), np.float64(2.0)], np.empty_like(r_values)) print result print "%.155f" % np.amax(result)
def setUpClass(self): print("Set up class") self.calc = Calculator()
def add(self, argA, argB): # Import Calculator: from calc import Calculator pyCalc = Calculator() valSum = pyCalc.add(argA, argB) return valSum