diff options
author | Zach White <skullydazed@users.noreply.github.com> | 2020-05-26 13:05:41 -0700 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-05-26 13:05:41 -0700 |
commit | 751316c34465ea77e066c3052729b207f3d62e0c (patch) | |
tree | cb99656b93c156757e2fd7c84fe716f9c300ca89 /lib/python/qmk/math.py | |
parent | 5d3bf8a050f3c0beb1f91147dc1ab54de36cbb05 (diff) | |
download | qmk_firmware-751316c34465ea77e066c3052729b207f3d62e0c.tar.gz qmk_firmware-751316c34465ea77e066c3052729b207f3d62e0c.zip |
[CLI] Add a subcommand for getting information about a keyboard (#8666)
You can now use `qmk info` to get information about keyboards and keymaps.
Co-authored-by: Erovia <Erovia@users.noreply.github.com>
Diffstat (limited to 'lib/python/qmk/math.py')
-rw-r--r-- | lib/python/qmk/math.py | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/lib/python/qmk/math.py b/lib/python/qmk/math.py new file mode 100644 index 000000000..88dc4a300 --- /dev/null +++ b/lib/python/qmk/math.py | |||
@@ -0,0 +1,33 @@ | |||
1 | """Parse arbitrary math equations in a safe way. | ||
2 | |||
3 | Gratefully copied from https://stackoverflow.com/a/9558001 | ||
4 | """ | ||
5 | import ast | ||
6 | import operator as op | ||
7 | |||
8 | # supported operators | ||
9 | operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul, ast.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor, ast.USub: op.neg} | ||
10 | |||
11 | |||
12 | def compute(expr): | ||
13 | """Parse a mathematical expression and return the answer. | ||
14 | |||
15 | >>> compute('2^6') | ||
16 | 4 | ||
17 | >>> compute('2**6') | ||
18 | 64 | ||
19 | >>> compute('1 + 2*3**(4^5) / (6 + -7)') | ||
20 | -5.0 | ||
21 | """ | ||
22 | return _eval(ast.parse(expr, mode='eval').body) | ||
23 | |||
24 | |||
25 | def _eval(node): | ||
26 | if isinstance(node, ast.Num): # <number> | ||
27 | return node.n | ||
28 | elif isinstance(node, ast.BinOp): # <left> <operator> <right> | ||
29 | return operators[type(node.op)](_eval(node.left), _eval(node.right)) | ||
30 | elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1 | ||
31 | return operators[type(node.op)](_eval(node.operand)) | ||
32 | else: | ||
33 | raise TypeError(node) | ||