本文整理汇总了Python中calculator.Calculator类的典型用法代码示例。如果您正苦于以下问题:Python Calculator类的具体用法?Python Calculator怎么用?Python Calculator使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Calculator类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: calculate
def calculate(self, question=None):
''' Return answer to the get/post value question via json in
answer. '''
cherrypy.response.headers['Content-type'] = 'application/json'
calc = ''
if 'workings' not in cherrypy.session:
cherrypy.session['workings'] = ''
if 'calc' not in cherrypy.session:
calc = Calculator()
calc.set_precision(3)
cherrypy.session['calc'] = calc
else:
calc = cherrypy.session['calc']
ans = calc.evaluate(question)
strippedans = ''
# TODO: Make general
if isinstance(ans, StrWithHtml):
ans = re.sub(r'c:/users/.*/appdata/local/temp/', r'/tmp/',
ans.html, 100)
strippedans = re.sub('[ ]?style=".*"', '', ans, 100)
strippedans = re.sub('</?canvas[^>]*>', '', strippedans, 100)
strippedans = re.sub('svg', 'png', strippedans, 100)
else:
ans = '\n'.join(map(lambda a: '<p>' + a + '</p>',
re.split(r"\n", ans)))
cherrypy.session['workings'] += ('<div style="page-break-after">'
+ '<h4 style="-pdf-keep-with-next">{}'
+ '</h4>\n<div>{}\n</div></div>\n').format(question, strippedans)
return json.dumps({'answer': ans})
示例2: index
def index():
result = []
#utc = datetime.utcnow()
#year = utc.year
#month = utc.month
#day = utc.day
#hour = utc.hour
#minute = utc.minute
#minute = int(math.floor(minute / 10.0) * 10.0)
#minute = 10 * math.floor(utc.minute / 10)
#now = datetime(year, month, day, hour, minute)
utc = request.args.get('utc', '')
utc = datetime.strptime(utc, '%Y-%m-%d %H:%M')
lat = float(request.args.get('lat', ''))
lon = float(request.args.get('lon', ''))
for item in db.location.find({"time" : utc}):
calculator = Calculator()
answer = calculator.convert(item['ra'], item['dec'], lat, lon, item['lt'], utc)
data = {
'aid' : item['aid'],
'lt' : item['lt'],
'alt' : answer['altitude'],
'azi' : answer['azimuth']
}
result.append(data)
return Response(json.dumps(result), mimetype='application/json')
示例3: TestComplex
class TestComplex(unittest.TestCase):
def setUp(self):
self.calc = Calculator()
@weight(2)
@visibility('after_due_date')
def test_eval_parens(self):
"""Evaluate (1 + 1) * 4"""
val = self.calc.eval("(1 + 1) * 4")
self.assertEqual(val, 8)
@weight(2)
@visibility('after_due_date')
def test_eval_precedence(self):
"""Evaluate 1 + 1 * 8"""
val = self.calc.eval("1 + 1 * 8")
self.assertEqual(val, 9)
@weight(2)
def test_eval_mul_div(self):
"""Evaluate 8 / 4 * 2"""
val = self.calc.eval("8 / 4 * 2")
self.assertEqual(val, 4)
@weight(2)
def test_eval_negative_number(self):
"""Evaluate -2 + 6"""
val = self.calc.eval("-2 + 6")
self.assertEqual(val, 4)
示例4: TddInPythonExample
class TddInPythonExample(unittest.TestCase):
def setUp(self):
self.calc = Calculator()
def test_calculator_add_method_returns_correct_result(self):
result = self.calc.add(2, 2)
self.assertEqual(4, result)
def test_calculator_returns_error_message_if_both_args_not_numbers(self):
self.assertRaises(ValueError, self.calc.add, 'two', 'three')
def test_calculator_subtract_method_returns_correct_result(self):
result = self.calc.subtract(4,2)
self.assertEqual(2, result)
def test_calculator_returns_error_message_if_both_args_not_numbers(self):
self.assertRaises(ValueError, self.calc.subtract, "four", "two")
def test_calculator_multiply_method_returns_correct_result(self):
result = self.calc.multiply(3,5)
self.assertEqual(15, result)
def test_calculator_returns_error_message_if_both_args_not_number(self):
self.assertRaises(ValueError, self.calc.multiply, "three","five")
def test_calculator_divide_method_returns_correct_result(self):
result = self.calc.divide(15,3)
self.assertEqual(5, result)
def test_calcualtor_returns_error_message_if_btoh_args_not_number(self):
self.assertRaises(ValueError, self.calc.divide, "fifteen","three")
示例5: test_add
def test_add():
calc = Calculator()
(4).should.equal(calc.add(2, 2))
calc.add.when.called_with('two', 'three').should.throw(ValueError)
calc.add.when.called_with('two', 3).should.throw(ValueError)
calc.add.when.called_with(2, 'three').should.throw(ValueError)
示例6: TestCalculator
class TestCalculator(unittest.TestCase):
@classmethod
def setUpClass(self):
# Create an instance of the calculator that can be used in all tests
self.calc = Calculator()
print('Set up class')
@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(5, 3), 2)
def test_multiply(self):
self.assertEqual(self.calc.multiply(2, 7), 14)
def test_divide(self):
self.assertEqual(self.calc.divide(14, 7), 2)
示例7: main
def main(argv=None):
if argv is None:
argv = sys.argv
variable_table = VariableTable()
calculator = Calculator(variable_table)
# get user input
while True:
try:
input_str = raw_input('> ')
except EOFError:
break
except KeyboardInterrupt:
print ''
break
#print "input: '" + input_str + "'"
try:
print calculator.run(input_str)
except UndefinedVariableException as e:
print 'Undefined variable: %s' % e
except ParserException:
print 'Parser error'
except LexerException:
print 'Lexer error'
except ExitCMD:
return 0
return 0
示例8: test_adds_numbers
def test_adds_numbers(self):
# Arrange
calculator = Calculator()
# Act
result = calculator.add(1, 2)
# Assert
self.assertEqual(3, result)
示例9: tf_idf
def tf_idf():
util.print_message('Start counting tf-idf...', debug=True)
if not os.path.exists(settings.TFIDF_FILE_PATH):
os.mkdir(settings.TFIDF_FILE_PATH)
c = Calculator()
file_names = util.get_file_list(settings.WORD_COUNT_FILE_PATH)
for file_name in file_names:
util.print_message('Processing tf-idf on {0}', arg=file_name)
c.tf_idf(file_name, None, None)
示例10: TestEvaluator
class TestEvaluator(unittest.TestCase):
def setUp(self):
self.calc = Calculator()
@weight(2)
@visibility('after_published')
def test_eval_power(self):
"""Evaluating 2 ** 8 should raise an exception"""
with self.assertRaises(CalculatorException):
self.calc.eval("2 ** 8")
示例11: test_invalid_string
def test_invalid_string(self):
calc = Calculator()
calc.expr = "a,b"
try:
result = calc.add()
finally:
result = -1
self.assertEqual(result, -1)
示例12: TestCalculator
class TestCalculator(unittest.TestCase):
def setUp(self):
self.c = Calculator()
def test_add3To4ToGet7(self):
actual = self.c.add(3, 4)
self.assertEquals(7, actual)
def test_addTwoIntegers(self):
actual = self.c.add(5, 8)
self.assertEquals(13, actual)
def test_invalidFirstArgThrowsException(self):
self.assertRaises(ValueError, self.c.add, "three", 6)
示例13: count_words
def count_words():
util.print_message('Start counting words...', debug=True)
if not os.path.exists(settings.WORD_COUNT_FILE_PATH):
os.mkdir(settings.WORD_COUNT_FILE_PATH)
client = MongoClient(settings.MONGO_HOST, 27017)
db = client[settings.MONGO_DATABASE]
c = Calculator()
cursor = db.arch.find()
for post in cursor:
c.tf(str(post['_id'])+'.txt', post['url'], post['body'])
示例14: CalculatorPushTestCase
class CalculatorPushTestCase(unittest.TestCase):
"""Test :py:meth:`Calculator.push`."""
def setUp(self):
self.calculator = Calculator()
def test_should_add_number_to_stack_if_powered(self):
"""Scenario: add number to stack."""
# Arrange
self.calculator.on()
number = 50
# Act
self.calculator.push(number)
# Assert
self.assertEqual(self.calculator._stack, [number])
def test_should_raise_exception_if_not_powered(self):
"""Scenario: not powered."""
# Act & Assert
self.assertRaises(CalculatorNotPoweredError, self.calculator.push, 50)
def test_should_add_two_numbers_to_stack(self):
"""Scenario: add two numbers to stack."""
# Arrange
self.calculator.on()
number1 = 50
number2 = 70
# Act
self.calculator.push(number1)
self.calculator.push(number2)
# Assert
self.assertEqual(self.calculator._stack, [number1, number2])
示例15: Mytest
class Mytest(unittest.TestCase):
def setUp(self):
self.foo = Calculator(3,2)
def test_add(self):
self.assertEqual(self.foo.add(), 5)
def test_sub(self):
self.assertEqual(self.foo.sub(),1)
def test_mul(self):
self.assertEqual(self.foo.mul(),6)
def test_div(self):
self.assertEqual(self.foo.div(), 1)