2003-09-13 17:00:22 +02:00
|
|
|
###
|
2004-08-23 15:14:06 +02:00
|
|
|
# Copyright (c) 2002-2004, Jeremiah Fincher
|
2003-09-13 17:00:22 +02:00
|
|
|
# All rights reserved.
|
|
|
|
#
|
|
|
|
# Redistribution and use in source and binary forms, with or without
|
|
|
|
# modification, are permitted provided that the following conditions are met:
|
|
|
|
#
|
|
|
|
# * Redistributions of source code must retain the above copyright notice,
|
|
|
|
# this list of conditions, and the following disclaimer.
|
|
|
|
# * Redistributions in binary form must reproduce the above copyright notice,
|
|
|
|
# this list of conditions, and the following disclaimer in the
|
|
|
|
# documentation and/or other materials provided with the distribution.
|
|
|
|
# * Neither the name of the author of this software nor the name of
|
|
|
|
# contributors to this software may be used to endorse or promote products
|
|
|
|
# derived from this software without specific prior written consent.
|
|
|
|
#
|
|
|
|
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
|
|
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
|
|
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
|
|
|
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
|
|
|
|
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
|
|
|
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
|
|
|
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
|
|
|
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
|
|
|
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
|
|
|
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
|
|
|
# POSSIBILITY OF SUCH DAMAGE.
|
|
|
|
###
|
|
|
|
|
|
|
|
"""
|
|
|
|
Various math-related commands.
|
|
|
|
"""
|
|
|
|
|
2003-11-25 09:23:47 +01:00
|
|
|
__revision__ = "$Id$"
|
|
|
|
|
2004-02-07 19:21:46 +01:00
|
|
|
from __future__ import division
|
|
|
|
|
2004-07-24 07:18:26 +02:00
|
|
|
import supybot.plugins as plugins
|
2003-09-13 17:00:22 +02:00
|
|
|
|
|
|
|
import re
|
|
|
|
import math
|
|
|
|
import cmath
|
2003-10-30 04:46:31 +01:00
|
|
|
import types
|
2003-10-04 14:29:58 +02:00
|
|
|
import string
|
2003-09-13 17:00:22 +02:00
|
|
|
from itertools import imap
|
|
|
|
|
2004-07-24 07:18:26 +02:00
|
|
|
import supybot.utils as utils
|
|
|
|
import supybot.privmsgs as privmsgs
|
|
|
|
import supybot.callbacks as callbacks
|
2003-09-13 17:00:22 +02:00
|
|
|
|
2004-07-21 21:36:35 +02:00
|
|
|
import convertcore
|
2004-01-25 08:03:27 +01:00
|
|
|
|
2003-09-13 17:00:22 +02:00
|
|
|
|
|
|
|
class Math(callbacks.Privmsg):
|
|
|
|
###
|
|
|
|
# So this is how the 'calc' command works:
|
|
|
|
# First, we make a nice little safe environment for evaluation; basically,
|
|
|
|
# the names in the 'math' and 'cmath' modules. Then, we remove the ability
|
|
|
|
# of a random user to get ints evaluated: this means we have to turn all
|
|
|
|
# int literals (even octal numbers and hexadecimal numbers) into floats.
|
|
|
|
# Then we delete all square brackets, underscores, and whitespace, so no
|
|
|
|
# one can do list comprehensions or call __...__ functions.
|
|
|
|
###
|
2004-01-09 01:13:44 +01:00
|
|
|
def base(self, irc, msg, args):
|
2004-02-07 21:41:07 +01:00
|
|
|
"""<fromBase> [<toBase>] <number>
|
2004-01-09 01:13:44 +01:00
|
|
|
|
2004-02-07 21:41:07 +01:00
|
|
|
Converts from base <fromBase> to base <toBase>. If <toBase> is left
|
|
|
|
out, it converts to decimal.
|
2004-01-09 01:13:44 +01:00
|
|
|
"""
|
2004-02-07 21:41:07 +01:00
|
|
|
(frm, to, number) = privmsgs.getArgs(args, required=2, optional=1)
|
|
|
|
if number == '':
|
|
|
|
number = to
|
|
|
|
to = '10'
|
2004-01-09 01:13:44 +01:00
|
|
|
try:
|
2004-02-07 21:41:07 +01:00
|
|
|
frm = int(frm)
|
|
|
|
to = int(to)
|
|
|
|
if not ((2 <= frm <= 36) and (2 <= to <= 36)):
|
2004-01-09 01:13:44 +01:00
|
|
|
raise ValueError
|
|
|
|
except ValueError:
|
2004-02-07 21:58:04 +01:00
|
|
|
irc.error('Bases must be an integer between 2 and 36.')
|
2004-01-09 01:13:44 +01:00
|
|
|
return
|
|
|
|
try:
|
2004-02-07 21:41:07 +01:00
|
|
|
irc.reply(self._convertBaseToBase(number, to, frm))
|
2004-01-09 01:13:44 +01:00
|
|
|
except ValueError:
|
2004-02-07 21:41:07 +01:00
|
|
|
irc.error('Invalid <number> for base %s: %s' % (frm, number))
|
2004-01-09 01:13:44 +01:00
|
|
|
|
2004-02-07 21:41:07 +01:00
|
|
|
def _convertDecimalToBase(self, number, base):
|
|
|
|
"""
|
|
|
|
Convert a decimal number to another base; returns a string.
|
|
|
|
"""
|
2004-02-09 04:08:33 +01:00
|
|
|
negative = False
|
|
|
|
if number < 0:
|
|
|
|
negative = True
|
|
|
|
number = -number
|
2004-02-07 21:41:07 +01:00
|
|
|
valStr = ''
|
|
|
|
if number == 0:
|
|
|
|
return '0'
|
|
|
|
while number != 0:
|
|
|
|
digit = number % base
|
|
|
|
if digit >= 10:
|
|
|
|
digit = string.uppercase[digit - 10]
|
|
|
|
else:
|
|
|
|
digit = str(digit)
|
|
|
|
valStr = digit + valStr
|
2004-02-10 04:21:45 +01:00
|
|
|
number = number // base
|
2004-02-09 04:08:33 +01:00
|
|
|
if negative:
|
|
|
|
return '-%s' % valStr
|
|
|
|
else:
|
|
|
|
return valStr
|
2004-07-21 21:36:35 +02:00
|
|
|
|
2004-02-07 21:41:07 +01:00
|
|
|
def _convertBaseToBase(self, number, toBase, fromBase):
|
|
|
|
"""
|
|
|
|
Convert a number from any base, 2 through 36, to any other
|
|
|
|
base, 2 through 36. Returns a string.
|
|
|
|
"""
|
|
|
|
number = long(str(number), fromBase)
|
2004-02-10 04:21:45 +01:00
|
|
|
if toBase == 10:
|
|
|
|
return str(number)
|
2004-02-07 21:41:07 +01:00
|
|
|
return self._convertDecimalToBase(number, toBase)
|
2004-07-21 21:36:35 +02:00
|
|
|
|
2003-10-30 04:46:31 +01:00
|
|
|
_mathEnv = {'__builtins__': types.ModuleType('__builtins__'), 'i': 1j}
|
2003-09-13 17:00:22 +02:00
|
|
|
_mathEnv.update(math.__dict__)
|
|
|
|
_mathEnv.update(cmath.__dict__)
|
2004-01-24 19:57:01 +01:00
|
|
|
def _sqrt(x):
|
|
|
|
if isinstance(x, complex) or x < 0:
|
|
|
|
return cmath.sqrt(x)
|
|
|
|
else:
|
|
|
|
return math.sqrt(x)
|
|
|
|
_mathEnv['sqrt'] = _sqrt
|
2004-09-06 10:07:54 +02:00
|
|
|
_mathEnv['abs'] = abs
|
2004-09-15 18:17:03 +02:00
|
|
|
_mathEnv['max'] = max
|
|
|
|
_mathEnv['min'] = min
|
2004-02-06 08:14:07 +01:00
|
|
|
_mathRe = re.compile(r'((?:(?<![A-Fa-f\d)])-)?'
|
2003-09-13 17:00:22 +02:00
|
|
|
r'(?:0x[A-Fa-f\d]+|'
|
|
|
|
r'0[0-7]+|'
|
|
|
|
r'\d+\.\d+|'
|
|
|
|
r'\.\d+|'
|
|
|
|
r'\d+\.|'
|
|
|
|
r'\d+))')
|
2004-01-22 01:52:11 +01:00
|
|
|
def _floatToString(self, x):
|
2004-01-25 08:03:27 +01:00
|
|
|
if -1e-10 < x < 1e-10:
|
2004-01-22 01:52:11 +01:00
|
|
|
return '0'
|
2004-01-25 08:03:27 +01:00
|
|
|
elif -1e-10 < int(x) - x < 1e-10:
|
2004-01-22 01:52:11 +01:00
|
|
|
return str(int(x))
|
|
|
|
else:
|
|
|
|
return str(x)
|
2004-07-21 21:36:35 +02:00
|
|
|
|
2003-09-13 17:00:22 +02:00
|
|
|
def _complexToString(self, x):
|
2004-01-22 01:52:11 +01:00
|
|
|
realS = self._floatToString(x.real)
|
|
|
|
imagS = self._floatToString(x.imag)
|
|
|
|
if imagS == '0':
|
|
|
|
return realS
|
|
|
|
elif imagS == '1':
|
|
|
|
imagS = '+i'
|
|
|
|
elif imagS == '-1':
|
|
|
|
imagS = '-i'
|
|
|
|
elif x.imag < 0:
|
|
|
|
imagS = '%si' % imagS
|
|
|
|
else:
|
|
|
|
imagS = '+%si' % imagS
|
|
|
|
if realS == '0' and imagS == '0':
|
2003-09-13 17:00:22 +02:00
|
|
|
return '0'
|
2004-01-22 01:52:11 +01:00
|
|
|
elif realS == '0':
|
|
|
|
return imagS.lstrip('+')
|
|
|
|
elif imagS == '0':
|
|
|
|
return realS
|
2003-09-13 17:00:22 +02:00
|
|
|
else:
|
2004-01-22 01:52:11 +01:00
|
|
|
return '%s%s' % (realS, imagS)
|
2003-09-13 17:00:22 +02:00
|
|
|
|
|
|
|
def calc(self, irc, msg, args):
|
|
|
|
"""<math expression>
|
|
|
|
|
2004-08-19 01:15:27 +02:00
|
|
|
Returns the value of the evaluated <math expression>. The syntax is
|
2004-01-28 23:50:00 +01:00
|
|
|
Python syntax; the type of arithmetic is floating point. Floating
|
2003-09-23 17:42:01 +02:00
|
|
|
point arithmetic is used in order to prevent a user from being able to
|
|
|
|
crash to the bot with something like 10**10**10**10. One consequence
|
|
|
|
is that large values such as 10**24 might not be exact.
|
2003-09-13 17:00:22 +02:00
|
|
|
"""
|
|
|
|
text = privmsgs.getArgs(args)
|
2004-01-01 20:09:34 +01:00
|
|
|
if text != text.translate(string.ascii, '_[]'):
|
2004-01-08 04:12:14 +01:00
|
|
|
irc.error('There\'s really no reason why you should have '
|
2004-01-01 20:09:34 +01:00
|
|
|
'underscores or brackets in your mathematical '
|
|
|
|
'expression. Please remove them.')
|
|
|
|
return
|
2004-02-06 08:14:07 +01:00
|
|
|
#text = text.translate(string.ascii, '_[] \t')
|
2004-01-01 20:09:34 +01:00
|
|
|
if 'lambda' in text:
|
2004-01-08 04:12:14 +01:00
|
|
|
irc.error('You can\'t use lambda in this command.')
|
2004-01-01 20:09:34 +01:00
|
|
|
return
|
2004-09-14 23:51:54 +02:00
|
|
|
text = text.lower()
|
2003-09-13 17:00:22 +02:00
|
|
|
def handleMatch(m):
|
|
|
|
s = m.group(1)
|
|
|
|
if s.startswith('0x'):
|
|
|
|
i = int(s, 16)
|
|
|
|
elif s.startswith('0') and '.' not in s:
|
|
|
|
try:
|
|
|
|
i = int(s, 8)
|
|
|
|
except ValueError:
|
|
|
|
i = int(s)
|
|
|
|
else:
|
|
|
|
i = float(s)
|
2003-10-13 05:47:33 +02:00
|
|
|
x = complex(i)
|
|
|
|
if x == abs(x):
|
|
|
|
x = abs(x)
|
|
|
|
return str(x)
|
2003-09-13 17:00:22 +02:00
|
|
|
text = self._mathRe.sub(handleMatch, text)
|
|
|
|
try:
|
2003-12-01 12:25:48 +01:00
|
|
|
self.log.info('evaluating %r from %s' % (text, msg.prefix))
|
2003-09-13 17:00:22 +02:00
|
|
|
x = complex(eval(text, self._mathEnv, self._mathEnv))
|
2004-01-08 04:12:14 +01:00
|
|
|
irc.reply(self._complexToString(x))
|
2003-09-13 17:00:22 +02:00
|
|
|
except OverflowError:
|
2003-11-17 16:55:43 +01:00
|
|
|
maxFloat = math.ldexp(0.9999999999999999, 1024)
|
2004-01-08 04:12:14 +01:00
|
|
|
irc.error('The answer exceeded %s or so.' % maxFloat)
|
2003-09-13 17:00:22 +02:00
|
|
|
except TypeError:
|
2004-01-08 04:12:14 +01:00
|
|
|
irc.error('Something in there wasn\'t a valid number.')
|
2003-10-19 16:47:29 +02:00
|
|
|
except NameError, e:
|
2004-01-08 04:12:14 +01:00
|
|
|
irc.error('%s is not a defined function.' % str(e).split()[1])
|
2003-09-13 17:00:22 +02:00
|
|
|
except Exception, e:
|
2004-01-24 19:57:01 +01:00
|
|
|
irc.error(str(e))
|
2003-09-13 17:00:22 +02:00
|
|
|
|
2003-12-04 09:29:19 +01:00
|
|
|
def icalc(self, irc, msg, args):
|
|
|
|
"""<math expression>
|
|
|
|
|
|
|
|
This is the same as the calc command except that it allows integer
|
|
|
|
math, and can thus cause the bot to suck up CPU. Hence it requires
|
|
|
|
the 'trusted' capability to use.
|
|
|
|
"""
|
|
|
|
text = privmsgs.getArgs(args)
|
2004-01-01 20:09:34 +01:00
|
|
|
if text != text.translate(string.ascii, '_[]'):
|
2004-01-08 04:12:14 +01:00
|
|
|
irc.error('There\'s really no reason why you should have '
|
2004-01-01 20:09:34 +01:00
|
|
|
'underscores or brackets in your mathematical '
|
|
|
|
'expression. Please remove them.')
|
|
|
|
return
|
|
|
|
# This removes spaces, too, but we'll leave the removal of _[] for
|
|
|
|
# safety's sake.
|
2003-12-04 09:29:19 +01:00
|
|
|
text = text.translate(string.ascii, '_[] \t')
|
2004-01-01 20:09:34 +01:00
|
|
|
if 'lambda' in text:
|
2004-01-08 04:12:14 +01:00
|
|
|
irc.error('You can\'t use lambda in this command.')
|
2004-01-01 20:09:34 +01:00
|
|
|
return
|
2003-12-04 09:29:19 +01:00
|
|
|
text = text.replace('lambda', '')
|
|
|
|
try:
|
|
|
|
self.log.info('evaluating %r from %s' % (text, msg.prefix))
|
2004-01-08 04:12:14 +01:00
|
|
|
irc.reply(str(eval(text, self._mathEnv, self._mathEnv)))
|
2003-12-04 09:29:19 +01:00
|
|
|
except OverflowError:
|
|
|
|
maxFloat = math.ldexp(0.9999999999999999, 1024)
|
2004-01-08 04:12:14 +01:00
|
|
|
irc.error('The answer exceeded %s or so.' % maxFloat)
|
2003-12-04 09:29:19 +01:00
|
|
|
except TypeError:
|
2004-01-08 04:12:14 +01:00
|
|
|
irc.error('Something in there wasn\'t a valid number.')
|
2003-12-04 09:29:19 +01:00
|
|
|
except NameError, e:
|
2004-01-08 04:12:14 +01:00
|
|
|
irc.error('%s is not a defined function.' % str(e).split()[1])
|
2003-12-04 09:29:19 +01:00
|
|
|
except Exception, e:
|
2004-01-08 04:12:14 +01:00
|
|
|
irc.error(utils.exnToString(e))
|
2003-12-04 09:29:19 +01:00
|
|
|
icalc = privmsgs.checkCapability(icalc, 'trusted')
|
2004-07-21 21:36:35 +02:00
|
|
|
|
2003-09-13 17:00:22 +02:00
|
|
|
_rpnEnv = {
|
|
|
|
'dup': lambda s: s.extend([s.pop()]*2),
|
2003-12-02 23:08:46 +01:00
|
|
|
'swap': lambda s: s.extend([s.pop(), s.pop()])
|
2003-09-13 17:00:22 +02:00
|
|
|
}
|
|
|
|
def rpn(self, irc, msg, args):
|
|
|
|
"""<rpn math expression>
|
|
|
|
|
|
|
|
Returns the value of an RPN expression.
|
|
|
|
"""
|
|
|
|
stack = []
|
|
|
|
for arg in args:
|
|
|
|
try:
|
2003-10-13 06:54:57 +02:00
|
|
|
x = complex(arg)
|
|
|
|
if x == abs(x):
|
|
|
|
x = abs(x)
|
|
|
|
stack.append(x)
|
2003-09-13 17:00:22 +02:00
|
|
|
except ValueError: # Not a float.
|
|
|
|
if arg in self._mathEnv:
|
|
|
|
f = self._mathEnv[arg]
|
|
|
|
if callable(f):
|
|
|
|
called = False
|
|
|
|
arguments = []
|
|
|
|
while not called and stack:
|
|
|
|
arguments.append(stack.pop())
|
|
|
|
try:
|
|
|
|
stack.append(f(*arguments))
|
|
|
|
called = True
|
|
|
|
except TypeError:
|
|
|
|
pass
|
|
|
|
if not called:
|
2004-01-08 04:12:14 +01:00
|
|
|
irc.error('Not enough arguments for %s' % arg)
|
2003-09-13 17:00:22 +02:00
|
|
|
return
|
|
|
|
else:
|
|
|
|
stack.append(f)
|
|
|
|
elif arg in self._rpnEnv:
|
|
|
|
self._rpnEnv[arg](stack)
|
|
|
|
else:
|
|
|
|
arg2 = stack.pop()
|
|
|
|
arg1 = stack.pop()
|
|
|
|
s = '%s%s%s' % (arg1, arg, arg2)
|
2003-10-19 16:47:29 +02:00
|
|
|
try:
|
|
|
|
stack.append(eval(s, self._mathEnv, self._mathEnv))
|
|
|
|
except SyntaxError:
|
2004-01-08 04:12:14 +01:00
|
|
|
irc.error('%r is not a defined function.' % arg)
|
2003-10-19 16:47:29 +02:00
|
|
|
return
|
2003-09-13 17:00:22 +02:00
|
|
|
if len(stack) == 1:
|
2004-01-08 04:12:14 +01:00
|
|
|
irc.reply(str(self._complexToString(complex(stack[0]))))
|
2003-09-13 17:00:22 +02:00
|
|
|
else:
|
|
|
|
s = ', '.join(imap(self._complexToString, imap(complex, stack)))
|
2004-01-08 04:12:14 +01:00
|
|
|
irc.reply('Stack: [%s]' % s)
|
2003-09-13 17:00:22 +02:00
|
|
|
|
2003-10-03 01:19:38 +02:00
|
|
|
def convert(self, irc, msg, args):
|
2004-01-25 08:03:27 +01:00
|
|
|
"""[<number>] <unit> to <other unit>
|
2003-09-13 17:00:22 +02:00
|
|
|
|
2004-01-25 08:03:27 +01:00
|
|
|
Converts from <unit> to <other unit>. If number isn't given, it
|
|
|
|
defaults to 1. For unit information, see 'units' command.
|
2003-10-03 01:19:38 +02:00
|
|
|
"""
|
2004-07-21 21:36:35 +02:00
|
|
|
|
2004-01-25 08:03:27 +01:00
|
|
|
# see if the first arg is a number of some sort
|
2004-07-21 21:36:35 +02:00
|
|
|
if args:
|
2004-01-25 08:03:27 +01:00
|
|
|
try:
|
|
|
|
num = float(args[0])
|
|
|
|
args.pop(0)
|
|
|
|
except ValueError:
|
|
|
|
num = 1.0
|
2003-10-23 06:21:40 +02:00
|
|
|
else:
|
2003-10-03 01:19:38 +02:00
|
|
|
raise callbacks.ArgumentError
|
2004-01-25 08:03:27 +01:00
|
|
|
|
2003-10-03 01:19:38 +02:00
|
|
|
try:
|
2004-01-25 08:03:27 +01:00
|
|
|
the_rest = ' '.join(args)
|
|
|
|
(unit1, unit2) = the_rest.split(' to ')
|
2003-10-03 01:19:38 +02:00
|
|
|
except ValueError:
|
2004-01-25 08:03:27 +01:00
|
|
|
raise callbacks.ArgumentError
|
|
|
|
|
2003-10-03 01:19:38 +02:00
|
|
|
try:
|
2004-01-25 08:03:27 +01:00
|
|
|
newNum = convertcore.convert(num, unit1, unit2)
|
|
|
|
newNum = self._floatToString(newNum)
|
2004-07-21 21:36:35 +02:00
|
|
|
|
2004-03-02 00:18:21 +01:00
|
|
|
irc.reply('%s' % newNum)
|
2004-01-25 08:03:27 +01:00
|
|
|
except convertcore.UnitDataError, ude:
|
|
|
|
irc.error(str(ude))
|
2003-09-13 17:00:22 +02:00
|
|
|
|
2003-10-03 01:19:38 +02:00
|
|
|
def units(self, irc, msg, args):
|
2004-01-25 08:03:27 +01:00
|
|
|
""" [<type>]
|
2003-10-03 01:19:38 +02:00
|
|
|
|
2004-01-25 08:03:27 +01:00
|
|
|
With no arguments, returns a list of measurement types, which can be
|
|
|
|
passed as arguments. When called with a type as an argument, returns
|
|
|
|
the units of that type.
|
2003-10-03 01:19:38 +02:00
|
|
|
"""
|
2004-07-21 21:36:35 +02:00
|
|
|
|
2004-01-25 08:03:27 +01:00
|
|
|
if len(args) == 0:
|
|
|
|
type = None
|
|
|
|
else:
|
|
|
|
type = ' '.join(args)
|
|
|
|
irc.reply(convertcore.units(type))
|
2004-07-21 21:36:35 +02:00
|
|
|
|
2003-09-13 17:00:22 +02:00
|
|
|
Class = Math
|
|
|
|
|
|
|
|
# vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78:
|