def test_use_func(self): self.s = EvalWithCompoundTypes(functions={"map": map, "str": str}) self.t('list(map(str, [-1, 0, 1]))', ['-1', '0', '1']) with self.assertRaises(NameNotDefined): self.s.eval('list(map(bad, [-1, 0, 1]))') with self.assertRaises(FunctionNotDefined): self.s.eval('dir(str)') with self.assertRaises(FeatureNotAvailable): self.s.eval('str.__dict__') self.s = EvalWithCompoundTypes(functions={"dir": dir, "str": str}) self.t('dir(str)', dir(str))
def final_spec(args, obj_space, cspaces, addr_spaces, targets, architecture): """ Generates a final CapDL spec file that can be given to a capdl loader application """ arch = lookup_architecture(architecture) for (e, key) in targets: name = os.path.basename(e) elf = ELF(e, name, architecture) cspace = cspaces[key] # Avoid inferring a TCB as we've already created our own. elf_spec = elf.get_spec(infer_tcb=False, infer_asid=False, pd=addr_spaces[key].vspace_root, addr_space=addr_spaces[key]) obj_space.merge(elf_spec, label=key) for (slot, tcb) in [(k, v.referent) for (k, v) in cspace.cnode.slots.items() if v is not None and isinstance(v.referent, TCB)]: if tcb['cspace'] and tcb['cspace'].referent is not cspace.cnode: # We exclude TCBs that refer to a different CSpace continue funcs = {"get_vaddr": lambda x: elf.get_symbol_vaddr(x)} s = EvalWithCompoundTypes(functions=funcs) tcb.ip = s.eval(str(tcb.ip)) tcb.sp = s.eval(str(tcb.sp)) tcb.addr = s.eval(str(tcb.addr)) tcb.init = s.eval(str(tcb.init)) if not args.fprovide_tcb_caps: del cspace.cnode[slot] cspace.cnode.finalise_size(arch=arch) return obj_space
def parse_expr(expr: str, names: dict, fns: dict, errors: list = None): errors = errors if type(errors) == list else [] names2 = Munch2.fromDict({**names, **{ }}) fns = {'F': update_recursive(fns, { 'list': { 'next': fn_list_next, 'join': fn_list_join }, 'str': fn_str, 'float': fn_float, 'int': fn_int, 'has': fn_has, 'next': fn_list_next, 'join': fn_list_join, 'trim': fn_str_trim, 'extend': fn_extend, 'update': fn_update, 'encrypt': fn_encrypt_names(names2), 'decrypt': fn_decrypt_names(names2), 'inc': fn_inc_names(names2), 'linspace': fn_linspace, 'arange': fn_arange })} s = EvalWithCompoundTypes(names=names2, functions=fns) try: v = s.eval(expr=expr) except Exception as ex: v = expr errors.append([expr, ex]) v = filter_value(v) return v
def __call__(self): s = EvalWithCompoundTypes(names=self.vars, functions=self.functions) recipients = s.eval(self.settings['recipients']) for recipient in recipients: recipient_data = self._get_recipient_data(recipient) subject = self.settings['subject_tpl'].format( recipient=recipient_data, **self.vars, ) body = self.settings['body_tpl'].format( recipient=recipient_data, **self.vars, ) to_email = getattr(recipient_data, 'email', recipient) if to_email: send_mail( subject, body, self.settings['from_email'], [ to_email, ], fail_silently=True, ) else: logger.error('No destination e-mail could be found for %s', recipient)
def evaluate_expression( expression: str, names: Dict[str, Any], functions: Optional[Dict[str, Callable]] = None, interpolations: Optional[Mapping[str, Any]] = None, ) -> Any: try: expression = expression.format_map(interpolations or {}) except KeyError as e: raise FieldNameError(e) return EvalWithCompoundTypes(names=names, functions=functions).eval(expression)
def prepare_evaluator(self): """ Setup evaluator engine :return: Prepare evaluator engine """ simpleeval_params = self.params.get('simpleeval', {}) # update simpleeval safety options for k, v in simpleeval_params.get('options', {}).items(): setattr(simpleeval, k.upper(), v) evaluator = EvalWithCompoundTypes() # self._evals_functions should mirror self.fns # TODO: Make a test to ensure proper mirroring evaluator.functions = self.fns evaluator.names = self.names # set the operators if simpleeval_params.get('operators'): evaluator.operators = simpleeval_params.get('operators') return evaluator
def __init__(self, params=None, names=None, fns=None, operators=None, opts=None): """ :param params: A dictionary containing some parameters that will modify how the builtin functions run. For example, the type of encryption to use and the encrpyption key to use """ self._params = params if params is not None else {} self._params.update({'etype': 'fernet'}) self._operators = operators if operators is not None else simpleeval.DEFAULT_OPERATORS opts = opts if opts is not None else {} self.opts.update(opts) self._names = Munch2(names) if names is not None else {} fns = fns if fns is not None else {} self._fns = { 'F': update_recursive( fns, {fn[3:]: getattr(self, fn) for fn in dir(self) if 'fn_' in fn}) } # Update simpleeval safety options for k, v in opts.items(): setattr(simpleeval, k.upper(), v) self._eval = EvalWithCompoundTypes() # self._evals_functions should mirror self._fns # TODO: Make a test to ensure proper mirroring self._eval.functions = self._fns self._eval.names = self._names if operators: self._operators = operators self._eval.operators = self._operators self.errors = []
def setUp(self): self.s = EvalWithCompoundTypes()
import os from flask import Flask, Blueprint, render_template, flash, redirect, url_for, send_file, Response, abort, request, session, jsonify, g from flask_login import current_user, login_required, login_user, logout_user from jinja2 import StrictUndefined from rhinventory.extensions import db, admin, debug_toolbar, github, login_manager from rhinventory.admin import add_admin_views from rhinventory.db import User, Asset, Location, log from rhinventory.labels import make_barcode, make_label, make_asset_label from simpleeval import EvalWithCompoundTypes simple_eval = EvalWithCompoundTypes() def create_app(config_object='rhinventory.config'): app = Flask(__name__.split('.')[0], template_folder='templates') app.config.from_object(config_object) db.init_app(app) admin.init_app(app) debug_toolbar.init_app(app) github.init_app(app) login_manager.init_app(app) files_blueprint = Blueprint('files', __name__, static_url_path='/files', static_folder=app.config['FILES_DIR']) app.register_blueprint(files_blueprint) add_admin_views(app) @app.before_request
# SimpleEval and simple_eval NOT WORK with compound types try: print(simple_eval('[1, 2, 3, 4]')) except Exception as e: print(e) # Sorry, List is not available in this evaluator try: my_eval = SimpleEval() print(my_eval.eval('[1, 2, 3, 4]')) except Exception as e: print(e) # Sorry, List is not available in this evaluator print() # Compound Types my_compound_types_eval = EvalWithCompoundTypes() my_compound_types_eval.functions['len'] = len # list print(my_compound_types_eval.eval('[1, 2, 3, 4]')) # [1, 2, 3, 4] print(my_compound_types_eval.eval('[1, 2] + [3, 4]')) # [1, 2, 3, 4] print(my_compound_types_eval.eval('len([1, 2, 3, 4])')) # 4 print(my_compound_types_eval.eval('[1, 2, 1, 3, 4].count(1)')) # 2 print(my_compound_types_eval.eval('list("1234")')) # ['1', '2', '3', '4'] print() # dict print(my_compound_types_eval.eval('{"a": 1, "b": 999}')) # {'a': 1, 'b': 999} print(my_compound_types_eval.eval('{"a": 1, "b": 999}["b"]')) # 999 print(my_compound_types_eval.eval( '{"a": 1, "b": 999}.items()')) # dict_items([('a', 1), ('b', 999)])
print() print(simple_eval("2 + 2 * 2")) # 6 print( simple_eval('10 ** 123') ) # 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 print(simple_eval("21 + 19 / 7 + (8 % 3) ** 9")) # 535.7142857142857 print() # Call methods print(simple_eval("'1,2,3,4'.split(',')")) # ['1', '2', '3', '4'] print(simple_eval("'+'.join('1234')")) # 1+2+3+4 print() from simpleeval import EvalWithCompoundTypes print(EvalWithCompoundTypes().eval('list("Hello").count("l")')) # 2 print(simple_eval('list("Hello").count("l")', functions={'list': list})) # 2 print() # User functions print(simple_eval("square(11)", functions={"square": lambda x: x * x})) # 121 import math print( simple_eval("abs(sin(3) * cos(3))", functions={ 'sin': math.sin, 'cos': math.cos, 'abs': abs })) # 0.13970774909946293