def simple_eval(text): def merge(a, b): ret = a.copy() ret.update(b) return ret simpleeval.MAX_POWER = MAX_POWER_LEN s = simpleeval.SimpleEval(operators=merge( simpleeval.DEFAULT_OPERATORS, { ast.BitXor: operator.xor, ast.BitAnd: operator.and_, ast.BitOr: operator.or_, ast.RShift: operator.rshift, ast.LShift: operator.lshift, })) for k, v in math.__dict__.items(): if not k.startswith('_'): if type(v) in [int, float]: s.names[k] = v elif callable(v) and k not in [ 'exp', 'expm1', 'ldexp', 'pow', 'factorial' ]: s.functions[k] = v s.functions.update({ 'hex': lambda x: hex(x).replace('0x', '', 1).rstrip('L').upper(), 'bin': lambda x: bin(x).replace('0b', '', 1).rstrip('L'), 'oct': lambda x: oct(x).replace('0o', '', 1).rstrip('L'), 'bool': bool }) return eval_or_error(s.eval, text)
def check(val): '''Returns True if val is a valid infix expression and raises FormatError otherwise.''' operators = { ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.floordiv, } # We don't actually care what the names evaluate to, as we're not using # SimpleEval() to actually evaluate anything; we're just using it as a # shortcut to check whether or not the expression is valid in-fix. So, all # the values given here are just dummy placeholders. names = { 'A': 0, 'B': 0, 'C': 0, 'D': 0, } infix_eval = simpleeval.SimpleEval(operators=operators, names=names) try: infix_eval.eval(val) except: # noqa: E722 # eval can throw anything the Python parser can throw, so it's hard to # catch every possible item. So, exempt ourselves from this particular # flake8 warning. raise jsonschema.exceptions.FormatError('"%s" is not valid infix' % val) return True
def validate(cls, v: StrIntFloat) -> "ExpressionInt": if isinstance(v, str): evaluator = simpleeval.SimpleEval() evaluator.operators[ast.And] = operator.and_ evaluator.operators[ast.Or] = operator.or_ evaluator.operators[ast.LShift] = operator.lshift evaluator.operators[ast.RShift] = operator.rshift v = evaluator.eval(v) return cls(v)
def __init__(self): # Load the skins template.xml file templatepath = os.path.join(SKINPATH, "template.xml") self.otherTemplates = [] try: self.tree = xmltree.parse(templatepath) log("Loaded template.xml file") # Pull out the names and includes of the 'other' templates - used to generate accurate progress # and to build empty 'other' templates if necessary for otherTemplate in self.tree.getroot().findall("other"): includeName = "skinshortcuts-template" if "include" in otherTemplate.attrib: includeName = "skinshortcuts-template-%s" % ( otherTemplate.attrib.get("include")) if includeName not in self.otherTemplates: self.otherTemplates.append(includeName) # Add the template.xml to the hash file self._save_hash(templatepath, xbmcvfs.File(templatepath).read()) except: # We couldn't load the template.xml file if xbmcvfs.exists(templatepath): # Unable to parse template.xml log("Unable to parse template.xml. Invalid xml?") self._save_hash(templatepath, xbmcvfs.File(templatepath).read()) else: # No template.xml self.tree = None self._save_hash(templatepath, None) # Empty variable which will contain our base elementree (passed from buildxml) self.includes = None # Empty progress which will contain the Kodi progress dialog gui (passed from buildxml) self.progress = None self.percent = None self.current = None # List which will contain 'other' elements we will need to finalize (we won't have all the # visibility conditions until the end) self.finalize = [] # Initialize simple eval self.simple_eval = simpleeval.SimpleEval() self.simple_eval.operators[ast.In] = operator.contains
def _get_value(rx_compiled, value_expression, item): seval = simpleeval.SimpleEval() for match in [rx_compiled.search(item.title.lower())]: if not match: continue seval.names = { **match.groupdict(), **simpleeval.DEFAULT_NAMES, 'price': item.price } logger.info(f"Evaluating item {item}, match {match}") try: return seval.eval(value_expression) except Exception as e: logger.warning(f"Ignoring exception: {e}") return math.inf return 0
def __init__(self): """ Virtually private constructor. """ other_functions = { "abs": abs.abs, "e": e.E(), "ePower": ePower.ePower, "factorial": factorial.factorial, "MAD": mad.mad, "π": PI.PI(), "power": power.power, "σ": sd.sd, "sin": sin.sin, "sqrt": sqrt.sqrt, "tenPower": tenPower.tenPower } self.se = simpleeval.SimpleEval() self.se.functions = simpleeval.DEFAULT_FUNCTIONS.copy() self.se.functions.update(other_functions) self.precision = 10 self.angleMode = 'deg' if MathTool.__instance != None: raise Exception("This class is a MathTool!") else: MathTool.__instance = self
def __init__(self): other_functions = { "sin": np.sin, "cos": np.cos, "tan": np.tan, "abs": abs } other_functions.update({ "mod": np.mod, "sign": np.sign, "floor": np.floor, "ceil": np.ceil }) self.s = simpleeval.SimpleEval() self.s.operators[ast.Mult] = np.multiply self.s.operators[ast.Pow] = np.power self.s.operators[ast.Mod] = np.mod self.s.functions = simpleeval.DEFAULT_FUNCTIONS.copy() del self.s.functions["str"] del self.s.functions["rand"] del self.s.functions["randint"] self.s.functions.update(other_functions) self.s.names = {"x": np.arange(256), "pi": np.pi} self.output = None
def generate_eval_parser(**simpleeval_kwargs): value_parser = simpleeval.SimpleEval(**simpleeval_kwargs) value_parser.operators = {**value_parser.operators, **EVAL_OPERATORS_EXTRA} return value_parser
'none': 0, 'full': 1, 'top_half': 2, 'bottom_half': 3, } def getDirectionFlags(ls): flags = 0 for d in ls: if d in faceToOffset: flags |= (1 << faceToOffset[d]) return flags evaluator = simpleeval.SimpleEval() def resolve(vertex): for i in range(len(vertex)): if type(vertex[i]) is str: vertex[i] = evaluator.eval(vertex[i]) def resolve2(vertex, vlookup): for i in range(len(vertex)): if i == 0: vertex[i] = vlookup[vertex[i]] elif type(vertex[i]) is str: vertex[i] = evaluator.eval(vertex[i])
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' # pip install simpleeval import simpleeval class Foo: class A: class B: class C: value = 3 value = 25 my_eval = simpleeval.SimpleEval() my_eval.names['foo'] = Foo print(my_eval.eval('foo.A.B.C.value * 10 + foo.A.value')) # 55
def __init__(self, parentContext=None, gil=None, functions={}, variables=None, constants=None, contextFunctions={}, contextName="script"): self.pipelines = [] # Used as a backup plan to be able to do things in a background thread # when doing so directly would cause a deadlock self.eventQueue = [] self.eventListeners = {} self.variables = variables if not variables is None else {} self.commands = ScriptActionKeeper() self.contextCommands = ScriptActionKeeper() self.children = {} self.children_iterable = {} self.constants = constants if (not (constants is None)) else {} self.contextName = contextName # Cache whether or not any binding is watching a variable # or variable. False positives are acceptable, it's just a slight # Performance hit self.needRefreshForVariable = {} # Used for detecting loops. .d Must be 0 whenever we are not CURRENTLY, as in right now, in this thread, executing an event. # Not a pure stack or semaphor, when you queue up an event, that event will run at one higher than the event that created it, # And always return to 0 when it is not actively executing event code, to ensure that things not caused directly by an event # Don't have a nonzero depth. # It'ts not even tracking recursion really, more like async causation, or parenthood back to an event not caused my another event. # The whole point is not to let an event create another event, which runs the first event, etc. self.eventRecursionDepth = threading.local() # Should we propagate events to children self.propagateEvents = False # Used to allow objects named foo.bar to be accessed as actual attributes of a foo obj, # Even though we use a flat list of vars. self.namespaces = {} self.contextName = "ScriptContext" self.timeEvents = {} self.poller = None self.slowpoller = None selfid = id(self) # Stack to keep track of the $event variable for the current event we are running, # For nested events self.eventValueStack = [] # Look for rising edge detects that already fired self.risingEdgeDetects = {} if parentContext: def delf(*a, **K): with lock: del parentContext.children[selfid] parentContext.children_iterable = parentContext.children.copy( ) with lock: parentContext.children[id(self)] = weakref.ref(self, delf) parentContext.children_iterable = parentContext.children.copy() self.parentContext = parentContext # Vars that have changed since last time we # Cleared the list. Used for telling the GUI # client about the current set of variables self.changedVariables = {} def setter(Variable, Value): if not isinstance(Variable, str): raise RuntimeError("Var name must be string") if Variable in globalConstants or Variable in self.constants: raise NameError("Key " + Variable + " is a constant") self.setVar(Variable, Value) self.setter = setter self.commands['set'] = setter for i in predefinedcommands: self.commands[i] = predefinedcommands[i] def defaultVar(name, default): try: return self._nameLookup(name) except NameError: return default functions = functions.copy() functions.update(globalUsrFunctions) functions['defaultVar'] = defaultVar functions['var'] = defaultVar c = {} # Wrap them, so the first param becomes this context object. def wrap(self, f): def wrapped(*a, **k): f(self, *a, **k) return wrapped for i in contextFunctions: c[i] = wrap(self, contextFunctions[i]) self.functions = functions self.evaluator = simpleeval.SimpleEval(functions=functions, names=self._nameLookup) if not gil: self.gil = threading.RLock() else: self.gil = gil
same prefix in. Calling a PathLongener with a dict without ``depth`` or ``path`` attributes is a no-op. """ def __init__(self, prefix: Union[Path, tuple] = ()): self.depth = len(prefix) self.path = Path.build(prefix) def __call__(self, res): p = res.get("path", None) if p is None: return d = res.pop("depth", None) if d is None: return if not isinstance(p, tuple): # may be a list, dammit p = tuple(p) p = self.path[:self.depth + d] + p self.path = p res["path"] = p # path_eval is a simple "eval" replacement to implement resolving # expressions in paths. While it can be used for math, its primary function # is to process tuples. _eval = simpleeval.SimpleEval(functions={}) _eval.nodes[ast.Tuple] = lambda node: tuple(_eval._eval(x) for x in node.elts) path_eval = _eval.eval