def addAction(self, id, name, action, condition, permission, category, visible=1, REQUEST=None): """ Adds an action to the list. """ al = self._actions[:] if not name: raise ValueError('A name is required.') if action: a_expr = Expression(text=str(action)) else: a_expr = '' if condition: c_expr = Expression(text=str(condition)) else: c_expr = '' al.append( ActionInformation(id=str(id), title=str(name), action=a_expr, condition=c_expr, permissions=(str(permission), ), category=str(category), visible=int(visible))) self._actions = al if REQUEST is not None: return self.manage_editActionsForm(REQUEST, manage_tabs_message='Added.')
def __init__(self, node, context, size=None): self.node = node numColons = len(node.getChildrenByType('COLON')) cursor = 1 self.step = 1 if node.children[cursor].type == 'expression': self.start = Expression(node.children[cursor]).evaluate(context) cursor += 1 else: self.start = 0 cursor += 1 if node.children[cursor].type == 'expression': if numColons > 1: self.step = Expression(node.children[cursor]).evaluate(context) cursor += 1 else: self.end = Expression(node.children[cursor]).evaluate(context) elif node.children[cursor].type == 'COLON': self.step = 1 else: self.end = size if numColons > 1: cursor += 1 if node.children[cursor].type == 'expression': self.end = Expression(node.children[cursor].type).evaluate(context) else: self.end = size
def edit(self, id=_unchanged, title=_unchanged, description=_unchanged, category=_unchanged, condition=_unchanged, permissions=_unchanged, priority=_unchanged, visible=_unchanged, action=_unchanged): """Edit the specified properties. """ if id is not _unchanged: self.id = id if title is not _unchanged: self.title = title if description is not _unchanged: self.description = description if category is not _unchanged: self.category = category if condition is not _unchanged: if condition and isinstance(condition, basestring): condition = Expression(condition) self.condition = condition if permissions is not _unchanged: self.permissions = permissions if priority is not _unchanged: self.priority = priority if visible is not _unchanged: self.visible = visible if action is not _unchanged: if action and isinstance(action, basestring): action = Expression(action) self.setActionExpression(action)
def __init__(self, policy_id, predicate='', mtime_func='', max_age_secs=None, no_cache=0, no_store=0, must_revalidate=0, vary=''): if not predicate: predicate = 'python:1' if not mtime_func: mtime_func = 'content/modified' if max_age_secs is not None: max_age_secs = int(max_age_secs) self._policy_id = policy_id self._predicate = Expression(text=predicate) self._mtime_func = Expression(text=mtime_func) self._max_age_secs = max_age_secs self._no_cache = int(no_cache) self._no_store = int(no_store) self._must_revalidate = int(must_revalidate) self._vary = vary
def parse_file(file_name, base_des_regles, base_des_faits): file = open(file_name, "r") input = file.read() input = input.split('\n') for line in input: if len(line): if not ('si ' in line or 'Si ' in line): base_des_faits.append(Fait(Expression(line))) else: regle = line[3:] regle = regle.split(' alors ') conditions = [] expressions = [] tableau = regle[0].split(' et ') for premisse in tableau: if bool( re.compile(r".*(=|<|>|<=|>=|!=|==).*").match( premisse)): conditions.append(premisse) else: expressions.append(Expression(premisse)) regle1 = regle[1][:len(regle[1]) - 1] regex = re.sub(r"(\w+)\(", r"['\1,", regle1) regex = regex.replace(",", "','") regex = regex + ']' regex = regex.replace("]", "']") conclusion = Expression(eval(regex)) base_des_regles.append( Regle(expressions, conditions, conclusion))
def __init__(self, id, title='', description='', category='object', condition='', permissions=(), priority=10, visible=1, action=''): """ Set up an instance. """ if condition and type(condition) == type(''): condition = Expression(condition) if action and type(action) == type(''): action = Expression(action) self.id = id self.title = title self.description = description self.category = category self.condition = condition self.permissions = permissions self.priority = priority self.visible = visible self.setActionExpression(action)
def changeActions(self, properties=None, REQUEST=None): """ Changes the _actions. """ if properties is None: properties = REQUEST actions = self._actions[:] for idx in range(len(actions)): s_idx = str(idx) action = { 'id': str(properties.get('id_' + s_idx, '')), 'name': str(properties.get('name_' + s_idx, '')), 'action': str(properties.get('action_' + s_idx, '')), 'condition': str(properties.get('condition_' + s_idx, '')), 'permissions': (properties.get('permission_' + s_idx, ()), ), 'category': str(properties.get('category_' + s_idx, 'object')), 'visible': properties.get('visible_' + s_idx, 0), } if not action['name']: raise ValueError('A name is required.') # DM: do not override shared element! # a = actions[idx] class Empty: pass a = Empty() a.id = action['id'] a.title = action['name'] if action['action'] is not '': a._action = Expression(text=action['action']) else: a._action = '' if action['condition'] is not '': a.condition = Expression(text=action['condition']) else: a.condition = '' a.permissions = action['permissions'] a.category = action['category'] a.visible = action['visible'] # DM - unshare! severe sharing bug via class variable "_actions" actions[idx] = ActionInformation( id=a.id, title=a.title, action=a._action, condition=a.condition, permissions=a.permissions, category=a.category, visible=a.visible, ) self._actions = actions if REQUEST is not None: return self.manage_editActionsForm( REQUEST, manage_tabs_message='Actions changed.')
def Execution(): if int(radioList.choice.get()) == 1: resultat = Unifcation.unifier(Expression(Expression1.content.get()), Expression(Expression2.content.get())) if resultat == None: tlog.insert(END, "Pas d'unifciation Possible" + "\n") else: tlog.insert( END, "La substitution géneralle pour ces deux expressions est :" + "\n") tlog.insert(END, str(resultat) + "\n") if int(radioList.choice.get()) == 2: FileHandler = fileImport1.path.replace("'", '') base_des_regles = [] base_des_faits = [] parse_file(FileHandler, base_des_regles, base_des_faits) LogFile, conclusions = genereOperateursApplicables( base_des_regles, base_des_faits) for e in LogFile: tlog.insert(END, e + "\n") if int(radioList.choice.get()) == 3: FileHandler = fileImport1.path.replace("'", '') base_des_regles = [] base_des_faits = [] parse_file(FileHandler, base_des_regles, base_des_faits) limit = iterativeLimitedDepthSearch(base_des_regles, base_des_faits, Expression(BUT.content.get()), 0) tlog.insert(END, "Le but se trouve a la profondeur :" + str(limit) + "\n") if int(radioList.choice.get()) == 4: FileHandler = fileImport1.path.replace("'", '') base_des_regles = [] base_des_faits = [] parse_file(FileHandler, base_des_regles, base_des_faits) path = astar(base_des_regles, base_des_faits[0], Expression(BUT.content.get()), 1) tlog.insert( END, "Solution Path according to the first heuristic is :" + "\n") print("Solution Path according to the first heuristic is :" + "\n") for e in path: print(e) tlog.insert(END, str(e) + "\n") if int(radioList.choice.get()) == 5: FileHandler = fileImport1.path.replace("'", '') base_des_regles = [] base_des_faits = [] parse_file(FileHandler, base_des_regles, base_des_faits) path = astar(base_des_regles, base_des_faits[0], Expression(BUT.content.get()), 2) tlog.insert( END, "Solution Path according to the first heuristic is :" + "\n") print("Solution Path according to the second heuristic is :" + "\n") for e in path: print(e) tlog.insert(END, str(e) + "\n")
def getexprs(stat): tkns = stat.split(" ") if len(tkns) == 1: return None, None ft, op, vl = getcnd(tkns[0]) exp1 = Expression(ft, op, vl) ft, op, vl = getcnd(tkns[2]) exp2 = Expression(ft, op, vl) return [exp1, int(tkns[1])], [exp2, int(tkns[3])]
def __add__(self, other): self.sorted = False if isinstance(other, (float, int)): self.expressions.append(Expression(other)) elif iterable(other): c = other[0] f = other[1] self.expressions.append(Expression(c, f)) elif isinstance(other, Expression): self.expressions.append(other) return self
def ut_01(): e1 = Expression() e2 = Expression() a1 = [Term(10, 1), Term(-20, 2), Term(30, -3)] a2 = [Term(5, 1), Term(6, 2), Term(7, -3)] e1.set_exp(a1) e2.set_exp(a2) e3 = e1 + e2 e3.print2()
def Expression(self): tok = self.peek().type if tok == "NEW": self.expect("NEW") obj = self.Type() return Expression(obj=obj) elif (tok == "NUMBER" or tok == "IDENTIFIER"): term = self.Calc() return Expression(term=term) elif tok == "STRING" or tok == "LBRACK": term = self.Term() return Expression(term=term) else: raise Exception("Expected a Type or Term but got", tok)
def test_expressions(): w = numpy.transpose(numpy.matrix(numpy.random.random((1, numFeatures)))) exp = Expression(binaryClassObjective, binaryClassObjectiveStochasticGradient, binaryClassObjectiveHessianVectorProduct, numFeatures) print(exp.get_value(w)) print(exp.get_subgrad(w, 1))
def evaluate_expression(self): exp_str = None # If invalid input, keep prompting for input while exp_str is None: exp_str = input( '\nPlease enter the expression you want to evaluate:\n') try: exp_str = exp_str.replace(' ', '') expression = Expression(exp_str) expression.parse_tree() except Exception as e: exp_str = None print('Invalid Expression, ' + str(e)) # checking for print order orderprint_selection = self.__print_order_selection() if orderprint_selection == "1": expression.print_preorder() elif orderprint_selection == "2": expression.print_inorder() elif orderprint_selection == "3": expression.print_postorder() # writes into a history file with open('./history.txt', 'a') as history_file: history_file.write("Expression {} evaluates to: {:.3f}\n".format( str(expression), expression.val)) with open('./input/input_history.txt', 'a') as history_file: history_file.write('\n' + str(expression)) # printing print("\nExpression evaluates to:\n{:.3f}".format(expression.val))
def __parsefile(self, input_file, sort_method, ascending_check, sort_by_value): # checks for sorting method and creates object accordingly if sort_method == "1": exp_list = SortedList(ascending_check) elif sort_method == "2": exp_list = [] for i in range(len(input_file)): try: input_file[i].replace(' ', '') expression = Expression(input_file[i]) expression.parse_tree() expression.set_sort_value(sort_by_value) except Exception as e: print("\nInvalid expression at line " + str(i + 1) + ". Skipping expression") print(e) continue if sort_method == "1": exp_list.insert(expression) elif sort_method == "2": exp_list.append(expression) if sort_method == "2": sort_expressions(exp_list, ascending_check) return exp_list
def changeFromProperties(self, props): ''' Returns 1 if changes were specified. ''' if props is None: return 0 res = 0 s = props.get('guard_permissions', None) if s: res = 1 p = [permission.strip() for permission in s.split(';')] self.permissions = tuple(p) s = props.get('guard_roles', None) if s: res = 1 r = [role.strip() for role in s.split(';')] self.roles = tuple(r) s = props.get('guard_groups', None) if s: res = 1 g = [group.strip() for group in s.split(';')] self.groups = tuple(g) s = props.get('guard_expr', None) if s: res = 1 self.expr = Expression(s) return res
def test_logical_ops(self): """ Test for the && and || operators precedence""" # Would evaluate to false if precedence was wrong self.assertTrue( Expression( 'PASS == PASS || PASS != NOTPASS && PASS == NOTPASS').evaluate( self.c))
def setActionExpression(self, action): if action and isinstance(action, basestring): if (not action.startswith('string:') and not action.startswith('python:')): action = 'string:${object_url}/%s' % action action = Expression(action) self.action = action
def _setPropValue(self, id, value): self._wrapperCheck(value) if isinstance(value, list): value = tuple(value) setattr(self, id, value) if id.endswith('_expr'): setattr(self, '%s_object' % id, Expression(value))
def setActionExpression(self, action): if action and type(action) is StringType: if not action.startswith('python:') and not action.startswith( 'string:'): action = 'string:${object_url}/%s' % action action = Expression(action) self.action = action
def evaluate(self, indexIdentifierNode): child = indexIdentifierNode.getChildByType('indexIdentifier') if child is not None: sibling = indexIdentifierNode.getChildByType('indexIdentifier', 1) evaluatedLeft = self.evaluate(child) evaluatedRight = self.evaluate(sibling) return CReg.concat(evaluatedLeft, evaluatedRight) else: identifier = indexIdentifierNode.getChildByType('Identifier').text value = self.getValue(identifier) if isinstance(value, CReg): creg = value rangeDefinitionNode = indexIdentifierNode.getChildByType('rangeDefinition') expressionListNode = indexIdentifierNode.getChildByType('expressionList') if rangeDefinitionNode is not None: rangeDefinition = Range(rangeDefinitionNode, self, creg.size) return creg.getRange(rangeDefinition) elif expressionListNode is not None: expressionNodes = expressionListNode.getChildrenByType('expression') expressions = [Expression(node).evaluate(self.store) for node in expressionNodes] return creg.getList(expressions) else: return creg else: return value
def setProperties(self, description, default_value='', default_expr='', for_catalog=0, for_status=0, update_always=0, props=None, REQUEST=None): ''' ''' self.description = str(description) self.default_value = str(default_value) if default_expr: self.default_expr = Expression(default_expr) else: self.default_expr = None g = Guard() if g.changeFromProperties(props or REQUEST): self.info_guard = g else: self.info_guard = None self.for_catalog = not not for_catalog # Pure boolean value self.for_status = not not for_status self.update_always = not not update_always if REQUEST is not None: return self.manage_properties(REQUEST, 'Properties changed.')
def markAsMeasured(self, indexIdentifierNode, context): child = indexIdentifierNode.getChildByType('indexIdentifier', 0) if child is not None: sibling = indexIdentifierNode.getChildByType('indexIdentifier', 1) self.markAsMeasured(child, context) self.markAsMeasured(sibling, context) else: identifier = indexIdentifierNode.getChildByType('Identifier').text qreg = self.quantumRegisters[identifier] rangeDefinitionNode = indexIdentifierNode.getChildByType('rangeDefinition') if rangeDefinitionNode is not None: rangeDefinition = Range(rangeDefinitionNode, context, qreg.size) if rangeDefinition.step == 1 and ( not isinstance(rangeDefinition.start, int) or not isinstance(rangeDefinition.end, int)): qubitRange = qreg.getRange(rangeDefinition.start, rangeDefinition.end) self.__addToEffectiveQubits(qubitRange) else: for i in range(rangeDefinition.start, rangeDefinition.end, rangeDefinition.step): qubit = qreg.getQubit(i) self.__addToEffectiveQubits(qubit) else: expressionListNode = indexIdentifierNode.getChildByType('expressionList') if expressionListNode is not None: expressionNodes = expressionListNode.getChildrenByType('expression') for expressionNode in expressionNodes: expression = Expression(expressionNode).evaluate(context) qubit = qreg.getQubit(expression) self.__addToEffectiveQubits(qubit) else: qubits = qreg.getAll() for qubit in qubits: self.__addToEffectiveQubits(qubit)
def evaluate_language(meanings, universe_size, target_utility): expression = Expression('test_expression', lambda model: True) language = [ EvaluatedExpression(expression, meaning) for meaning in meanings ] assert math.isclose(measure_informativeness(language, universe_size), target_utility)
def set(self, key: str, value=None, type=None): if key in self.store.keys(): if self.store[key]['type'] is not None and type is None: type = self.store[key]['type'] if type.typeLiteral in ['bit', 'creg'] and not isinstance(value, CReg): size = Expression(type.designatorExpr1).evaluate(self.store) value = CReg.fromSymbolAndSize(key, value, size) self.store[key] = {'value': value, 'type': type}
def __init__( self , policy_id , predicate='' , mtime_func='' , max_age_secs=None , no_cache=0 , no_store=0 , must_revalidate=0 , vary='' , etag_func='' , s_max_age_secs=None , proxy_revalidate=0 , public=0 , private=0 , no_transform=0 , enable_304s=0 ): if not predicate: predicate = 'python:1' if not mtime_func: mtime_func = 'object/modified' if max_age_secs is not None: max_age_secs = int( max_age_secs ) if s_max_age_secs is not None: s_max_age_secs = int( s_max_age_secs ) self._policy_id = policy_id self._predicate = Expression( text=predicate ) self._mtime_func = Expression( text=mtime_func ) self._max_age_secs = max_age_secs self._s_max_age_secs = s_max_age_secs self._no_cache = int( no_cache ) self._no_store = int( no_store ) self._must_revalidate = int( must_revalidate ) self._proxy_revalidate = int( proxy_revalidate ) self._public = int( public ) self._private = int( private ) self._no_transform = int( no_transform ) self._vary = vary self._etag_func = Expression( text=etag_func ) self._enable_304s = int ( enable_304s )
def main(): # data = [70, 30, 25, 80, 60, 50, 75, 10, 45] # forest = Stack() # for i in data: # forest.push(i) # print(forest) post_exp = Expression().Postfix() print(post_exp.evaluation(['5', '6', '2', '+', '*', '12', '4', '/', '-']))
def ChercherUnificationPourRegle(base_des_faits, regle, i, Result, Unif): Test = False if i == len(regle.presmisses.expressions): conditionsValid = True for c in regle.presmisses.conditions: if eval(c) == False: conditionsValid = False return False break if conditionsValid == True: Result.append(regle) Result.append(Unif) Result = [] Unif = [] return True for f in base_des_faits: Uni = Unifcation.unifier(f.exp, regle.presmisses.expressions[i]) if (Uni != None): Test = True premisses = [] conds = [] for e in regle.presmisses.expressions: premisses.append(Expression(e.expression)) for e in regle.presmisses.conditions: conds.append(e) regleCopie = Regle(premisses, conds, Expression(regle.conclusion.expression)) for j in range(0, len(regleCopie.presmisses.expressions)): regleCopie.presmisses.expressions[j].substitute(Uni) for k in range(0, len(regleCopie.presmisses.conditions)): for sub in Uni: regleCopie.presmisses.conditions[ k] = regleCopie.presmisses.conditions[k].replace( sub[0], sub[1]) for j in range(0, len(regleCopie.conclusion.expression)): regleCopie.conclusion.substitute(Uni) test = ChercherUnificationPourRegle(base_des_faits, regleCopie, i + 1, Result, Unif) if test == True: Uni = Uni[::-1] Unif.append(Uni) return Test
def getActionExpression(self): """ Return the text of the TALES expression for our URL. """ action = self._getActionObject() expr = action and action.text or '' if expr and isinstance(expr, basestring): if (not expr.startswith('string:') and not expr.startswith('python:')): expr = 'string:${object_url}/%s' % expr self.action = Expression(expr) return expr
def getActionExpression(self): """ Return the text of the TALES expression for our URL. """ action = self._getActionObject() expr = action and action.text or '' if expr and type(expr) is StringType: if not expr.startswith('python:') and not expr.startswith( 'string:'): expr = 'string:%s' % expr self.action = Expression(expr) return expr